import base64 import json from dataclasses import replace from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from threading import Thread from uuid import uuid4 import pymupdf from Crypto.Cipher import DES from fastapi.testclient import TestClient from idp_service.api import create_app from idp_service.config import Settings from idp_service.db import Store from idp_service.decrypt import DEFAULT_KEY_HEX, DecryptionError, prepare_pdf from idp_service import kie from idp_service.ocr import InvalidOutput, validate_response from idp_service.worker import Worker from idp_service.webhdfs import download_pdf def settings_for(tmp_path): return replace(Settings(), data_dir=tmp_path / "data", storage="local", ocr_workers=2, poll_seconds=0.01, kie_enabled=False) def make_pdf(path: Path, count=3): document = pymupdf.open() for index in range(count): page = document.new_page() page.insert_text((72, 72), f"Page {index + 1}") document.save(path) document.close() def drain(worker, settings): """Chạy hết job đang chờ: prepare, mọi trang, extract, rồi finalize và callback.""" assert worker.coordinator_once() while True: page = worker.store.claim_page(settings.lease_seconds, settings.ocr_workers) if not page: break worker.process_page(page) job = worker.store.claim_extract(settings.lease_seconds, settings.ocr_workers) if job: worker.extract(job) assert worker.coordinator_once() def test_api_idempotency_and_end_to_end(tmp_path, monkeypatch): settings = settings_for(tmp_path) source = tmp_path / "input.pdf" make_pdf(source) app = create_app(settings) request = {"request_id": str(uuid4()), "file_path": str(source), "file_type": "application/pdf"} with TestClient(app) as client: first = client.post("/process", json=request) assert first.status_code == 202 second = client.post("/process", json=request) assert second.status_code == 202 assert second.json()["job_id"] == first.json()["job_id"] assert second.headers["X-Idempotent-Replay"] == "true" assert client.post("/process", json={**request, "file_path": "/other.pdf"}).status_code == 409 def fake_infer(settings, source, page_no, **kwargs): return {"width": 100, "height": 100, "blocks": [ {"label": "Paragraph", "bbox": [1, 1, 500, 500], "html": f"Page {page_no}"}]} monkeypatch.setattr("idp_service.worker.infer_page", fake_infer) drain(Worker(settings), settings) status = client.get(f"/jobs/{first.json()['job_id']}").json() assert status["status"] == "completed" assert status["completed_pages"] == 3 assert status["result_available"] is True bundle = client.get(f"/jobs/{first.json()['job_id']}/result").json() assert len(bundle["pages"]) == 3 assert all(page["status"] == "done" for page in bundle["pages"]) # IDP_KIE_ENABLED=0: bundle vẫn giữ đủ khung extraction với các trường null. assert bundle["extraction"] == {"schema": kie.SCHEMA_NAME, "status": "skipped", "fields": kie.empty_answer(), "error": None} def test_upload_pdf_returns_bundle_without_gpu(tmp_path): settings = replace(settings_for(tmp_path), ocr_backend="pdf_text") source = tmp_path / "Giấy chứng nhận.pdf" make_pdf(source, count=2) app = create_app(settings) with TestClient(app) as client: with source.open("rb") as handle: reply = client.post("/parse", files={"file": (source.name, handle, "application/pdf")}) assert reply.status_code == 202 job_id = reply.json()["job_id"] assert reply.json()["result_url"] == f"/jobs/{job_id}/result" assert client.get(f"/jobs/{job_id}/result").status_code == 409 drain(Worker(settings), settings) assert client.get(f"/jobs/{job_id}").json()["status"] == "completed" bundle = client.get(f"/jobs/{job_id}/result").json() assert bundle["schema"] == "dla-document-bundle" assert bundle["source"] == {"filename": "Giấy chứng nhận.pdf", "media_type": "application/pdf", "page_count": 2, "render_dpi": 200} assert bundle["document_id"].startswith("doc_") page = bundle["pages"][0] assert page["page_id"] == f"{bundle['document_id']}/p001" assert page["width"] > 0 and page["height"] > 0 block = page["blocks"][0] assert block["block_id"] == f"{page['page_id']}/b000" assert block["label"] in {"Paragraph", "Image"} assert all(0 <= value <= 1000 for value in block["bbox"]) assert block["outline_no"] == "0.1" assert bundle["outline"][0]["block_ids"][0] == block["block_id"] assert bundle["extraction"]["status"] == "skipped" # Upload đã dedupe theo sha256 được dọn sau khi finalize. assert list(settings.upload_dir.glob("*.pdf")) == [] def test_upload_rejects_non_pdf_and_replays_same_request_id(tmp_path): settings = settings_for(tmp_path) source = tmp_path / "input.pdf" make_pdf(source, count=1) request_id = str(uuid4()) app = create_app(settings) with TestClient(app) as client: assert client.post("/parse", files={"file": ("note.txt", b"hello", "text/plain")}).status_code == 422 assert client.post("/parse", files={"file": ("empty.pdf", b"", "application/pdf")}).status_code == 422 content = source.read_bytes() first = client.post("/parse", files={"file": ("input.pdf", content, "application/pdf")}, data={"request_id": request_id}) second = client.post("/parse", files={"file": ("input.pdf", content, "application/pdf")}, data={"request_id": request_id}) assert second.json()["job_id"] == first.json()["job_id"] assert second.headers["X-Idempotent-Replay"] == "true" conflict = client.post("/parse", files={"file": ("other.pdf", content, "application/pdf")}, data={"request_id": request_id}) assert conflict.status_code == 409 # Job đầu vẫn giữ được file của nó sau khi request xung đột bị từ chối. assert len(list(settings.upload_dir.glob("*.pdf"))) == 1 def test_page_retry_then_partial_failure(tmp_path, monkeypatch): settings = replace(settings_for(tmp_path), max_page_attempts=2) source = tmp_path / "bad.pdf" make_pdf(source, count=1) store = Store(settings.db_path) job, _ = store.create_job(str(uuid4()), str(source), None, None, 100) worker = Worker(settings, store) worker.coordinator_once() def fail(*args, **kwargs): raise InvalidOutput("Model reached max_tokens", truncated=True) monkeypatch.setattr("idp_service.worker.infer_page", fail) first = store.claim_page(settings.lease_seconds, settings.ocr_workers) worker.process_page(first) with store.tx() as db: db.execute("UPDATE pages SET next_at=0 WHERE job_id=?", (job["id"],)) second = store.claim_page(settings.lease_seconds, settings.ocr_workers) assert second["penalize_repetition"] == 1 worker.process_page(second) worker.extract(store.claim_extract(settings.lease_seconds, settings.ocr_workers)) worker.coordinator_once() result = store.get_job(job["id"]) assert result["status"] == "partial_failed" assert result["failed_pages"] == 1 bundle = json.loads(result["result_json"]) assert bundle["pages"][0]["status"] == "failed" def test_pdf_text_backend_labels_pages_without_text(tmp_path): from idp_service.ocr import extract_text_blocks blank = tmp_path / "blank.pdf" document = pymupdf.open() document.new_page() document.save(blank) document.close() result = extract_text_blocks(blank, 1) assert result["blocks"] == [{"label": "Image", "bbox": [0, 0, 1000, 1000], "html": "

[no extractable text]

"}] KIE_ANSWER = { "document_type": "QUYẾT ĐỊNH", "document_number": "123/QĐ-UBND", "issued_date": "09/09/2026", "issuing_authority": "ỦY BAN NHÂN DÂN TỈNH BẮC NINH", "title": "Về việc phê duyệt quy hoạch", "signer": {"name": "Nguyễn Văn A", "position": "KT. CHỦ TỊCH"}, } def model_server(kie_content): """Server giả đóng vai vLLM: nhận cả prompt DLA lẫn prompt KIE, và nhận callback.""" callbacks, kie_requests = [], [] class Handler(BaseHTTPRequestHandler): def do_POST(self): body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) if self.path == "/v1/chat/completions": content = body["messages"][0]["content"] assert content[0]["image_url"]["url"].startswith("data:image/png;base64,") if content[-1]["text"].startswith("Trích xuất thông tin"): kie_requests.append(body) answer = {"choices": [{"finish_reason": "stop", "message": {"content": kie_content}}]} else: answer = {"choices": [{"finish_reason": "stop", "message": {"content": '
Test
'}}]} else: callbacks.append(body) answer = {"ok": True} data = json.dumps(answer).encode() self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def log_message(self, *_): pass return ThreadingHTTPServer(("127.0.0.1", 0), Handler), callbacks, kie_requests def test_extract_fixed_schema_end_to_end_and_callback(tmp_path): server, callbacks, kie_requests = model_server("```json\n" + json.dumps(KIE_ANSWER, ensure_ascii=False) + "\n```") thread = Thread(target=server.serve_forever, daemon=True) thread.start() try: url = f"http://127.0.0.1:{server.server_port}/v1/chat/completions" settings = replace(settings_for(tmp_path), ocr_url=url, kie_enabled=True, kie_url=url) source = tmp_path / "quyet-dinh.pdf" make_pdf(source, count=2) app = create_app(settings) with TestClient(app) as client: reply = client.post("/parse", files={"file": ("quyet-dinh.pdf", source.read_bytes(), "application/pdf")}, data={"callback_url": f"http://127.0.0.1:{server.server_port}/callback"}) job_id = reply.json()["job_id"] assert client.get(f"/jobs/{job_id}/extraction").status_code == 409 drain(Worker(settings), settings) # Một lượt KIE cho cả tài liệu, gửi kèm ảnh mọi trang. assert len(kie_requests) == 1 assert len(kie_requests[0]["messages"][0]["content"]) == 3 assert kie_requests[0]["model"] == settings.kie_model extraction = client.get(f"/jobs/{job_id}/extraction").json() assert extraction["status"] == "done" assert extraction["schema"] == kie.SCHEMA_NAME assert extraction["fields"] == KIE_ANSWER assert client.get(f"/jobs/{job_id}").json()["extract_status"] == "done" bundle = client.get(f"/jobs/{job_id}/result").json() assert bundle["extraction"]["fields"] == KIE_ANSWER assert bundle["extraction"]["status"] == "done" output = callbacks[0]["conf"]["output"] assert output["extraction"]["fields"] == KIE_ANSWER assert len(output["extraction"]["pages"]) == 2 finally: server.shutdown() server.server_close() thread.join() def test_extract_retries_bad_answer_then_gives_up(tmp_path): # Model trả JSON nhưng đặt khoá tiếng Việt: coi như hỏng chứ không im lặng trả null. server, _, kie_requests = model_server('{"loai_van_ban": "QUYẾT ĐỊNH"}') thread = Thread(target=server.serve_forever, daemon=True) thread.start() try: url = f"http://127.0.0.1:{server.server_port}/v1/chat/completions" settings = replace(settings_for(tmp_path), ocr_url=url, kie_enabled=True, kie_url=url, max_kie_attempts=2) source = tmp_path / "input.pdf" make_pdf(source, count=1) store = Store(settings.db_path) job, _ = store.create_job(str(uuid4()), str(source), None, None, 100) worker = Worker(settings, store) worker.coordinator_once() worker.process_page(store.claim_page(settings.lease_seconds, settings.ocr_workers)) for _ in range(settings.max_kie_attempts): with store.tx() as db: db.execute("UPDATE jobs SET extract_next_at=0 WHERE id=?", (job["id"],)) worker.extract(store.claim_extract(settings.lease_seconds, settings.ocr_workers)) assert len(kie_requests) == settings.max_kie_attempts worker.coordinator_once() # Extract hỏng không làm hỏng job: bundle vẫn completed, trường để null kèm lỗi. result = store.get_job(job["id"]) assert result["status"] == "completed" bundle = json.loads(result["result_json"]) assert bundle["extraction"]["status"] == "failed" assert bundle["extraction"]["fields"] == kie.empty_answer() assert bundle["extraction"]["error"] == "Đáp án không có trường nào của schema" finally: server.shutdown() server.server_close() thread.join() def test_kie_prompt_schema_and_answer_shape(): prompt = kie.render_prompt(3) assert prompt.startswith("Trích xuất thông tin từ ảnh tài liệu (3 trang, ảnh theo thứ tự trang)") assert '- "signer" (object): Người ký ban hành ở cuối văn bản\n - "name"' in prompt assert [line for line in prompt.splitlines() if line.startswith('- "')][:5] == [ line for line in kie.render_fields(kie.SCHEMA) if line.startswith('- "')][:5] assert kie.render_prompt(1).startswith("Trích xuất thông tin từ ảnh tài liệu và") # Khoá thừa bị bỏ, khoá thiếu thành null, chuỗi rỗng và mảng chuỗi được làm sạch. answer = kie.normalize_answer({"document_type": ["QUYẾT", "ĐỊNH"], "document_number": " ", "signer": {"name": "Nguyễn Văn A"}, "ghi_chu": "thừa"}) assert answer == {"document_type": "QUYẾT\nĐỊNH", "document_number": None, "issued_date": None, "issuing_authority": None, "title": None, "signer": {"name": "Nguyễn Văn A", "position": None}} assert list(answer) == [field["key"] for field in kie.SCHEMA] # Tài liệu dài chỉ gửi các trang đầu và trang cuối (nơi có người ký). assert kie.select_pages(3, 5) == [1, 2, 3] assert kie.select_pages(20, 5) == [1, 2, 3, 4, 20] def test_rejects_truncated_plain_text_and_invalid_bbox(): def response(content, finish="stop"): return {"choices": [{"finish_reason": finish, "message": {"content": content}}]} for content, finish in [("text only", "stop"), ('
x
', "stop"), ('
x
', "length")]: try: validate_response(response(content, finish)) except InvalidOutput: pass else: raise AssertionError("Invalid output was accepted") def test_real_http_ocr_and_callback(tmp_path): callbacks = [] class Handler(BaseHTTPRequestHandler): def do_POST(self): size = int(self.headers["Content-Length"]) body = json.loads(self.rfile.read(size)) if self.path == "/v1/chat/completions": assert body["messages"][0]["content"][0]["image_url"]["url"].startswith("data:image/png;base64,") answer = {"choices": [{"finish_reason": "stop", "message": {"content": '
Test
'}}]} else: callbacks.append(body) answer = {"ok": True} data = json.dumps(answer).encode() self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def log_message(self, *_): pass server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) thread = Thread(target=server.serve_forever, daemon=True) thread.start() try: settings = replace(settings_for(tmp_path), ocr_url=f"http://127.0.0.1:{server.server_port}/v1/chat/completions") source = tmp_path / "input.pdf" make_pdf(source, count=1) app = create_app(settings) with TestClient(app) as client: reply = client.post("/process", json={"request_id": str(uuid4()), "file_path": str(source), "dag_run_id": "callback_test_001", "callback_url": f"http://127.0.0.1:{server.server_port}/callback"}) assert reply.status_code == 202 drain(Worker(settings), settings) assert client.get(f"/jobs/{reply.json()['job_id']}").json()["callback_state"] == "delivered" assert callbacks[0]["dag_run_id"] == "callback_test_001" assert set(callbacks[0]) == {"dag_run_id", "conf"} conf = callbacks[0]["conf"] assert conf["request_id"] == reply.json()["request_id"] assert conf["job_id"] == reply.json()["job_id"] assert conf["status"] == "done" assert conf["output"]["canonical"]["schema"] == "dla-document-bundle" assert conf["output"]["canonical"]["pages"][0]["status"] == "done" images = conf["output"]["extraction"]["pages"] assert len(images) == 1 assert images[0]["page_no"] == 1 assert images[0]["media_type"] == "image/png" assert base64.b64decode(images[0]["data_base64"]).startswith(b"\x89PNG\r\n\x1a\n") finally: server.shutdown() server.server_close() thread.join() def test_global_gpu_limit_and_fairness_across_files(tmp_path): settings = settings_for(tmp_path) store = Store(settings.db_path) for name in ("a", "b"): source = tmp_path / f"{name}.pdf" make_pdf(source, count=2) store.create_job(str(uuid4()), str(source), None, None, 100) worker = Worker(settings, store) worker.coordinator_once() worker.coordinator_once() first = store.claim_page(settings.lease_seconds, global_limit=2) second = store.claim_page(settings.lease_seconds, global_limit=2) assert first["job_id"] != second["job_id"] assert store.claim_page(settings.lease_seconds, global_limit=2) is None def test_webhdfs_adapter_streams(tmp_path, monkeypatch): class FakeClient: def __init__(self): self.files = {"/input.pdf": b"pdf bytes"} def status(self, path, strict=True): if path not in self.files: return None return {"type": "FILE", "length": len(self.files[path])} def download(self, source, destination, overwrite=False): Path(destination).write_bytes(self.files[source]) client = FakeClient() monkeypatch.setattr("idp_service.webhdfs.make_client", lambda url: client) pdf = tmp_path / "input.pdf" download_pdf("http://namenode:9870", "/input.pdf", pdf, 100) assert pdf.read_bytes() == b"pdf bytes" def test_voffice_des_decryption_and_plain_pdf_passthrough(tmp_path): original = tmp_path / "original.pdf" make_pdf(original, count=2) content = original.read_bytes() padding = 8 - len(content) % 8 encrypted = tmp_path / "encrypted.bin" encrypted.write_bytes(DES.new(bytes.fromhex(DEFAULT_KEY_HEX), DES.MODE_ECB).encrypt( content + bytes([padding]) * padding)) decrypted = tmp_path / "decrypted.pdf" assert prepare_pdf(encrypted, decrypted, "auto", DEFAULT_KEY_HEX) is True assert decrypted.read_bytes() == content with pymupdf.open(decrypted) as document: assert document.page_count == 2 plain_input = tmp_path / "plain-input.pdf" plain_input.write_bytes(content) passthrough = tmp_path / "passthrough.pdf" assert prepare_pdf(plain_input, passthrough, "auto", DEFAULT_KEY_HEX) is False assert passthrough.read_bytes() == content def test_voffice_decryption_rejects_wrong_key(tmp_path): encrypted = tmp_path / "encrypted.bin" encrypted.write_bytes(b"12345678") try: prepare_pdf(encrypted, tmp_path / "out.pdf", "required", "0000000000000000") except DecryptionError: pass else: raise AssertionError("Invalid encrypted document was accepted")