File size: 3,004 Bytes
5762b96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
"""
ccpu_parser.postprocess
-----------------------

Post-traitement léger du JSON renvoyé par le LLM :
- normalisation minimale,
- ajout de warnings automatiques,
- validation via Pydantic (CCPUResult).
"""

from __future__ import annotations

from typing import Any, Dict, List

from .schemas import CCPUResult, Certificate, Parameter
from .utils import logger


def _ensure_certificate(raw: Dict[str, Any]) -> Dict[str, Any]:
    cert = raw.get("certificate") or {}
    if not isinstance(cert, dict):
        cert = {}

    cert.setdefault("type_doc", "UNKNOWN")
    cert.setdefault("norme_declared", None)
    cert.setdefault("grade_declared", None)
    cert.setdefault("supplier", None)
    cert.setdefault("customer", None)
    cert.setdefault("certificate_id", None)
    cert.setdefault("heat_number", None)
    cert.setdefault("batch_number", None)
    cert.setdefault("issue_date", None)
    cert.setdefault("language", None)
    cert.setdefault("notes", None)

    return cert


def _ensure_parameters(raw: Dict[str, Any]) -> List[Dict[str, Any]]:
    params = raw.get("parameters") or []
    if not isinstance(params, list):
        params = []

    cleaned: List[Dict[str, Any]] = []
    for item in params:
        if not isinstance(item, dict):
            continue

        label_raw = item.get("label_raw")
        if not label_raw:
            # on laisse tomber les lignes sans libellé exploitable
            continue

        pos = item.get("position_hint") or {}
        if not isinstance(pos, dict):
            pos = {}
        item["position_hint"] = {
            "page": pos.get("page"),
            "row_index": pos.get("row_index"),
            "col_index": pos.get("col_index"),
        }

        cleaned.append(item)

    return cleaned


def _ensure_warnings(raw: Dict[str, Any]) -> List[str]:
    warnings = raw.get("warnings") or []
    if not isinstance(warnings, list):
        warnings = [str(warnings)]
    return [str(w) for w in warnings]


def postprocess_llm_json(raw: Dict[str, Any]) -> CCPUResult:
    """
    Transforme le dictionnaire brut venant du LLM en CCPUResult validé.
    Ajoute quelques warnings génériques.
    """
    cert_dict = _ensure_certificate(raw)
    params_list = _ensure_parameters(raw)
    warnings_list = _ensure_warnings(raw)

    if cert_dict.get("type_doc") not in ("CCPU_3.1", "CCPU_2.2"):
        warnings_list.append(
            "type_doc is UNKNOWN or missing explicit EN 10204 3.1/2.2 reference."
        )

    if not params_list:
        warnings_list.append("No parameters extracted from the document.")

    certificate = Certificate(**cert_dict)
    parameters: List[Parameter] = []
    for p in params_list:
        try:
            parameters.append(Parameter(**p))
        except Exception as exc:  # noqa: BLE001
            logger.warning("Dropping invalid parameter %s: %s", p, exc)

    return CCPUResult(
        certificate=certificate,
        parameters=parameters,
        warnings=warnings_list,
    )