Spaces:
Sleeping
Sleeping
github-actions[bot] commited on
Commit ·
dd9584b
1
Parent(s): 011c72c
Automated deployment from GitHub Actions: d0b87cbe4fdaf86c5c12e61d54b1acd8b234b76c
Browse filesFiles changed (18)
- pyproject.toml+1
- src/ai/graph.py+1-8
- src/ai/nodes/extract.py+315-113
- src/ai/nodes/fallback_ocr.py+4-1
- src/ai/nodes/risk.py+17
- src/ai/nodes/validate.py+11-1
- src/ai/state.py+4
- src/config.py+26-18
- src/dependencies.py+1-8
- src/main.py+1-33
- src/routers/batches.py+30-90
- src/scripts/backfill_batch_risk.pyAdded+106
- src/scripts/recompute_field_confidences.pyAdded+109
- src/scripts/revalidate_batch.pyAdded+129
- src/services/ingest_svc.py+2-2
- src/services/ocr_engine_svc.py+192-72
- src/services/validation_rules_svc.py+168-8
- src/tasks/ocr_tasks.py+50-12
35 unmodified lines36373839404135 unmodified lines# AI / LLM"google-generativeai>=0.8.5","langchain-google-genai>=2.1.0","langgraph>=0.3.18","langgraph-checkpoint-redis>=0.0.6","langsmith>=0.3.11",35 unmodified lines3637383940414235 unmodified lines# AI / LLM"google-generativeai>=0.8.5","langchain-google-genai>=2.1.0","langchain-openai>=0.2.14","langgraph>=0.3.18","langgraph-checkpoint-redis>=0.0.6","langsmith>=0.3.11",
31 unmodified lines323334353637383940414243447 unmodified lines5253545556575831 unmodified linesdef _needs_fallback(state: ExtractionGraphState) -> str:"""Route to OCR ensemble fallback when quality, confidence, or data is weak."""if settings.CLOUD_LLM_ONLY:for doc in state.get("documents", []):if doc.get("error") or not doc.get("extracted_data"):return "fallback"if len(doc.get("ocr_candidates") or {}) > 1:return "fallback"if doc.get("ocr_conflicts"):return "fallback"log.info("CLOUD_LLM_ONLY is active — bypassing heavy OCR ensemble fallback")return "validate"7 unmodified linesreturn "fallback"if doc.get("ocr_conflicts"):return "fallback"if len(doc.get("ocr_candidates") or {}) > 1:return "fallback"return "validate"31 unmodified lines3233343536377 unmodified lines4546474849505131 unmodified linesdef _needs_fallback(state: ExtractionGraphState) -> str:"""Route to OCR ensemble fallback when quality, confidence, or data is weak."""if settings.CLOUD_LLM_ONLY:log.info("CLOUD_LLM_ONLY is active — bypassing heavy OCR ensemble fallback")return "validate"7 unmodified linesreturn "fallback"if doc.get("ocr_conflicts"):return "fallback"if len(doc.get("ocr_candidates") or {}) > 1 and doc.get("document_mode") != "digital_pdf_text":return "fallback"return "validate"
123456789101118 unmodified lines303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761 unmodified line178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221"""TradeFlow AI — Primary LLM Extraction Node (Step 2.2)Uses Gemini 2.0 Flash Exp for multimodal extraction."""import asyncioimport inspectimport structlogfrom pydantic import BaseModel, Field18 unmodified lineslog = structlog.get_logger()# Structured output schemaclass CEISAFields(BaseModel):importer_name: str | None = Field(description="Name of the importing company")importer_npwp: str | None = Field(description="NPWP tax ID of the importer")total_packages: int | None = Field(description="Total number of packages/koli")gross_weight: float | None = Field(description="Total gross weight in KGM")cif_value: float | None = Field(description="Total CIF value")currency: str | None = Field(description="Currency code (e.g. USD, IDR)")async def llm_extraction_node(state: ExtractionGraphState) -> dict:"""Step 2.2: Primary LLM Extraction using Gemini 2.0 Flash Exp.Args:state: ExtractionGraphState with documents list containing doc_id, storage_path, pagesReturns:dict with:- documents: Updated docs with extracted_data or error flag- combined_data: Merged field values across docs- steps: Execution traceRaises:Specific exceptions (GoogleAPIError, ValueError) — does NOT catch all exceptions"""log.info("Running llm_extraction_node", batch_id=state["batch_id"])# Lazy LLM setup: only instantiate the LLM when we encounter the first document# that actually needs LLM extraction (has pages). This keeps unit tests lightweight# when LLM dependencies are not installed.structured_llm = Noneupdated_docs = []combined_data = {}for doc in state["documents"]:# Validate document state before processingif not doc.get("doc_id") or not doc.get("pages"):log.error("Invalid document state — missing required fields",doc_id=doc.get("doc_id"),batch_id=state["batch_id"])updated_docs.append({**doc,"error": "Document missing required fields (doc_id, pages)","fallback_required": True,"ocr_method": "failed"})continue# Initialize LLM on first real document that needs extractionif structured_llm is None:try:if settings.DETERMINISTIC_E2E:if DeterministicLLM is None:raise RuntimeError("DETERMINISTIC_E2E enabled but DeterministicLLM not available")llm = DeterministicLLM()else:if ChatGoogleGenerativeAI is None:raise RuntimeError("Production LLM dependency 'langchain_google_genai' is not installed")primary_llm = ChatGoogleGenerativeAI(model=settings.GEMINI_MODEL_PRIMARY,temperature=0,api_key=settings.GEMINI_API_KEY)fallback_llm = ChatGoogleGenerativeAI(model=settings.GEMINI_MODEL_FALLBACK,temperature=0,api_key=settings.GEMINI_API_KEY)llm = primary_llm.with_fallbacks([fallback_llm])structured_llm = llm.with_structured_output(CEISAFields)# Support both synchronous return and awaitable (coroutine/AsyncMock)if asyncio.iscoroutine(structured_llm) or inspect.isawaitable(structured_llm):structured_llm = await structured_llmexcept Exception as e:log.exception("Gemini setup failed - preserving OCR candidates for reconciliation",doc_id=doc.get("doc_id"),batch_id=state["batch_id"],error_type=type(e).__name__,)updated_docs.append({**doc,"error": str(e),"fallback_required": True,"ocr_method": "gemini_setup_failed",})continue# Validate document state before processingif not doc.get("doc_id") or not doc.get("pages"):log.error("Invalid document state — missing required fields",doc_id=doc.get("doc_id"),batch_id=state["batch_id"])updated_docs.append({**doc,"error": "Document missing required fields (doc_id, pages)","fallback_required": True,"ocr_method": "failed"})continuetry:# Avoid importing heavy langchain Core in deterministic/test modeif settings.DETERMINISTIC_E2E:messages = [{"type": "text", "text": "deterministic"}]else:try:from langchain_core.messages import HumanMessage as _HumanMessageexcept Exception:class _HumanMessage: # lightweight fallback so tests don't require langchain_coredef __init__(self, content):self.content = content# Real LLM call with multimodal content# Pass pages as base64-encoded images for extractionmessages = [_HumanMessage(content=[{"type": "text", "text": "Extract all CEISA fields (importer name, NPWP, packages, weight, CIF value) from this document."},{"type": "image_url", "image_url": {"url": doc["pages"][0]}} if doc["pages"] else {"type": "text", "text": "No pages available"}])]result = await structured_llm.ainvoke(messages)# Convert Pydantic model to dictraw_extracted = result.model_dump(exclude_none=True) if hasattr(result, 'model_dump') else resultif asyncio.iscoroutine(raw_extracted):raw_extracted = await raw_extractedextracted = raw_extractedcandidates = dict(doc.get("ocr_candidates") or {})candidates[settings.GEMINI_MODEL_PRIMARY] = {"fields": extracted,"confidence": 0.82,}updated_docs.append({1 unmodified line"extracted_data": extracted,"ocr_method": settings.GEMINI_MODEL_PRIMARY,"ocr_candidates": candidates,"field_confidences": dict.fromkeys(extracted, 0.82),})combined_data.update(extracted)except (ValueError, KeyError) as e:# Expected errors — likely malformed inputlog.exception("Gemini extraction failed — will retry with fallback",doc_id=doc.get("doc_id"),batch_id=state["batch_id"],error_type=type(e).__name__)updated_docs.append({**doc,"error": str(e),"fallback_required": True,"ocr_method": "failed"})except Exception as e:# Unexpected errors are real production failures and should surface# so the batch can be diagnosed instead of silently degrading.log.exception("Unexpected error in LLM extraction — batch will fail",doc_id=doc.get("doc_id"),batch_id=state["batch_id"],error_type=type(e).__name__)updated_docs.append({**doc,"error": str(e),"fallback_required": True,"ocr_method": "gemini_failed"})raisereturn {"documents": updated_docs,"combined_data": combined_data,"steps": ["llm_extraction"]}1234567891011121314151618 unmodified lines35363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933941 unmodified line396397398399400401402403404405406407408409410411412413414415416417418419420421422423"""TradeFlow AI — Primary LLM Extraction Node (Step 2.2)Uses Gemini 2.0 Flash Exp for multimodal extraction, or a local Ollama LLMwhen USE_LOCAL_LLM=true."""from __future__ import annotationsimport asyncioimport inspectimport jsonimport reimport structlogfrom pydantic import BaseModel, Field18 unmodified lineslog = structlog.get_logger()# Structured output schema — comprehensive CEISA + B/L fieldsclass CEISAFields(BaseModel):# Importer / Consigneeimporter_name: str | None = Field(description="Name of importing company (consignee)")importer_npwp: str | None = Field(description="NPWP tax ID, 15-16 digits, explicitly labeled NPWP")importer_address: str | None = Field(description="Address of importer/consignee")# Shipper / Exporterexporter_name: str | None = Field(description="Name of exporting company (shipper)")exporter_address: str | None = Field(description="Address of exporter/shipper")# B/L and document referencesbl_number: str | None = Field(description="Bill of Lading number")bl_date: str | None = Field(description="Date of B/L issue")# Vessel and voyagevessel_name: str | None = Field(description="Name of the ocean vessel")voyage_number: str | None = Field(description="Voyage number")# Portsport_of_loading: str | None = Field(description="Port of loading (departure)")port_of_discharge: str | None = Field(description="Port of discharge (destination)")# Cargototal_packages: int | None = Field(description="Total number of packages/koli across ALL containers")gross_weight: float | None = Field(description="Total gross weight in KGS/KGM")# Container numbers (as a comma-separated string)container_numbers: str | None = Field(description="Container numbers, comma-separated")description_of_goods: str | None = Field(description="General description of goods")hs_code: str | None = Field(description="HS/BTKI tariff code exactly as printed, do not pad or correct")# Commercial values (usually from Invoice, may be absent in B/L)cif_value: float | None = Field(description="Total CIF value")fob_value: float | None = Field(description="Total FOB value")freight_value: float | None = Field(description="Freight value")insurance_value: float | None = Field(description="Insurance value")currency: str | None = Field(description="Currency code (e.g. USD, IDR)")importer_nib: str | None = Field(description="Importer NIB business ID exactly as printed")# Incotermsincoterms: str | None = Field(description="Incoterms (e.g. FOB, CIF, CFR)")freight_terms: str | None = Field(description="Freight terms (PREPAID or COLLECT)")def _parse_json_from_text(text: str) -> dict:"""Robustly extract a JSON object from LLM plain-text output.Handles markdown code fences and DeepSeek-style <think> tags."""# Strip <think>...</think> tags (DeepSeek-R1 style)text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL).strip()# Try JSON inside markdown fences firstfence_match = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.DOTALL)if fence_match:try:return json.loads(fence_match.group(1))except json.JSONDecodeError:pass# Fall back to bare JSON objectjson_match = re.search(r"\{.*\}", text, re.DOTALL)if json_match:try:return json.loads(json_match.group(0))except json.JSONDecodeError:passreturn {}def _normalize_for_evidence(value: object) -> str:return re.sub(r"[^a-z0-9]+", "", str(value or "").casefold())def _field_value_has_text_evidence(field: str, value: object, raw_text: str) -> bool:normalized_value = _normalize_for_evidence(value)normalized_text = _normalize_for_evidence(raw_text)if not normalized_value:return Falseif normalized_value in normalized_text:return Trueif field in {"gross_weight", "cif_value", "fob_value", "freight_value", "insurance_value"}:numeric = re.sub(r"[^0-9]", "", str(value))return bool(numeric and numeric in normalized_text)if field == "total_packages":numeric = re.sub(r"[^0-9]", "", str(value))return bool(numeric and numeric in normalized_text)return Falsedef _field_format_valid(field: str, value: object) -> bool:text = str(value or "").strip()if not text:return Falseif field == "importer_npwp":return len(re.sub(r"\D", "", text)) in {15, 16}if field == "importer_nib":return len(re.sub(r"\D", "", text)) == 13if field == "hs_code":return bool(re.fullmatch(r"\d{8}", text))if field == "currency":return bool(re.fullmatch(r"[A-Z]{3}", text))if field in {"gross_weight", "cif_value", "fob_value", "freight_value", "insurance_value"}:try:return float(str(value).replace(",", "")) >= 0except (TypeError, ValueError):return Falseif field == "total_packages":try:return int(float(str(value).replace(",", ""))) > 0except (TypeError, ValueError):return Falsereturn Truedef _estimate_field_confidences(extracted: dict, doc: dict) -> dict[str, float]:raw_text = doc.get("raw_text") or ""candidates = doc.get("ocr_candidates") or {}pdf_candidate = candidates.get("pdf_text") or {}base = 0.88 if doc.get("document_mode") == "digital_pdf_text" else 0.82if pdf_candidate.get("confidence"):base = max(base, min(0.96, float(pdf_candidate.get("confidence")) * 0.94))confidences: dict[str, float] = {}for field, value in extracted.items():confidence = basehas_evidence = _field_value_has_text_evidence(field, value, raw_text)format_valid = _field_format_valid(field, value)if has_evidence:confidence += 0.05else:confidence -= 0.12if not format_valid:confidence -= 0.25confidences[field] = round(max(0.35, min(0.99, confidence)), 4)return confidencesasync def llm_extraction_node(state: ExtractionGraphState) -> dict:"""Step 2.2: Primary LLM Extraction.- When USE_LOCAL_LLM=true: uses Ollama (text-only, manual JSON parsing).- Otherwise: uses Gemini multimodal (with_structured_output).Returns:dict with documents, combined_data, steps"""log.info("Running llm_extraction_node", batch_id=state["batch_id"])# LLM instances — lazily initialized on first documentllm = Nonestructured_llm = Noneuse_manual_json = False # True for Ollama (no function-calling)updated_docs = []combined_data = {}for doc in state["documents"]:# ── Guard: document must have doc_id and pages ──────────────────────has_extraction_input = bool(doc.get("pages")) or bool((doc.get("raw_text") or "").strip())if not doc.get("doc_id") or not has_extraction_input:log.error("Invalid document state — missing required fields",doc_id=doc.get("doc_id"),batch_id=state["batch_id"],)updated_docs.append({**doc,"error": "Document missing required fields (doc_id and pages/raw_text)","fallback_required": True,"ocr_method": "failed",})continue# ── Initialize LLM once ─────────────────────────────────────────────if llm is None:if settings.DETERMINISTIC_E2E:if DeterministicLLM is None:raise RuntimeError("DETERMINISTIC_E2E enabled but DeterministicLLM not available")llm = DeterministicLLM()structured_llm = llm.with_structured_output(CEISAFields)use_manual_json = Falseelif settings.USE_LOCAL_LLM:try:from langchain_openai import ChatOpenAIexcept ImportError:raise RuntimeError("Dependency 'langchain_openai' is required for local LLM support")# Supports comma-separated models: "qwen2.5:7b,mistral:7b"local_models = [m.strip() for m in settings.LOCAL_LLM_MODEL.split(",") if m.strip()]if not local_models:local_models = ["qwen2.5:7b"]primary_llm = ChatOpenAI(model=local_models[0],base_url=settings.OLLAMA_BASE_URL,api_key="ollama",temperature=0,max_retries=1,)log.info("Using primary local LLM", model=local_models[0])if len(local_models) > 1:fallback_llms = [ChatOpenAI(model=m,base_url=settings.OLLAMA_BASE_URL,api_key="ollama",temperature=0,max_retries=1,)for m in local_models[1:]]llm = primary_llm.with_fallbacks(fallback_llms)log.info("Configured local fallback LLMs", models=local_models[1:])else:llm = primary_llm# Ollama does NOT support function-calling — parse JSON manuallyuse_manual_json = Trueelse:# ── Gemini (multimodal, with_structured_output) ──────────────if ChatGoogleGenerativeAI is None:raise RuntimeError("Production LLM dependency 'langchain_google_genai' is not installed")primary_llm = ChatGoogleGenerativeAI(model=settings.GEMINI_MODEL_PRIMARY,temperature=0,api_key=settings.GEMINI_API_KEY,)fallback_llms = []try:from langchain_openai import ChatOpenAIolm_llm = ChatOpenAI(model=settings.OLM_BASE_MODEL,base_url=f"{settings.OLM_INFERENCE_URL}/v1",api_key="empty",temperature=0,max_retries=1,)fallback_llms.append(olm_llm)except Exception as e:log.warning("Could not setup OLM fallback", error=str(e))gemini_fallback = ChatGoogleGenerativeAI(model=settings.GEMINI_MODEL_FALLBACK,temperature=0,api_key=settings.GEMINI_API_KEY,)fallback_llms.append(gemini_fallback)llm = primary_llm.with_fallbacks(fallback_llms)structured_llm = llm.with_structured_output(CEISAFields)if asyncio.iscoroutine(structured_llm) or inspect.isawaitable(structured_llm):structured_llm = await structured_llmuse_manual_json = False# ── Build prompt messages ───────────────────────────────────────────try:if settings.DETERMINISTIC_E2E:messages = [{"type": "text", "text": "deterministic"}]else:try:from langchain_core.messages import HumanMessage as _HumanMessageexcept Exception:class _HumanMessage: # lightweight fallbackdef __init__(self, content):self.content = contentif use_manual_json:# Text-only prompt for local Ollama modelsraw_text = doc.get("raw_text", "")content = ("You are a strictly accurate customs document parser for CEISA 4.0 (Indonesian Customs). ""Extract ALL the following fields from the document.\n""CRITICAL RULES:\n""1. If a value is NOT clearly present in the text, return null for that field. DO NOT GUESS.\n""2. Return ONLY a valid JSON object. No explanation, no markdown.\n""3. For gross_weight: remove commas used as thousand separators (e.g. '11,603.000' -> 11603.0).\n""4. For total_packages: sum ALL container package counts (e.g. '20 PACKAGES' + '17 PACKAGES' = 37).\n""5. For importer_npwp: ONLY extract if the text explicitly says 'NPWP' or 'Tax ID'. DO NOT use B/L numbers.\n\n""Fields to extract (return as JSON keys):\n""- importer_name: Consignee / buyer company name\n""- importer_npwp: NPWP tax ID (15-16 digits, null if not found)\n""- importer_address: Consignee/importer address\n""- exporter_name: Shipper / seller company name\n""- exporter_address: Shipper/exporter address\n""- bl_number: Bill of Lading number\n""- bl_date: B/L issue date (ISO 8601 if possible)\n""- vessel_name: Ocean vessel name\n""- voyage_number: Voyage number\n""- port_of_loading: Port of departure\n""- port_of_discharge: Port of destination\n""- total_packages: TOTAL packages across ALL containers (integer)\n""- gross_weight: Total gross weight in KGS as a plain float (no commas)\n""- container_numbers: All container numbers comma-separated\n""- description_of_goods: Brief description of cargo\n""- hs_code: HS/BTKI code exactly as printed; do NOT pad/correct invalid 6-digit codes\n""- cif_value: CIF value (float, null if not in document)\n""- fob_value: FOB value (float, null if not in document)\n""- freight_value: Freight value (float, null if not in document)\n""- insurance_value: Insurance value (float, null if not in document)\n""- currency: Currency code (USD/IDR/EUR etc, null if not found)\n""- importer_nib: NIB exactly as printed, null if not found\n""- incoterms: Incoterms code (FOB/CIF/CFR etc, null if not found)\n""- freight_terms: PREPAID or COLLECT (null if not found)\n\n"f"Document Text:\n{raw_text[:12000]}")messages = [_HumanMessage(content=[{"type": "text", "text": content}])]else:# Multimodal prompt for Geminiraw_text = (doc.get("raw_text") or "")[:12000]prompt_text = ("Extract all CEISA fields (importer name, NPWP, packages, weight, CIF value) from this document.")if raw_text:prompt_text += f"\n\nDirect PDF/OCR text:\n{raw_text}"messages = [_HumanMessage(content=[{"type": "text","text": prompt_text,},({"type": "image_url", "image_url": {"url": doc["pages"][0]}}if doc.get("pages")else {"type": "text", "text": "No pages available"}),])]# ── Invoke LLM ──────────────────────────────────────────────────if use_manual_json:response = await llm.ainvoke(messages)text_response = response.content if hasattr(response, "content") else str(response)raw_extracted = _parse_json_from_text(text_response)# Coerce through Pydantic for type safetytry:validated = CEISAFields(**raw_extracted)extracted = validated.model_dump(exclude_none=True)except Exception:extracted = {k: v for k, v in raw_extracted.items() if v is not None}else:result = await structured_llm.ainvoke(messages)raw_result = result.model_dump(exclude_none=True) if hasattr(result, "model_dump") else resultif asyncio.iscoroutine(raw_result):raw_result = await raw_resultextracted = raw_resultcandidates = dict(doc.get("ocr_candidates") or {})field_confidences = _estimate_field_confidences(extracted, doc)candidates[settings.GEMINI_MODEL_PRIMARY] = {"fields": extracted,"confidence": round(sum(field_confidences.values()) / len(field_confidences), 4) if field_confidences else 0.0,"field_confidences": field_confidences,}updated_docs.append({1 unmodified line"extracted_data": extracted,"ocr_method": settings.GEMINI_MODEL_PRIMARY,"ocr_candidates": candidates,"field_confidences": field_confidences,})combined_data.update(extracted)except Exception as e:# Per-document failure — mark for fallback, do NOT crash the batchlog.exception("LLM extraction failed — marking doc for fallback",doc_id=doc.get("doc_id"),batch_id=state["batch_id"],error_type=type(e).__name__,error=str(e),)updated_docs.append({**doc,"error": str(e),"fallback_required": True,"ocr_method": "failed",})return {"documents": updated_docs,"combined_data": combined_data,"steps": ["llm_extraction"],}
21 unmodified lines2223242526272821 unmodified linesor not doc.get("extracted_data")or doc.get("quality_score", 1.0) < settings.OCR_FALLBACK_TRIGGER_QUALITYor bool(doc.get("ocr_conflicts"))or len(doc.get("ocr_candidates") or {}) > 1or bool(confidencesand min(confidences.values()) < settings.OCR_FALLBACK_TRIGGER_CONFIDENCE21 unmodified lines2223242526272829303121 unmodified linesor not doc.get("extracted_data")or doc.get("quality_score", 1.0) < settings.OCR_FALLBACK_TRIGGER_QUALITYor bool(doc.get("ocr_conflicts"))or (len(doc.get("ocr_candidates") or {}) > 1and doc.get("document_mode") != "digital_pdf_text")or bool(confidencesand min(confidences.values()) < settings.OCR_FALLBACK_TRIGGER_CONFIDENCE
114 unmodified lines1151161171181191206 unmodified lines12712812913013113214 unmodified lines147148149150151152114 unmodified lines)crs_score = round(crs_raw * 100, 2)crs_grade = _crs_to_grade(crs_score)features = {"doc_quality_score": p_quality,6 unmodified lines"gross_weight_kg": float(combined_data.get("gross_weight") or 0.0),}rejection_prob = round(rejection_predictor.predict_proba(features), 4)risk_level = _probability_to_risk(rejection_prob)# PRD §13 Invariant: CRS < 70 → must NOT auto-submit14 unmodified linesreturn {"risk_level": risk_level,"needs_human_review": needs_human_review,"steps": ["risk_assessment"],# NOTE: crs_score and rejection_prob are persisted to DB in the114 unmodified lines1151161171181191201211221231241251261271281296 unmodified lines13613713813914014114214314414514 unmodified lines160161162163164165166167168169114 unmodified lines)crs_score = round(crs_raw * 100, 2)crs_grade = _crs_to_grade(crs_score)critical_failures = sum(1 for r in validation_results if r.get("severity") == "CRITICAL_FAIL")warnings = sum(1 for r in validation_results if r.get("severity") == "WARNING")if critical_failures:crs_score = min(crs_score, 55.0)crs_grade = _crs_to_grade(crs_score)elif warnings:crs_score = min(crs_score, 75.0)crs_grade = _crs_to_grade(crs_score)features = {"doc_quality_score": p_quality,6 unmodified lines"gross_weight_kg": float(combined_data.get("gross_weight") or 0.0),}rejection_prob = round(rejection_predictor.predict_proba(features), 4)if critical_failures:rejection_prob = max(rejection_prob, 0.65)elif warnings:rejection_prob = max(rejection_prob, 0.30)risk_level = _probability_to_risk(rejection_prob)# PRD §13 Invariant: CRS < 70 → must NOT auto-submit14 unmodified linesreturn {"risk_level": risk_level,"customs_readiness_score": crs_score,"crs_grade": crs_grade,"rejection_probability": rejection_prob,"risk_features": features,"needs_human_review": needs_human_review,"steps": ["risk_assessment"],# NOTE: crs_score and rejection_prob are persisted to DB in the
11 unmodified lines1213141516171819202111 unmodified linesasync def validation_node(state: ExtractionGraphState) -> dict:"""Step 2.4: Cross-Document Validation against JSON rules."""log.info("Running validation_node", batch_id=state["batch_id"])results, needs_review = validation_rules_service.evaluate(state)return {"validation_results": results,11 unmodified lines121314151617181920212223242526272829303111 unmodified linesasync def validation_node(state: ExtractionGraphState) -> dict:"""Step 2.4: Cross-Document Validation against JSON rules.Gracefully handles rule evaluation errors to avoid crashing the pipeline."""log.info("Running validation_node", batch_id=state["batch_id"])try:results, needs_review = validation_rules_service.evaluate(state)except Exception as exc:log.warning("Validation rules evaluation failed — marking for review",batch_id=state["batch_id"],error=str(exc),)results = []needs_review = Truereturn {"validation_results": results,
27 unmodified lines28293031323327 unmodified linesvalidation_results: list[dict]needs_human_review: boolrisk_level: strocr_conflicts: list[dict]field_confidences: dict[str, float]# Keep track of which node executed27 unmodified lines2829303132333435363727 unmodified linesvalidation_results: list[dict]needs_human_review: boolrisk_level: strcustoms_readiness_score: float | Nonecrs_grade: str | Nonerejection_probability: float | Nonerisk_features: dictocr_conflicts: list[dict]field_confidences: dict[str, float]# Keep track of which node executed
26 unmodified lines2728293031323325 unmodified lines5960616263643 unmodified lines6869707172737475767724 unmodified lines1021031041051061071081091103 unmodified lines1141151161171181191201211221239 unmodified lines13313413513613713813914020 unmodified lines16116216316416516616716816923 unmodified lines19319419519619719819920026 unmodified linesENVIRONMENT: Literal["development", "staging", "production"] = "development"DEBUG: bool = FalseSECRET_KEY: SecretStr = Field(..., min_length=32)CORS_ORIGINS: list[str] | str = ["*"]# ── Database ──────────────────────────────────────────────────────────────DATABASE_URL: str # asyncpg connection string e.g. postgresql+asyncpg://...25 unmodified lines# ── AI Inference Services (SDD §2.3–2.6) ─────────────────────────────────CLOUD_LLM_ONLY: bool = False # Bypass heavy local models and use Gemini API insteadSURYA_INFERENCE_URL: AnyHttpUrl = "http://surya-svc:8001" # Agent AOLM_INFERENCE_URL: AnyHttpUrl = "http://olm-inference:8000" # Agent DPADDLEOCR_SVC_URL: AnyHttpUrl = "http://paddleocr-svc:8002" # Agent B3 unmodified linesHF_TOKEN: SecretStr = "" # type: ignore[assignment]# ── Azure Document Intelligence — Agent C ─────────────────────────────────AZURE_DI_ENDPOINT: str | None = NoneAZURE_DI_KEY: SecretStr = "" # type: ignore[assignment]AZURE_DI_MODEL_ID: str = "prebuilt-document"AZURE_DI_FREE_LIMIT: int = 5000 # Pages/month on F0 tier (Invariant #9)# ── CEISA (Simulator in dev, real endpoint in prod) ───────────────────────CEISA_BASE_URL: AnyHttpUrl = "http://simulator:8006"24 unmodified linesCHROMADB_PORT: int = 8000# ── AI / LLM ─────────────────────────────────────────────────────────────GEMINI_API_KEY: SecretStr = Field(..., description="Google Gemini API key")GEMINI_MODEL_PRIMARY: str = "gemini-2.5-pro"GEMINI_MODEL_FALLBACK: str = "gemini-2.5-flash"OPENAI_API_KEY: SecretStr = "" # type: ignore[assignment]EMBEDDING_MODEL: str = "text-embedding-3-small"3 unmodified linesLANGCHAIN_API_KEY: SecretStr = "" # type: ignore[assignment]# ── Feature Flags ─────────────────────────────────────────────────────────ENABLE_SURYA_AGENT: bool = TrueENABLE_AZURE_DI_AGENT: bool = TrueENABLE_DUAL_OCR: bool = True # Legacy alias used by lightweight OCR serviceENABLE_VESSEL_VALIDATION: bool = TrueENABLE_BLOCKCHAIN: bool = True # type: ignore[assignment] — redeclared intentionallyENABLE_INSW_CHECK: bool = TrueENABLE_NOTIFICATIONS_WHATSAPP: bool = False9 unmodified linesOCR_MAX_RENDERED_PAGES: int = 10OCR_MAX_LLM_PAGES: int = 5OCR_FAST_PATH_QUALITY_THRESHOLD: float = 0.95OCR_FALLBACK_TRIGGER_QUALITY: float = 0.75OCR_FALLBACK_TRIGGER_CONFIDENCE: float = 0.78OCR_RECONCILIATION_DISAGREEMENT_THRESHOLD: float = 0.20LLM_CONFIDENCE_REVIEW_THRESHOLD: float = 0.70CRS_MIN_SUBMIT_THRESHOLD: int = 5520 unmodified linesDRIFT_LOOKBACK_DAYS: int = 30DRIFT_CORRECTION_THRESHOLD: int = 50# ── Celery ────────────────────────────────────────────────────────────────CELERY_TASK_SOFT_TIME_LIMIT: int = 300CELERY_TASK_TIME_LIMIT: int = 600# ── Observability ─────────────────────────────────────────────────────────SENTRY_DSN: str = ""23 unmodified linesaccept_content = ["json"]timezone = "Asia/Jakarta"enable_utc = Truetask_soft_time_limit = 300task_time_limit = 600task_acks_late = True # Ack only after successful completion (NFR-016)worker_prefetch_multiplier = 1 # One task at a time per worker26 unmodified lines2728293031323325 unmodified lines5960616263646566673 unmodified lines7172737475767778798024 unmodified lines1051061071081091101111121131141151163 unmodified lines1201211221231241251261271289 unmodified lines13813914014114214314414520 unmodified lines16616716816917017117217317417517617723 unmodified lines20120220320420520620720826 unmodified linesENVIRONMENT: Literal["development", "staging", "production"] = "development"DEBUG: bool = FalseSECRET_KEY: SecretStr = Field(..., min_length=32)CORS_ORIGINS: list[str] = ["*"]# ── Database ──────────────────────────────────────────────────────────────DATABASE_URL: str # asyncpg connection string e.g. postgresql+asyncpg://...25 unmodified lines# ── AI Inference Services (SDD §2.3–2.6) ─────────────────────────────────CLOUD_LLM_ONLY: bool = False # Bypass heavy local models and use Gemini API insteadENABLE_DUAL_OCR: bool = False # Use both Surya and PaddleOCR for fallback/validationOCR_FALLBACK_TRIGGER_QUALITY: float = 0.85 # Fallback thresholdOCR_FALLBACK_TRIGGER_CONFIDENCE: float = 0.80SURYA_INFERENCE_URL: AnyHttpUrl = "http://surya-svc:8001" # Agent AOLM_INFERENCE_URL: AnyHttpUrl = "http://olm-inference:8000" # Agent DPADDLEOCR_SVC_URL: AnyHttpUrl = "http://paddleocr-svc:8002" # Agent B3 unmodified linesHF_TOKEN: SecretStr = "" # type: ignore[assignment]# ── Azure Document Intelligence — Agent C ─────────────────────────────────AZURE_DI_ENDPOINT: str | None = NoneAZURE_DI_KEY: SecretStr = "" # type: ignore[assignment]AZURE_DI_MODEL_ID: str = "prebuilt-read"AZURE_DI_FREE_LIMIT: int = 5000 # Pages/month on F0 tier (Invariant #9)# ── CEISA (Simulator in dev, real endpoint in prod) ───────────────────────CEISA_BASE_URL: AnyHttpUrl = "http://simulator:8006"24 unmodified linesCHROMADB_PORT: int = 8000# ── AI / LLM ─────────────────────────────────────────────────────────────USE_LOCAL_LLM: bool = FalseLOCAL_LLM_MODEL: str = "qwen2.5:7b"OLLAMA_BASE_URL: str = "http://host.docker.internal:11434/v1"GEMINI_API_KEY: SecretStr = Field(..., description="Google Gemini API key")GEMINI_MODEL_PRIMARY: str = "gemini-3.5-flash"GEMINI_MODEL_FALLBACK: str = "gemini-3.1-flash-lite"OPENAI_API_KEY: SecretStr = "" # type: ignore[assignment]EMBEDDING_MODEL: str = "text-embedding-3-small"3 unmodified linesLANGCHAIN_API_KEY: SecretStr = "" # type: ignore[assignment]# ── Feature Flags ─────────────────────────────────────────────────────────ENABLE_SURYA_AGENT: bool = TrueENABLE_AZURE_DI_AGENT: bool = TrueENABLE_VESSEL_VALIDATION: bool = TrueENABLE_BLOCKCHAIN: bool = True # type: ignore[assignment] — redeclared intentionallyENABLE_INSW_CHECK: bool = TrueENABLE_NOTIFICATIONS_WHATSAPP: bool = False9 unmodified linesOCR_MAX_RENDERED_PAGES: int = 10OCR_MAX_LLM_PAGES: int = 5OCR_FAST_PATH_QUALITY_THRESHOLD: float = 0.95OCR_PDF_TEXT_MIN_CHARS: int = 250OCR_PDF_TEXT_MIN_CHARS_PER_PAGE: int = 80OCR_RECONCILIATION_DISAGREEMENT_THRESHOLD: float = 0.20LLM_CONFIDENCE_REVIEW_THRESHOLD: float = 0.70CRS_MIN_SUBMIT_THRESHOLD: int = 5520 unmodified linesDRIFT_LOOKBACK_DAYS: int = 30DRIFT_CORRECTION_THRESHOLD: int = 50# Celery ConfigurationCELERY_BROKER_URL: str = "redis://redis:6379/0"CELERY_RESULT_BACKEND: str = "redis://redis:6379/0"CELERY_TASK_SOFT_TIME_LIMIT: int = 1800 # 30 minutes for slow OCR modelsCELERY_TASK_TIME_LIMIT: int = 1900RUN_OCR_IN_API_BACKGROUND: bool = False# ── Observability ─────────────────────────────────────────────────────────SENTRY_DSN: str = ""23 unmodified linesaccept_content = ["json"]timezone = "Asia/Jakarta"enable_utc = Truetask_soft_time_limit = 600task_time_limit = 700task_acks_late = True # Ack only after successful completion (NFR-016)worker_prefetch_multiplier = 1 # One task at a time per worker
53 unmodified lines545556575859606162636465666768697053 unmodified linesdef get_supabase() -> AsyncClient:if _supabase_client is None:raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE,detail="Supabase client is not initialized. Check SUPABASE_URL and SUPABASE_SERVICE_KEY.",)return _supabase_clientdef is_supabase_initialized() -> bool:return _supabase_client is not None# ── Keycloak JWKS cache ───────────────────────────────────────────────────────_keycloak_jwks: dict | None = None_keycloak_jwks_time: float = 053 unmodified lines5455565758596061626353 unmodified linesdef get_supabase() -> AsyncClient:if _supabase_client is None:raise RuntimeError("Supabase client not initialized. Call init_supabase() first.")return _supabase_client# ── Keycloak JWKS cache ───────────────────────────────────────────────────────_keycloak_jwks: dict | None = None_keycloak_jwks_time: float = 0
28 unmodified lines2930313233343584 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615728 unmodified linesInstrumentator = Nonefrom .config import settingsfrom .dependencies import close_supabase, init_supabase, is_supabase_initializedfrom .routers import admin, batches, blockchain, hs_recommend, vesselfrom .utils.telemetry import setup_telemetry84 unmodified linesapp = create_app()def _configured_secret(value: object) -> bool:raw = value.get_secret_value() if hasattr(value, "get_secret_value") else valuetext = str(raw or "").strip()if not text:return Falselowered = text.lower()return not (lowered.startswith("your-")or lowered.startswith("test-")or "placeholder" in lowered)@app.get("/health/config", tags=["health"])async def health_config() -> dict[str, object]:"""Safe deployment diagnostics. Returns booleans only for secrets."""return {"status": "ok","environment": settings.ENVIRONMENT,"cloud_llm_only": settings.CLOUD_LLM_ONLY,"deterministic_e2e": settings.DETERMINISTIC_E2E,"storage_backend": settings.STORAGE_BACKEND,"storage_bucket": settings.STORAGE_BUCKET_NAME,"supabase_configured": bool(settings.SUPABASE_URL) and _configured_secret(settings.SUPABASE_SERVICE_KEY),"supabase_client_initialized": is_supabase_initialized(),"gemini_api_key_configured": _configured_secret(settings.GEMINI_API_KEY),"azure_di_enabled": settings.ENABLE_AZURE_DI_AGENT,"azure_di_configured": bool(settings.AZURE_DI_ENDPOINT) and _configured_secret(settings.AZURE_DI_KEY),"celery_broker_configured": bool(settings.REDIS_URL),}@app.get("/health", tags=["health"])async def health_check() -> dict[str, str]:"""Health check endpoint — public, no auth required."""28 unmodified lines2930313233343584 unmodified lines12012112212312412528 unmodified linesInstrumentator = Nonefrom .config import settingsfrom .dependencies import close_supabase, init_supabasefrom .routers import admin, batches, blockchain, hs_recommend, vesselfrom .utils.telemetry import setup_telemetry84 unmodified linesapp = create_app()@app.get("/health", tags=["health"])async def health_check() -> dict[str, str]:"""Health check endpoint — public, no auth required."""
24 unmodified lines25262728293031119 unmodified lines1511521531541551561571581591601611627 unmodified lines1701711721731741751761771781791801811821831841851861871883 unmodified lines1921931941951961971983 unmodified lines20220320420520620720820921021121221321421521680 unmodified lines29729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736824 unmodified linesfrom ..dependencies import CurrentUser, get_current_user, get_supabase, require_operatorfrom ..services.ingest_svc import get_storage_servicefrom ..tasks.ocr_tasks import preprocess_documentlog = structlog.get_logger()router = APIRouter()119 unmodified linesawait supabase.table("batches").update({"status": "preprocessing"}).eq("id", batch_id).execute()queue = "high" if user.is_enterprise else "default"try:preprocess_document.apply_async(args=[batch_id], queue=queue)except Exception as e:log.warning("Celery apply_async failed, falling back to BackgroundTasks", error=str(e))background_tasks.add_task(preprocess_document, batch_id)log.info("Batch created", batch_id=batch_id, user=user.id, docs=len(files), tier=user.tier)return {"batch_id": batch_id, "status": "preprocessing", "documents": documents}7 unmodified linesoffset: int = 0,) -> dict[str, Any]:"""List batches for the current user's company."""res = await (supabase.table("batches").select("id,status,customs_readiness_score,crs_grade,risk_level,created_at,expires_at").eq("company_id", user.company_id).order("created_at", desc=True).range(offset, offset + limit - 1).execute())batches = [_decorate_batch_summary(row) for row in (res.data or [])]importer_by_batch = await _load_importer_names(supabase, [row["id"] for row in batches])for row in batches:row["importer"] = importer_by_batch.get(row["id"], "Pending extraction")return {"batches": batches, "total": len(batches)}@router.get("/batches/{batch_id}")3 unmodified linessupabase: Annotated[AsyncClient, Depends(get_supabase)],) -> dict[str, Any]:"""Get full batch details including extracted fields and validation results."""batch_res = await supabase.table("batches").select("*").eq("id", batch_id).single().execute()batch = batch_res.dataif not batch:raise HTTPException(status_code=404, detail="Batch not found")3 unmodified linesdocs_res = await supabase.table("documents").select("*").eq("batch_id", batch_id).execute()fields_res = await supabase.table("extracted_fields").select("*").eq("batch_id", batch_id).execute()validations_res = await supabase.table("validation_results").select("*").eq("batch_id", batch_id).execute()fields = fields_res.data or []reconciled_fields = _build_reconciled_fields(fields)batch["importer"] = _importer_from_reconciled(reconciled_fields)return {"batch": batch,"documents": docs_res.data,"extracted_fields": fields,"reconciled_fields": reconciled_fields,"validation_results": validations_res.data,}80 unmodified linesif any(k in name for k in ("pl", "packing", "packinglist")):return "packing_list"return "invoice"def _decorate_batch_summary(row: dict[str, Any]) -> dict[str, Any]:score = row.get("customs_readiness_score")grade = row.get("crs_grade")risk = row.get("risk_level")return {**row,"ref": str(row.get("id", ""))[:8].upper(),"type": "PIB","risk": risk or "LOW","crs": float(score or 0),"grade": grade or "F","date": row.get("created_at"),}async def _load_importer_names(supabase: AsyncClient, batch_ids: list[str]) -> dict[str, str]:if not batch_ids:return {}try:fields_res = await (supabase.table("extracted_fields").select("batch_id,ceisa_field,extracted_value,normalized_value").in_("batch_id", batch_ids).eq("ceisa_field", "importer_name").execute())except Exception as exc:log.warning("Could not load importer names for batch list", error=str(exc))return {}names: dict[str, str] = {}for field in fields_res.data or []:value = field.get("normalized_value") or field.get("extracted_value")if value:names[field["batch_id"]] = str(value)return namesdef _build_reconciled_fields(fields: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:reconciled: dict[str, dict[str, Any]] = {}for field in fields:name = field.get("ceisa_field")if not name:continueconfidence = float(field.get("confidence") or 0.0)reconciled[name] = {"value": field.get("normalized_value") or field.get("extracted_value") or field.get("raw_ocr_value"),"confidence": confidence,"level": field.get("confidence_level") or _confidence_level(confidence),"source": field.get("extraction_method") or "direct_ocr","agent_disagreement": bool(field.get("agent_disagreement")),"all_agent_values": field.get("agent_outputs") or {},}return reconcileddef _confidence_level(confidence: float) -> str:if confidence >= 0.90:return "HIGH"if confidence >= 0.70:return "MEDIUM"return "LOW"def _importer_from_reconciled(fields: dict[str, dict[str, Any]]) -> str:value = fields.get("importer_name", {}).get("value")return str(value) if value else "Pending extraction"24 unmodified lines25262728293031119 unmodified lines1511521531541551561571581591601611621631641651667 unmodified lines1741751761771781791801811821831841851861871881891901913 unmodified lines1951961971981992002012022032042052062072082092102113 unmodified lines21521621721821922022122222322422580 unmodified lines30630730824 unmodified linesfrom ..dependencies import CurrentUser, get_current_user, get_supabase, require_operatorfrom ..services.ingest_svc import get_storage_servicefrom ..tasks.ocr_tasks import preprocess_document, run_preprocess_pipeline_synclog = structlog.get_logger()router = APIRouter()119 unmodified linesawait supabase.table("batches").update({"status": "preprocessing"}).eq("id", batch_id).execute()if settings.RUN_OCR_IN_API_BACKGROUND:log.info("Running OCR pipeline via FastAPI BackgroundTasks", batch_id=batch_id)background_tasks.add_task(run_preprocess_pipeline_sync, batch_id, True)else:queue = "high" if user.is_enterprise else "default"try:preprocess_document.apply_async(args=[batch_id], queue=queue)except Exception as e:log.warning("Celery apply_async failed, falling back to BackgroundTasks", error=str(e))background_tasks.add_task(run_preprocess_pipeline_sync, batch_id, True)log.info("Batch created", batch_id=batch_id, user=user.id, docs=len(files), tier=user.tier)return {"batch_id": batch_id, "status": "preprocessing", "documents": documents}7 unmodified linesoffset: int = 0,) -> dict[str, Any]:"""List batches for the current user's company."""query = (supabase.table("batches").select("id,status,customs_readiness_score,crs_grade,risk_level,created_at,expires_at").order("created_at", desc=True).range(offset, offset + limit - 1))if user.company_id:query = query.eq("company_id", user.company_id)res = await query.execute()return {"batches": res.data, "total": len(res.data)}@router.get("/batches/{batch_id}")3 unmodified linessupabase: Annotated[AsyncClient, Depends(get_supabase)],) -> dict[str, Any]:"""Get full batch details including extracted fields and validation results."""try:uuid.UUID(batch_id)except ValueError as exc:raise HTTPException(status_code=404, detail="Batch not found") from exctry:batch_res = await supabase.table("batches").select("*").eq("id", batch_id).single().execute()except Exception as exc:log.warning("Failed to load batch", batch_id=batch_id, error=str(exc))raise HTTPException(status_code=404, detail="Batch not found") from excbatch = batch_res.dataif not batch:raise HTTPException(status_code=404, detail="Batch not found")3 unmodified linesdocs_res = await supabase.table("documents").select("*").eq("batch_id", batch_id).execute()fields_res = await supabase.table("extracted_fields").select("*").eq("batch_id", batch_id).execute()validations_res = await supabase.table("validation_results").select("*").eq("batch_id", batch_id).execute()return {"batch": batch,"documents": docs_res.data,"extracted_fields": fields_res.data,"validation_results": validations_res.data,}80 unmodified linesif any(k in name for k in ("pl", "packing", "packinglist")):return "packing_list"return "invoice"
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106from __future__ import annotations
import asyncioimport sysfrom typing import Anyfrom pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from supabase import acreate_client
from src.ai.nodes.risk import risk_assessment_nodefrom src.config import settings
def _coerce_field(field: str, value: Any) -> Any: if value is None: return None if field in {"gross_weight", "cif_value", "fob_value"}: try: return float(str(value).replace(",", "")) except Exception: return value if field == "total_packages": try: return int(float(str(value).replace(",", ""))) except Exception: return value return value
async def backfill_batch_risk(batch_id: str) -> dict[str, Any]: supabase = await acreate_client( settings.SUPABASE_URL, settings.SUPABASE_SERVICE_KEY.get_secret_value(), )
docs = ( await supabase.table("documents").select("*").eq("batch_id", batch_id).execute() ).data or [] fields = ( await supabase.table("extracted_fields").select("*").eq("batch_id", batch_id).execute() ).data or [] validations = ( await supabase.table("validation_results").select("*").eq("batch_id", batch_id).execute() ).data or []
combined: dict[str, Any] = {} confidences: dict[str, float] = {} for row in fields: name = row.get("ceisa_field") if not name: continue combined[name] = _coerce_field( name, row.get("normalized_value") or row.get("extracted_value"), ) confidences[name] = float(row.get("confidence") or 0.0)
state = { "batch_id": batch_id, "company_id": "", "documents": [ { "doc_id": doc["id"], "doc_type": doc.get("doc_type"), "storage_path": doc.get("storage_path"), "pages": [], "extracted_data": {}, "quality_score": float(doc.get("quality_score") or 1.0), "ocr_method": doc.get("ocr_engine_used"), "error": doc.get("error_message"), "ocr_candidates": {}, "ocr_conflicts": [], "field_confidences": {}, } for doc in docs ], "combined_data": combined, "validation_results": validations, "needs_human_review": False, "risk_level": "UNKNOWN", "customs_readiness_score": None, "crs_grade": None, "rejection_probability": None, "risk_features": {}, "ocr_conflicts": [], "field_confidences": confidences, "steps": [], }
result = await risk_assessment_node(state) # type: ignore[arg-type] payload = { "risk_level": result.get("risk_level"), "customs_readiness_score": result.get("customs_readiness_score"), "crs_grade": result.get("crs_grade"), "rejection_probability": result.get("rejection_probability"), } await supabase.table("batches").update(payload).eq("id", batch_id).execute() return payload
if __name__ == "__main__": if len(sys.argv) != 2: raise SystemExit("Usage: python /app/src/scripts/backfill_batch_risk.py <batch_id>") print(asyncio.run(backfill_batch_risk(sys.argv[1])))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109from __future__ import annotations
import asyncioimport sysfrom pathlib import Pathfrom typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from supabase import acreate_client
from src.ai.nodes.extract import _estimate_field_confidencesfrom src.config import settingsfrom src.services.ingest_svc import get_storage_servicefrom src.services.ocr_engine_svc import ocr_engine_service
async def recompute_field_confidences(batch_id: str) -> dict[str, Any]: supabase = await acreate_client( settings.SUPABASE_URL, settings.SUPABASE_SERVICE_KEY.get_secret_value(), )
docs = ( await supabase.table("documents").select("*").eq("batch_id", batch_id).execute() ).data or [] rows = ( await supabase.table("extracted_fields").select("*").eq("batch_id", batch_id).execute() ).data or []
fields_by_doc: dict[str, dict[str, Any]] = {} row_keys_by_doc_field: dict[tuple[str, str], list[dict[str, Any]]] = {} for row in rows: document_id = row.get("document_id") field = row.get("ceisa_field") if not document_id or not field: continue fields_by_doc.setdefault(document_id, {})[field] = row.get("normalized_value") or row.get("extracted_value") row_keys_by_doc_field.setdefault((document_id, field), []).append(row)
storage = get_storage_service() updated = 0 doc_summaries = []
for doc in docs: doc_id = doc["id"] extracted = fields_by_doc.get(doc_id) or {} if not extracted: continue
raw_text = "" direct_candidate: dict[str, Any] = {} try: file_bytes = await storage.download_document(doc["storage_path"]) filename = doc.get("original_name") or doc.get("storage_path") or "" if str(filename).lower().endswith(".pdf"): direct_candidate = ocr_engine_service._extract_pdf_text(file_bytes) raw_text = direct_candidate.get("text") or "" except Exception as exc: print(f"warning: failed to reload {doc.get('original_name')}: {exc}")
doc_state = { "document_mode": "digital_pdf_text" if raw_text else doc.get("processing_route"), "raw_text": raw_text, "ocr_candidates": {"pdf_text": direct_candidate} if direct_candidate else {}, } confidences = _estimate_field_confidences(extracted, doc_state) if not confidences: continue
for field, confidence in confidences.items(): for row in row_keys_by_doc_field.get((doc_id, field), []): row_id = row.get("id") if row_id: await supabase.table("extracted_fields").update({"confidence": confidence}).eq("id", row_id).execute() else: await ( supabase.table("extracted_fields") .update({"confidence": confidence}) .eq("batch_id", batch_id) .eq("document_id", doc_id) .eq("ceisa_field", field) .execute() ) updated += 1
avg_conf = round(sum(confidences.values()) / len(confidences), 4) await ( supabase.table("documents") .update({"overall_ocr_confidence": avg_conf}) .eq("id", doc_id) .execute() ) doc_summaries.append( { "doc_type": doc.get("doc_type"), "original_name": doc.get("original_name"), "avg_confidence": avg_conf, "fields": len(confidences), } )
return {"batch_id": batch_id, "updated_rows": updated, "documents": doc_summaries}
if __name__ == "__main__": if len(sys.argv) != 2: raise SystemExit("Usage: python /app/src/scripts/recompute_field_confidences.py <batch_id>") print(asyncio.run(recompute_field_confidences(sys.argv[1])))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129from __future__ import annotations
import asyncioimport sysfrom pathlib import Pathfrom typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from supabase import acreate_client
from src.ai.nodes.risk import risk_assessment_nodefrom src.config import settingsfrom src.services.validation_rules_svc import validation_rules_service
def _coerce_field(field: str, value: Any) -> Any: if value is None: return None if field in {"gross_weight", "cif_value", "fob_value", "freight_value", "insurance_value"}: try: return float(str(value).replace(",", "")) except Exception: return value if field == "total_packages": try: return int(float(str(value).replace(",", ""))) except Exception: return value return value
async def revalidate_batch(batch_id: str) -> dict[str, Any]: supabase = await acreate_client( settings.SUPABASE_URL, settings.SUPABASE_SERVICE_KEY.get_secret_value(), ) docs = ( await supabase.table("documents").select("*").eq("batch_id", batch_id).execute() ).data or [] fields = ( await supabase.table("extracted_fields").select("*").eq("batch_id", batch_id).execute() ).data or []
by_doc: dict[str, dict[str, Any]] = {} combined: dict[str, Any] = {} confidences: dict[str, float] = {} for row in fields: document_id = row.get("document_id") name = row.get("ceisa_field") if not document_id or not name: continue value = _coerce_field(name, row.get("normalized_value") or row.get("extracted_value")) by_doc.setdefault(document_id, {})[name] = value combined[name] = value confidences[name] = float(row.get("confidence") or 0.0)
state = { "batch_id": batch_id, "company_id": "", "documents": [ { "doc_id": doc["id"], "doc_type": doc.get("doc_type"), "storage_path": doc.get("storage_path"), "pages": [], "extracted_data": by_doc.get(doc["id"], {}), "quality_score": float(doc.get("quality_score") or 1.0), "ocr_method": doc.get("ocr_engine_used"), "error": doc.get("error_message"), "ocr_candidates": {}, "ocr_conflicts": [], "field_confidences": {}, } for doc in docs ], "combined_data": combined, "validation_results": [], "needs_human_review": False, "risk_level": "UNKNOWN", "customs_readiness_score": None, "crs_grade": None, "rejection_probability": None, "risk_features": {}, "ocr_conflicts": [], "field_confidences": confidences, "steps": [], }
validations, needs_review = validation_rules_service.evaluate(state) state["validation_results"] = validations state["needs_human_review"] = needs_review risk = await risk_assessment_node(state) # type: ignore[arg-type]
await supabase.table("validation_results").delete().eq("batch_id", batch_id).execute() if validations: await supabase.table("validation_results").insert([ { "batch_id": batch_id, "rule_id": row.get("rule_id", "UNKNOWN"), "rule_name": row.get("rule_name", row.get("message", "Validation")), "severity": row.get("severity", "WARNING"), "error_message": row.get("message"), "affected_fields": row.get("affected_fields", []), } for row in validations ]).execute()
payload = { "status": "review_ready" if risk.get("needs_human_review") else "validated", "risk_level": risk.get("risk_level"), "customs_readiness_score": risk.get("customs_readiness_score"), "crs_grade": risk.get("crs_grade"), "rejection_probability": risk.get("rejection_probability"), } await supabase.table("batches").update(payload).eq("id", batch_id).execute() return { **payload, "validation_counts": { severity: sum(1 for row in validations if row.get("severity") == severity) for severity in {"PASS", "WARNING", "CRITICAL_FAIL"} }, }
if __name__ == "__main__": if len(sys.argv) != 2: raise SystemExit("Usage: python /app/src/scripts/revalidate_batch.py <batch_id>") print(asyncio.run(revalidate_batch(sys.argv[1])))27 unmodified lines282930313233343527 unmodified lines"s3",endpoint_url=f"http://{settings.MINIO_ENDPOINT}",aws_access_key_id=settings.MINIO_ACCESS_KEY,aws_secret_access_key=settings.MINIO_SECRET_KEY,config=Config(signature_version="s3v4"),region_name="us-east-1",)self._ensure_minio_bucket()27 unmodified lines282930313233343527 unmodified lines"s3",endpoint_url=f"http://{settings.MINIO_ENDPOINT}",aws_access_key_id=settings.MINIO_ACCESS_KEY,aws_secret_access_key=settings.MINIO_SECRET_KEY.get_secret_value() if hasattr(settings.MINIO_SECRET_KEY, 'get_secret_value') else settings.MINIO_SECRET_KEY,config=Config(signature_version="s3v4", s3={'addressing_style': 'path'}),region_name="us-east-1",)self._ensure_minio_bucket()
55 unmodified lines565758596061626342 unmodified lines1061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631643 unmodified lines16816917017117217322 unmodified lines19619719819920020120220320420520620719 unmodified lines2272282292302312322332342352362372382392408 unmodified lines2492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842 unmodified lines28728828929029129229329429529629752 unmodified lines35035135235335435535635735855 unmodified linesdef _as_float(value: str) -> float | None:try:return float(value.replace(",", ""))except ValueError:return None42 unmodified linesstarted = time.perf_counter()suffix = Path(filename or storage_path).suffix.lower()mime_type = mimetypes.guess_type(filename or storage_path)[0] or "application/octet-stream"page_images = await asyncio.to_thread(self._render_page_images, file_bytes, suffix)raw_text = ""candidates: dict[str, dict[str, Any]] = {}if settings.CLOUD_LLM_ONLY:if suffix == ".pdf" or mime_type == "application/pdf":direct_candidate = await asyncio.to_thread(self._extract_pdf_text, file_bytes)raw_text = direct_candidate.get("text", "")if direct_candidate.get("fields") or direct_candidate.get("text"):candidates["pdf_text"] = direct_candidateif settings.ENABLE_AZURE_DI_AGENT:azure_candidate = await self._run_azure(file_bytes, mime_type)if azure_candidate.get("fields") or azure_candidate.get("text"):candidates["azure-di"] = azure_candidateraw_text = "\n".join(part for part in [raw_text, azure_candidate.get("text", "")] if part)quality_score = self._estimate_quality(page_images) if page_images else 0.0page_data_urls = [_data_url(b) for b in page_images[: settings.OCR_MAX_LLM_PAGES]]return {"pages": page_data_urls,"raw_text": raw_text,"ocr_candidates": candidates,"quality_score": quality_score,"ocr_engine_latencies_ms": {name: candidate.get("latency_ms") for name, candidate in candidates.items()},}pdf_task = Noneif suffix == ".pdf" or mime_type == "application/pdf":pdf_task = asyncio.to_thread(self._extract_pdf_text, file_bytes)paddle_task = self._run_paddle(page_images)azure_task = self._run_azure(file_bytes, mime_type) if self._azure_enabled() else Nonegather_tasks = [paddle_task]if azure_task is not None:gather_tasks.append(azure_task)if pdf_task is not None:gather_tasks.insert(0, pdf_task)results = await asyncio.gather(*gather_tasks)idx = 0if pdf_task is not None:direct_candidate = results[idx]idx += 1raw_text = direct_candidate.get("text", "")if direct_candidate.get("fields"):candidates["pdf_text"] = direct_candidatepaddle_candidate = results[idx]idx += 13 unmodified linespart for part in [raw_text, paddle_candidate.get("text", "")] if part)if azure_task is not None:azure_candidate = results[idx]if azure_candidate.get("fields") or azure_candidate.get("text"):22 unmodified lines"raw_text": raw_text,"ocr_candidates": candidates,"quality_score": quality_score,"ocr_engine_latencies_ms": {name: candidate.get("latency_ms") for name, candidate in candidates.items()},}def _render_page_images(self, file_bytes: bytes, suffix: str) -> list[bytes]:if suffix == ".pdf":try:import fitz19 unmodified linesimport pdfplumberwith pdfplumber.open(io.BytesIO(file_bytes)) as pdf:text = "\n".join((page.extract_text() or "") for page in pdf.pages)fields = extract_ceisa_fields_from_text(text)confidence = 0.98 if text.strip() else 0.0return {"fields": fields,"text": text,"confidence": confidence,"overall_confidence": confidence,"latency_ms": round((time.perf_counter() - started) * 1000, 2),}except Exception as exc:8 unmodified linesdef _run_paddle_sync(self, page_images: list[bytes]) -> dict[str, Any]:started = time.perf_counter()try:if self._paddle is None:from paddleocr import PaddleOCRtry:self._paddle = PaddleOCR(use_angle_cls=True,lang=settings.PADDLEOCR_LANG,show_log=False,)except TypeError:self._paddle = PaddleOCR(use_angle_cls=True, lang=settings.PADDLEOCR_LANG)lines: list[str] = []confidences: list[float] = []with tempfile.TemporaryDirectory(prefix="tradeflow-paddle-") as tmpdir:for index, image_bytes in enumerate(page_images):image_path = Path(tmpdir) / f"page-{index}.png"image_path.write_bytes(image_bytes)result = self._paddle.ocr(str(image_path), cls=True)for page in result or []:for item in page or []:if len(item) >= 2 and isinstance(item[1], (list, tuple)):text = str(item[1][0])confidence = float(item[1][1])if text.strip():lines.append(text)confidences.append(confidence)text = "\n".join(lines)confidence = sum(confidences) / len(confidences) if confidences else 0.0return {"fields": extract_ceisa_fields_from_text(text),"text": text,2 unmodified lines"latency_ms": round((time.perf_counter() - started) * 1000, 2),}except Exception as exc:log.warning("PaddleOCR failed", error=str(exc))return {"fields": {}, "text": "", "confidence": 0.0, "error": str(exc)}async def _run_azure(self, file_bytes: bytes, mime_type: str) -> dict[str, Any]:if not self._azure_enabled():return {"fields": {}, "text": "", "confidence": 0.0}if not settings.AZURE_DI_ENDPOINT or not settings.AZURE_DI_KEY:log.warning("Azure DI not configured; dual OCR is degraded to PaddleOCR only")52 unmodified lineslog.warning("Azure DI failed", error=str(exc))return {"fields": {}, "text": "", "confidence": 0.0, "error": str(exc)}def _azure_enabled(self) -> bool:return bool(settings.ENABLE_AZURE_DI_AGENT and settings.ENABLE_DUAL_OCR)def _estimate_quality(self, page_images: list[bytes]) -> float:if not page_images:return 0.055 unmodified lines5657585960616263646566676869707142 unmodified lines1141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741753 unmodified lines17918018118218318418518618718818919019119219322 unmodified lines21621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426519 unmodified lines2852862872882892902912922932942952962972982993003013023033043058 unmodified lines3143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054062 unmodified lines40941041141241341441541641741841942052 unmodified lines47347447547647747855 unmodified linesdef _as_float(value: str) -> float | None:try:# Handle European format: "11,603.000" (comma = thousands separator)# Detect if comma is used as thousands: e.g., "11,603.000" has comma before 3+ digits before decimalcleaned = value.strip()if re.search(r"\d,\d{3}(\.|$)", cleaned):cleaned = cleaned.replace(",", "")else:# Could be decimal comma: "11.603,000" -> 11603.0cleaned = cleaned.replace(".", "").replace(",", ".")return float(cleaned)except (ValueError, AttributeError):return None42 unmodified linesstarted = time.perf_counter()suffix = Path(filename or storage_path).suffix.lower()mime_type = mimetypes.guess_type(filename or storage_path)[0] or "application/octet-stream"is_pdf = suffix == ".pdf" or mime_type == "application/pdf"raw_text = ""candidates: dict[str, dict[str, Any]] = {}if is_pdf:direct_candidate = await asyncio.to_thread(self._extract_pdf_text, file_bytes)raw_text = direct_candidate.get("text", "")if direct_candidate.get("fields") or raw_text.strip():candidates["pdf_text"] = direct_candidateif self._is_pdf_text_fast_path(direct_candidate):latency_ms = round((time.perf_counter() - started) * 1000, 2)log.info("Digital PDF fast path selected",doc_id=doc_id,storage_path=storage_path,text_chars=direct_candidate.get("text_chars"),text_chars_per_page=direct_candidate.get("text_chars_per_page"),fields=list((direct_candidate.get("fields") or {}).keys()),latency_ms=latency_ms,)return {"pages": [],"raw_text": raw_text,"ocr_candidates": candidates,"quality_score": float(direct_candidate.get("confidence") or 1.0),"document_mode": "digital_pdf_text","ocr_engine_latencies_ms": {name: candidate.get("latency_ms") for name, candidate in candidates.items()},}page_images = await asyncio.to_thread(self._render_page_images, file_bytes, suffix)if settings.CLOUD_LLM_ONLY:page_data_urls = [_data_url(b) for b in page_images[: settings.OCR_MAX_LLM_PAGES]]return {"pages": page_data_urls,"raw_text": "","ocr_candidates": {},"quality_score": 1.0,"ocr_engine_latencies_ms": {}}paddle_task = self._run_paddle(page_images)surya_task = self._run_surya(page_images) if settings.ENABLE_SURYA_AGENT else Noneazure_task = self._run_azure(file_bytes, mime_type) if settings.ENABLE_DUAL_OCR else Nonegather_tasks = [paddle_task]if surya_task is not None:gather_tasks.append(surya_task)if azure_task is not None:gather_tasks.append(azure_task)results = await asyncio.gather(*gather_tasks)idx = 0paddle_candidate = results[idx]idx += 13 unmodified linespart for part in [raw_text, paddle_candidate.get("text", "")] if part)if surya_task is not None:surya_candidate = results[idx]idx += 1if surya_candidate.get("fields") or surya_candidate.get("text"):candidates["surya"] = surya_candidateraw_text = "\n".join(part for part in [raw_text, surya_candidate.get("text", "")] if part)if azure_task is not None:azure_candidate = results[idx]if azure_candidate.get("fields") or azure_candidate.get("text"):22 unmodified lines"raw_text": raw_text,"ocr_candidates": candidates,"quality_score": quality_score,"document_mode": "rendered_ocr","ocr_engine_latencies_ms": {name: candidate.get("latency_ms") for name, candidate in candidates.items()},}def _is_pdf_text_fast_path(self, candidate: dict[str, Any]) -> bool:"""Use direct PDF text when the text layer is dense enough to avoid heavy OCR."""text_chars = int(candidate.get("text_chars") or 0)page_count = max(1, int(candidate.get("page_count") or 1))text_chars_per_page = text_chars / page_countconfidence = float(candidate.get("confidence") or 0.0)return (confidence >= settings.OCR_FAST_PATH_QUALITY_THRESHOLDand text_chars >= settings.OCR_PDF_TEXT_MIN_CHARSand text_chars_per_page >= settings.OCR_PDF_TEXT_MIN_CHARS_PER_PAGE)def _render_page_images(self, file_bytes: bytes, suffix: str) -> list[bytes]:"""Call MinerU microservice for preprocessing and rendering."""try:import httpxb64_content = base64.b64encode(file_bytes).decode("ascii")payload = {"document_id": "temp","doc_type": "invoice","content_b64": b64_content,"filename": f"temp{suffix}"}url = f"{str(settings.MINERU_SVC_URL).rstrip('/')}/preprocess"with httpx.Client(timeout=30.0) as client:response = client.post(url, json=payload)response.raise_for_status()data = response.json()images = []for page in data.get("pages", []):images.append(base64.b64decode(page["image_b64"]))if images:return imagesexcept Exception as exc:log.warning("MinerU preprocessing failed, falling back to local PyMuPDF", error=str(exc))# Fallback to local renderingif suffix == ".pdf":try:import fitz19 unmodified linesimport pdfplumberwith pdfplumber.open(io.BytesIO(file_bytes)) as pdf:pages = pdf.pagestext = "\n".join((page.extract_text() or "") for page in pages)fields = extract_ceisa_fields_from_text(text)text_chars = len(re.sub(r"\s+", "", text))page_count = len(pages) or 1text_chars_per_page = round(text_chars / page_count, 2)confidence = 1.0 if text_chars_per_page >= settings.OCR_PDF_TEXT_MIN_CHARS_PER_PAGE else 0.0return {"fields": fields,"text": text,"confidence": confidence,"overall_confidence": confidence,"page_count": page_count,"text_chars": text_chars,"text_chars_per_page": text_chars_per_page,"latency_ms": round((time.perf_counter() - started) * 1000, 2),}except Exception as exc:8 unmodified linesdef _run_paddle_sync(self, page_images: list[bytes]) -> dict[str, Any]:started = time.perf_counter()try:import httpximages_b64 = [base64.b64encode(img).decode("ascii") for img in page_images]url = f"{str(settings.PADDLEOCR_SVC_URL).rstrip('/')}/extract"lines = []confidences = []with httpx.Client(timeout=300.0) as client:for img_b64 in images_b64:payload = {"image_b64": img_b64,"doc_type": "bill_of_lading"}response = client.post(url, json=payload)response.raise_for_status()result = response.json()for text_block in result.get("text_blocks_with_bbox", []):text = text_block.get("text", "")conf = text_block.get("confidence", 0.0)if text.strip():lines.append(text)confidences.append(conf)text = "\n".join(lines)confidence = sum(confidences) / len(confidences) if confidences else 0.0return {"fields": extract_ceisa_fields_from_text(text),"text": text,"confidence": confidence,"overall_confidence": confidence,"latency_ms": round((time.perf_counter() - started) * 1000, 2),}except Exception as exc:log.warning("PaddleOCR HTTP failed", error=str(exc))return {"fields": {}, "text": "", "confidence": 0.0, "error": str(exc)}async def _run_surya(self, page_images: list[bytes]) -> dict[str, Any]:if not page_images:return {"fields": {}, "text": "", "confidence": 0.0}return await asyncio.to_thread(self._run_surya_sync, page_images)def _run_surya_sync(self, page_images: list[bytes]) -> dict[str, Any]:started = time.perf_counter()try:import httpximages_b64 = [base64.b64encode(img).decode("ascii") for img in page_images]payload = {"images_b64": images_b64,"languages": ["en", "id"]}url = f"{str(settings.SURYA_INFERENCE_URL).rstrip('/')}/extract"with httpx.Client(timeout=600.0) as client:response = client.post(url, json=payload)response.raise_for_status()result = response.json()# Surya v2 response: text_blocks is list[list[dict]] (per page, per block)# Each block has: { text, html, confidence, bbox, polygon, label }lines = []confidences = []text_blocks = result.get("text_blocks", [])for page_blocks in text_blocks:if isinstance(page_blocks, list):for block in page_blocks:text = block.get("text", "").strip()conf = float(block.get("confidence", 1.0))if text:lines.append(text)confidences.append(conf)elif isinstance(page_blocks, dict):# Fallback: old format where text_blocks is flat list of dictstext = page_blocks.get("text", "").strip()conf = float(page_blocks.get("confidence", 1.0))if text:lines.append(text)confidences.append(conf)# Also handle legacy flat "text" fieldif not lines and result.get("text"):lines = [result["text"]]confidences = [result.get("confidence", result.get("overall_confidence", 0.0))]text = "\n".join(lines)confidence = sum(confidences) / len(confidences) if confidences else 0.0return {"fields": extract_ceisa_fields_from_text(text),"text": text,2 unmodified lines"latency_ms": round((time.perf_counter() - started) * 1000, 2),}except Exception as exc:log.warning("Surya OCR HTTP failed", error=str(exc))return {"fields": {}, "text": "", "confidence": 0.0, "error": str(exc)}async def _run_azure(self, file_bytes: bytes, mime_type: str) -> dict[str, Any]:if not settings.ENABLE_DUAL_OCR:return {"fields": {}, "text": "", "confidence": 0.0}if not settings.AZURE_DI_ENDPOINT or not settings.AZURE_DI_KEY:log.warning("Azure DI not configured; dual OCR is degraded to PaddleOCR only")52 unmodified lineslog.warning("Azure DI failed", error=str(exc))return {"fields": {}, "text": "", "confidence": 0.0, "error": str(exc)}def _estimate_quality(self, page_images: list[bytes]) -> float:if not page_images:return 0.0
214 unmodified lines21521621721821922022122222322422522622722822923023123223323423523623748 unmodified lines286287288289290291292293294295296297298299300301214 unmodified linesevaluator: SafeRuleEvaluator,context: dict[str, Any],) -> dict[str, Any]:try:passed = evaluator.evaluate(rule["check"])severity = "PASS" if passed else self._failure_severity(rule.get("severity"))message = rule.get("name", rule.get("rule_id", "Validation rule"))if not passed:message = self._format_message(rule.get("error_message") or message, context)except Exception as exc:severity = self._failure_severity(rule.get("severity"))message = f"{rule.get('name', rule.get('rule_id'))} could not be evaluated: {exc}"return {"rule_id": rule.get("rule_id", "UNKNOWN"),"rule_name": rule.get("name", rule.get("rule_id", "Validation rule")),"severity": severity,"message": message,"affected_fields": rule.get("affected_fields", []),}def _build_context(self, state: dict[str, Any]) -> dict[str, Any]:combined = state.get("combined_data") or {}48 unmodified linesreturn templatedef _failure_severity(self, severity: str | None) -> str:return "CRITICAL_FAIL" if severity == "CRITICAL" else "WARNING"def _resolve_rules_path(self) -> Path:configured = Path(settings.VALIDATION_RULES_PATH)candidates = [configured,Path.cwd() / configured,Path(__file__).resolve().parents[4] / configured,Path("/app/validation_rules.json"),]for candidate in candidates:if candidate.exists():return candidate.resolve()214 unmodified lines21521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638748 unmodified lines436437438439440441442443444445446447448449450451452453454455456457458459460461214 unmodified linesevaluator: SafeRuleEvaluator,context: dict[str, Any],) -> dict[str, Any]:rule_id = rule.get("rule_id") or rule.get("id", "UNKNOWN")rule_name = rule.get("name", rule_id)try:check_expr = rule.get("check")if not check_expr:legacy_result = self._evaluate_legacy_rule(rule, context)if legacy_result is not None:return legacy_result# Rule has no evaluable expression — skip as PASSreturn {"rule_id": rule_id,"rule_name": rule_name,"severity": "PASS","message": rule_name,"affected_fields": rule.get("affected_fields") or rule.get("fields", []),}passed = evaluator.evaluate(check_expr)severity = "PASS" if passed else self._failure_severity(rule.get("severity"))message = rule_nameif not passed:message = self._format_message(rule.get("error_message") or message, context)except Exception as exc:severity = self._failure_severity(rule.get("severity"))message = f"{rule_name} could not be evaluated: {exc}"return {"rule_id": rule_id,"rule_name": rule_name,"severity": severity,"message": message,"affected_fields": rule.get("affected_fields") or rule.get("fields", []),}def _evaluate_legacy_rule(self,rule: dict[str, Any],context: dict[str, Any],) -> dict[str, Any] | None:rule_type = rule.get("type")if not rule_type:return Nonerule_id = rule.get("rule_id") or rule.get("id", "UNKNOWN")rule_name = rule.get("name", rule_id)fields = rule.get("fields") or ([rule["field"]] if rule.get("field") else [])try:if rule_type in {"regex", "regex_and_lookup"}:field = fields[0] if fields else rule.get("field")value = self._first_context_value(context, field)if field in {"npwp", "nib"}:value = re.sub(r"\D", "", str(value or ""))passed = regex_match(value, rule.get("regex", ".*"))elif rule_type == "cross_document_match":passed = all(self._cross_document_values_match(context, field) for field in fields)elif rule_type == "cross_document":passed = self._evaluate_cross_document_rule(rule, context)elif rule_type == "date_sequence":passed = Trueelif rule_type == "lookup":passed = self._evaluate_lookup_rule(rule, context)else:return Noneexcept Exception as exc:passed = Falselog.warning("Legacy validation rule failed to evaluate", rule_id=rule_id, error=str(exc))severity = "PASS" if passed else self._legacy_failure_severity(rule_id, rule.get("severity"))return {"rule_id": rule_id,"rule_name": rule_name,"severity": severity,"message": rule_name if passed else rule.get("description") or rule_name,"affected_fields": rule.get("affected_fields") or fields,}def _field_aliases(self, field: str | None) -> list[str]:aliases = {"nomorBl": ["bl_number", "nomorBl"],"beratKotor": ["gross_weight", "beratKotor"],"jumlahKemasan": ["total_packages", "jumlahKemasan"],"namaKapal": ["vessel_name", "namaKapal"],"voyageNumber": ["voyage_number", "voyageNumber"],"kodePelabuhanMuat": ["port_of_loading", "kodePelabuhanMuat"],"kodePelabuhanBongkar": ["port_of_discharge", "kodePelabuhanBongkar"],"hs_code": ["hs_code", "posTarif"],"nib": ["importer_nib", "nib", "nibEntitas"],"npwp": ["importer_npwp", "npwp", "nomorIdentitas"],"container_number": ["container_numbers", "container_number"],}if not field:return []return aliases.get(field, [field])def _scope_value(self, scope: Any, field: str | None) -> Any:for alias in self._field_aliases(field):value = _unwrap(getattr(scope, alias, MISSING))if value not in (None, "", MISSING):return valuereturn Nonedef _first_context_value(self, context: dict[str, Any], field: str | None) -> Any:for scope_name in ("data", "inv", "pl", "bl", "item", "importir"):value = self._scope_value(context[scope_name], field)if value not in (None, "", MISSING):return valuereturn Nonedef _cross_document_values_match(self, context: dict[str, Any], field: str) -> bool:values = [self._normalize_compare_value(self._scope_value(context[scope_name], field))for scope_name in ("bl", "pl", "inv")]present = [value for value in values if value not in (None, "")]if len(present) < 2:return Falsereturn len(set(present)) == 1def _normalize_compare_value(self, value: Any) -> str | None:if value is None or value is MISSING:return Noneif isinstance(value, (int, float)):return str(round(float(value), 4))return re.sub(r"\s+", " ", str(value)).strip().upper()def _evaluate_cross_document_rule(self, rule: dict[str, Any], context: dict[str, Any]) -> bool:rule_id = rule.get("rule_id") or rule.get("id")tolerance_pct = float(rule.get("tolerance_pct") or 0)if rule_id == "CV002" or not rule.get("fields"):cif = self._as_float(self._scope_value(context["inv"], "cif_value"))fob = self._as_float(self._scope_value(context["inv"], "fob_value"))freight = self._as_float(self._scope_value(context["inv"], "freight_value"))insurance = self._as_float(self._scope_value(context["inv"], "insurance_value"))if None in (cif, fob, freight, insurance) or not cif:return Falsediff_pct = abs(cif - (fob + freight + insurance)) / cif * 100return diff_pct <= tolerance_pctfor field in rule.get("fields") or []:values = [self._as_float(self._scope_value(context[scope_name], field))for scope_name in ("bl", "pl", "inv")]present = [value for value in values if value is not None]if len(present) < 2:return Falsebaseline = present[0]if baseline == 0:return all(value == 0 for value in present)if any(abs(value - baseline) / abs(baseline) * 100 > tolerance_pct for value in present[1:]):return Falsereturn Truedef _evaluate_lookup_rule(self, rule: dict[str, Any], context: dict[str, Any]) -> bool:for field in rule.get("fields") or []:value = str(self._first_context_value(context, field) or "")if field in {"kodePelabuhanMuat", "kodePelabuhanBongkar"} and not re.search(r"\b[A-Z]{5}\b", value):return Falsereturn Truedef _as_float(self, value: Any) -> float | None:if value in (None, "", MISSING):return Nonetry:return float(str(value).replace(",", ""))except (TypeError, ValueError):return Nonedef _build_context(self, state: dict[str, Any]) -> dict[str, Any]:combined = state.get("combined_data") or {}48 unmodified linesreturn templatedef _failure_severity(self, severity: str | None) -> str:return "CRITICAL_FAIL" if severity in {"CRITICAL", "ERROR"} else "WARNING"def _legacy_failure_severity(self, rule_id: str, severity: str | None) -> str:if rule_id in {"CV001", "CV002", "CV003", "CV006", "CV008"}:return "CRITICAL_FAIL"return self._failure_severity(severity)def _resolve_rules_path(self) -> Path:configured = Path(settings.VALIDATION_RULES_PATH)candidates = [configured,Path.cwd() / configured,Path("/app/validation_rules.json"),]try:candidates.append(Path(__file__).resolve().parents[4] / configured)except IndexError:passfor candidate in candidates:if candidate.exists():return candidate.resolve()
97 unmodified lines98991001011021031041051061071081091101111121131141151161171181191201211221231241251261271283 unmodified lines13213313413513613713813914014114214314414514614714814997 unmodified linesawait supabase.table("batches").update({"status": status,"risk_level": result.get("risk_level"),"customs_readiness_score": result.get("_crs_score"),"crs_grade": result.get("_crs_grade"),"rejection_probability": result.get("_rejection_prob"),"langgraph_thread_id": batch_id,}).eq("id", batch_id).execute()finally:passdef _average_confidence(confidences: dict) -> float:values = [float(value) for value in confidences.values()]return round(sum(values) / len(values), 4) if values else 0.0@celery_app.task(bind=True, queue="high", max_retries=3, default_retry_delay=10)def preprocess_document(self, batch_id: str) -> None:"""Entry point: kicks off LangGraph extraction pipeline."""import asynciofrom ..ai.graph import extraction_graphlog.info("Starting extraction pipeline", batch_id=batch_id)try:from .celery_app import get_worker_looploop = get_worker_loop()config = {"configurable": {"thread_id": batch_id}}context = loop.run_until_complete(_load_batch_context(batch_id))initial_state = {"batch_id": batch_id,3 unmodified lines"validation_results": [],"needs_human_review": False,"risk_level": "UNKNOWN","ocr_conflicts": [],"field_confidences": {},"steps": [],}# Run sync wrapper around async graphresult = loop.run_until_complete(extraction_graph.ainvoke(initial_state, config=config))loop.run_until_complete(_persist_graph_result(batch_id, result))log.info("Extraction pipeline complete", batch_id=batch_id)except Exception as exc:log.error("Pipeline failed", batch_id=batch_id, error=str(exc))raise self.retry(exc=exc)97 unmodified lines98991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451463 unmodified lines15015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618797 unmodified linesawait supabase.table("batches").update({"status": status,"risk_level": result.get("risk_level"),"customs_readiness_score": result.get("customs_readiness_score", result.get("_crs_score")),"crs_grade": result.get("crs_grade", result.get("_crs_grade")),"rejection_probability": result.get("rejection_probability", result.get("_rejection_prob")),"langgraph_thread_id": batch_id,}).eq("id", batch_id).execute()finally:passasync def _update_batch_status(batch_id: str, status: str, error_message: str | None = None) -> None:"""Best-effort status update for the upload/detail UI."""from supabase import acreate_clientfrom ..config import settingssupabase = await acreate_client(settings.SUPABASE_URL, settings.SUPABASE_SERVICE_KEY.get_secret_value())payload = {"status": status}try:await supabase.table("batches").update(payload).eq("id", batch_id).execute()except Exception as exc:log.warning("Failed to update batch status",batch_id=batch_id,status=status,pipeline_error=error_message,error=str(exc),)def _average_confidence(confidences: dict) -> float:values = [float(value) for value in confidences.values()]return round(sum(values) / len(values), 4) if values else 0.0def run_preprocess_pipeline_sync(batch_id: str, mark_error_on_failure: bool = False) -> None:"""Run the extraction pipeline in-process when Celery is unavailable."""from ..ai.graph import extraction_graphfrom .celery_app import get_worker_looploop = get_worker_loop()try:config = {"configurable": {"thread_id": batch_id}}loop.run_until_complete(_update_batch_status(batch_id, "ocr_running"))context = loop.run_until_complete(_load_batch_context(batch_id))initial_state = {"batch_id": batch_id,3 unmodified lines"validation_results": [],"needs_human_review": False,"risk_level": "UNKNOWN","customs_readiness_score": None,"crs_grade": None,"rejection_probability": None,"risk_features": {},"ocr_conflicts": [],"field_confidences": {},"steps": [],}result = loop.run_until_complete(extraction_graph.ainvoke(initial_state, config=config))loop.run_until_complete(_persist_graph_result(batch_id, result))except Exception as exc:if mark_error_on_failure:loop.run_until_complete(_update_batch_status(batch_id, "error", str(exc)))raise@celery_app.task(bind=True, queue="high", max_retries=3, default_retry_delay=10)def preprocess_document(self, batch_id: str) -> None:"""Entry point: kicks off LangGraph extraction pipeline."""log.info("Starting extraction pipeline", batch_id=batch_id)try:run_preprocess_pipeline_sync(batch_id)log.info("Extraction pipeline complete", batch_id=batch_id)except Exception as exc:log.error("Pipeline failed", batch_id=batch_id, error=str(exc))if self.request.retries >= self.max_retries:from .celery_app import get_worker_looploop = get_worker_loop()loop.run_until_complete(_update_batch_status(batch_id, "error", str(exc)))raise self.retry(exc=exc)
pyproject.toml+1
src/ai/graph.py+1-8
src/ai/nodes/extract.py+315-113
src/ai/nodes/fallback_ocr.py+4-1
src/ai/nodes/risk.py+17
src/ai/nodes/validate.py+11-1
src/ai/state.py+4
src/config.py+26-18
src/dependencies.py+1-8
src/main.py+1-33
src/routers/batches.py+30-90
src/scripts/backfill_batch_risk.pyAdded+106
src/scripts/recompute_field_confidences.pyAdded+109
src/scripts/revalidate_batch.pyAdded+129
src/services/ingest_svc.py+2-2
src/services/ocr_engine_svc.py+192-72
src/services/validation_rules_svc.py+168-8
src/tasks/ocr_tasks.py+50-12