Fix flow
This commit is contained in:
@@ -11,6 +11,8 @@ class Settings:
|
||||
hdfs_native_uri: str = os.getenv("IDP_HDFS_NATIVE_URI", "")
|
||||
api_key: str = os.getenv("IDP_API_KEY", "")
|
||||
callback_hosts: str = os.getenv("IDP_CALLBACK_HOSTS", "")
|
||||
callback_basic_user: str = os.getenv("IDP_CALLBACK_BASIC_USER", "")
|
||||
callback_basic_password: str = os.getenv("IDP_CALLBACK_BASIC_PASSWORD", "")
|
||||
ocr_url: str = os.getenv("IDP_OCR_URL", "http://localhost:9222/v1/chat/completions")
|
||||
ocr_model: str = os.getenv("IDP_OCR_MODEL", "chandra")
|
||||
ocr_backend: str = os.getenv("IDP_OCR_BACKEND", "http") # http hoặc pdf_text
|
||||
@@ -19,6 +21,7 @@ class Settings:
|
||||
kie_model: str = os.getenv("IDP_KIE_MODEL") or os.getenv("IDP_OCR_MODEL", "chandra")
|
||||
kie_max_pages: int = int(os.getenv("IDP_KIE_MAX_PAGES", "5"))
|
||||
kie_timeout: int = int(os.getenv("IDP_KIE_TIMEOUT", "300"))
|
||||
kie_max_tokens: int = int(os.getenv("IDP_KIE_MAX_TOKENS", "2048"))
|
||||
max_kie_attempts: int = int(os.getenv("IDP_MAX_KIE_ATTEMPTS", "3"))
|
||||
run_worker: bool = os.getenv("IDP_RUN_WORKER", "0").lower() in ("1", "true", "yes")
|
||||
ocr_workers: int = int(os.getenv("IDP_OCR_WORKERS", "64"))
|
||||
|
||||
@@ -140,7 +140,7 @@ def extract_document(settings: Settings, pdf_path: Path, page_count: int) -> dic
|
||||
payload = {
|
||||
"model": settings.kie_model,
|
||||
"messages": [{"role": "user", "content": content}],
|
||||
"max_tokens": 2048,
|
||||
"max_tokens": settings.kie_max_tokens,
|
||||
"temperature": 0.0,
|
||||
"top_p": 0.1,
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ import threading
|
||||
import time
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError
|
||||
from urllib.parse import quote, urlsplit, urlunsplit
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
import pymupdf
|
||||
@@ -35,6 +37,8 @@ class Worker:
|
||||
raise ValueError("OCR workers must be positive and lease must exceed OCR timeout")
|
||||
if settings.ocr_backend not in ("http", "pdf_text"):
|
||||
raise ValueError("IDP_OCR_BACKEND must be http or pdf_text")
|
||||
if bool(settings.callback_basic_user) != bool(settings.callback_basic_password):
|
||||
raise ValueError("Set both IDP_CALLBACK_BASIC_USER and IDP_CALLBACK_BASIC_PASSWORD")
|
||||
if settings.ocr_backend == "pdf_text":
|
||||
log.warning("IDP_OCR_BACKEND=pdf_text: bundle dựng từ text layer của PDF, không gọi model")
|
||||
|
||||
@@ -179,12 +183,20 @@ class Worker:
|
||||
},
|
||||
},
|
||||
}
|
||||
headers = {"Content-Type": "application/json", "Idempotency-Key": job["id"]}
|
||||
if self.settings.callback_basic_user:
|
||||
credentials = f"{self.settings.callback_basic_user}:{self.settings.callback_basic_password}"
|
||||
headers["Authorization"] = "Basic " + base64.b64encode(credentials.encode("utf-8")).decode("ascii")
|
||||
request = Request(job["callback_url"], data=json.dumps(payload).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json",
|
||||
"Idempotency-Key": job["id"]}, method="POST")
|
||||
with urlopen(request, timeout=10) as response:
|
||||
if not 200 <= response.status < 300:
|
||||
raise RuntimeError(f"Callback HTTP {response.status}")
|
||||
headers=headers, method="POST")
|
||||
try:
|
||||
with urlopen(request, timeout=10) as response:
|
||||
if not 200 <= response.status < 300:
|
||||
raise RuntimeError(f"Callback HTTP {response.status}")
|
||||
except HTTPError as exc:
|
||||
if exc.code != 409 or not self.airflow_run_matches(job["callback_url"], payload, headers):
|
||||
raise
|
||||
log.info("Airflow DAG run already exists for %s; callback confirmed", job["id"])
|
||||
self.store.callback_done(job["id"], job["callback_attempts"])
|
||||
shutil.rmtree(self.job_dir(job["id"]), ignore_errors=True)
|
||||
except Exception as exc:
|
||||
@@ -194,6 +206,25 @@ class Worker:
|
||||
if job["callback_attempts"] >= self.settings.max_callback_attempts:
|
||||
shutil.rmtree(self.job_dir(job["id"]), ignore_errors=True)
|
||||
|
||||
@staticmethod
|
||||
def airflow_run_matches(callback_url: str, payload: dict, headers: dict) -> bool:
|
||||
"""A 409 confirms delivery only when Airflow has this same job's DAG run."""
|
||||
parsed = urlsplit(callback_url)
|
||||
path = parsed.path.rstrip("/")
|
||||
segments = path.split("/")
|
||||
if len(segments) != 6 or segments[:4] != ["", "api", "v1", "dags"] or segments[5] != "dagRuns":
|
||||
return False
|
||||
run_url = urlunsplit((parsed.scheme, parsed.netloc,
|
||||
path + "/" + quote(payload["dag_run_id"], safe=""), "", ""))
|
||||
get_headers = {"Authorization": headers["Authorization"]} if "Authorization" in headers else {}
|
||||
with urlopen(Request(run_url, headers=get_headers, method="GET"), timeout=10) as response:
|
||||
existing = json.load(response)
|
||||
conf = existing.get("conf") or {}
|
||||
expected = payload["conf"]
|
||||
return (existing.get("dag_run_id") == payload["dag_run_id"]
|
||||
and conf.get("job_id") == expected["job_id"]
|
||||
and conf.get("request_id") == expected["request_id"])
|
||||
|
||||
def coordinator_once(self) -> bool:
|
||||
did_work = False
|
||||
job = self.store.claim_prepare(self.settings.lease_seconds)
|
||||
|
||||
Reference in New Issue
Block a user