API trước đây chỉ nhận đường dẫn HDFS từ Airflow. Thêm endpoint
multipart/form-data nhận thẳng file PDF, vẫn chạy bất đồng bộ: trả 202 kèm
job_id và result_url, worker xử lý nền, client lấy dla-document-bundle ở
GET /jobs/{job_id}/result hoặc qua callback.
- File upload ghi xuống IDP_DATA_DIR/uploads theo sha256 nội dung nên gửi lại
cùng request_id trả cùng job_id; file được xoá khi không còn job nào dùng.
- Thêm cột filename/source_kind để bundle giữ đúng tên file gốc thay vì tên
đã băm.
- IDP_RUN_WORKER=1 chạy worker trong process API cho triển khai một host.
- IDP_OCR_BACKEND=pdf_text dựng bundle từ text layer của PDF để chạy thử toàn
bộ luồng khi chưa serve được model.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
315 lines
13 KiB
Python
315 lines
13 KiB
Python
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.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)
|
|
|
|
|
|
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 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)
|
|
worker = Worker(settings)
|
|
assert worker.coordinator_once()
|
|
for _ in range(3):
|
|
page = worker.store.claim_page(settings.lease_seconds, settings.ocr_workers)
|
|
assert page
|
|
worker.process_page(page)
|
|
assert worker.coordinator_once()
|
|
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"])
|
|
|
|
|
|
def drain(worker, settings):
|
|
"""Chạy hết job đang chờ: prepare, mọi trang, rồi finalize."""
|
|
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)
|
|
assert worker.coordinator_once()
|
|
|
|
|
|
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"]
|
|
# 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.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": "<p>[no extractable text]</p>"}]
|
|
|
|
|
|
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"),
|
|
('<div data-label="Paragraph" data-bbox="0 0 1200 20">x</div>', "stop"),
|
|
('<div data-label="Paragraph" data-bbox="0 0 20 20">x</div>', "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":
|
|
'<div data-label="Paragraph" data-bbox="1 1 500 500">Test</div>'}}]}
|
|
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),
|
|
"callback_url": f"http://127.0.0.1:{server.server_port}/callback"})
|
|
assert reply.status_code == 202
|
|
worker = Worker(settings)
|
|
worker.coordinator_once()
|
|
page = worker.store.claim_page(settings.lease_seconds, settings.ocr_workers)
|
|
worker.process_page(page)
|
|
worker.coordinator_once()
|
|
assert client.get(f"/jobs/{reply.json()['job_id']}").json()["callback_state"] == "delivered"
|
|
assert callbacks[0]["status"] == "done"
|
|
assert callbacks[0]["output"]["schema"] == "dla-document-bundle"
|
|
assert callbacks[0]["output"]["pages"][0]["status"] == "done"
|
|
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")
|