chouchouvs commited on
Commit
b14344f
·
verified ·
1 Parent(s): e0fbdb8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -131
app.py CHANGED
@@ -1,145 +1,88 @@
1
  """
2
- app.py
3
- ------
4
-
5
- Application Gradio pour le Space Hugging Face CCPU.
6
-
7
- Ce fichier :
8
-
9
- - Crée une interface Gradio minimale pour téléverser un PDF de certificat CCPU,
10
- lancer l'extraction via le backend `ccpu_parser.extract.extract_ccpu_from_pdf`,
11
- et afficher le JSON résultant.
12
- - Fournit automatiquement une API HTTP Gradio exploitable par Excel/VBA
13
- (endpoints auto-générés par le SDK gradio des Spaces).
14
-
15
- Fonction principale exposée :
16
- - `analyze_ccpu_bytes(pdf_bytes: bytes | None) -> dict`
17
  """
18
 
19
- from __future__ import annotations
20
-
21
- import json
22
- from typing import Optional
23
-
24
  import gradio as gr
25
 
26
- from ccpu_parser.extract import extract_ccpu_from_pdf
27
- from ccpu_parser.schemas import CCPUResult
28
- from ccpu_parser.utils import logger
29
-
30
-
31
- def analyze_ccpu_bytes(pdf_bytes: Optional[bytes]) -> dict:
32
- """
33
- Fonction de prédiction Gradio.
34
-
35
- Paramètres
36
- ----------
37
- pdf_bytes : bytes | None
38
- Contenu binaire du fichier PDF transmis par le composant gr.File(type="binary").
39
-
40
- Retour
41
- ------
42
- dict
43
- Dictionnaire compatible avec le modèle CCPUResult (certificate / parameters / warnings).
44
-
45
- Exceptions
46
- ----------
47
- gr.Error
48
- - si aucun fichier n'est fourni
49
- - si l'extraction échoue
50
- """
51
- if pdf_bytes is None:
52
- raise gr.Error("Merci de déposer un fichier PDF de certificat matière (CCPU).")
53
-
54
- try:
55
- logger.info(
56
- "Analyse CCPU lancée via Gradio (taille PDF = %d octets).",
57
- len(pdf_bytes),
58
- )
59
- result: CCPUResult = extract_ccpu_from_pdf(pdf_bytes)
60
- logger.info(
61
- "Analyse terminée : %d paramètre(s), %d warning(s).",
62
- len(result.parameters),
63
- len(result.warnings),
64
- )
65
- # Gradio sait renvoyer directement un dict dans gr.JSON, on passe par .dict()
66
- return result.dict()
67
- except Exception as exc: # noqa: BLE001
68
- logger.exception("Erreur lors de l'analyse CCPU via Gradio : %s", exc)
69
- raise gr.Error(f"Erreur lors de l'analyse du PDF : {exc}") from exc
70
-
71
-
72
- with gr.Blocks(title="CCPU Certificate Parser") as app:
73
- """
74
- Définition de l'interface Gradio :
75
-
76
- - Un upload de fichier PDF
77
- - Un bouton "Analyser"
78
- - Un composant JSON pour afficher la structure complète CCPUResult
79
- - Un petit log textuel optionnel
80
- """
81
-
82
- gr.Markdown(
83
- """
84
- # 🧾 CCPU Certificate Parser
85
-
86
- Téléverse un certificat matière (EN 10204 2.2 / 3.1) au format PDF.
87
- L'outil extrait les tableaux (chimie, mécanique, résilience, dureté...)
88
- et renvoie une structure JSON normalisée (certificate / parameters / warnings).
89
- """
90
- )
91
-
92
- with gr.Row():
93
- file_input = gr.File(
94
- label="Certificat CCPU (.pdf)",
95
- file_types=[".pdf"],
96
- type="binary", # → bytes directement dans analyze_ccpu_bytes
97
  )
 
98
 
99
- with gr.Row():
100
- analyze_btn = gr.Button("Analyser le certificat", variant="primary")
101
 
102
- with gr.Row():
103
- json_output = gr.JSON(
104
- label="Résultat JSON (CCPUResult)",
105
- value=None,
106
- )
107
-
108
- status_box = gr.Markdown("Status : en attente de fichier...")
109
-
110
- def _wrapped_analyze(pdf_bytes: Optional[bytes]) -> tuple[dict, str]:
111
- """
112
- Petit wrapper pour mettre à jour à la fois le JSON et le statut.
113
- """
114
  if pdf_bytes is None:
115
- raise gr.Error("Merci de déposer un fichier PDF.")
116
-
117
- result_dict = analyze_ccpu_bytes(pdf_bytes)
118
- status = (
119
- f"Analyse terminée. Paramètres extraits : "
120
- f"{len(result_dict.get('parameters', []))}."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  )
122
- return result_dict, status
123
-
124
- analyze_btn.click(
125
- fn=_wrapped_analyze,
126
- inputs=file_input,
127
- outputs=[json_output, status_box],
128
- )
129
-
130
- gr.Markdown(
131
- """
132
- ### ℹ️ API
133
 
134
- Ce Space Gradio expose aussi une API HTTP (Hugging Face Spaces) :
 
 
 
 
135
 
136
- - Endpoint `POST /` via l'API Gradio standard,
137
- - Ou via le endpoint auto-généré `POST /run/predict` (cf. docs HF/Gradio).
138
 
139
- Depuis Excel/VBA ou Python, tu pourras appeler cette API en envoyant le PDF
140
- et en récupérant directement le JSON affiché ci-dessus.
141
- """
142
- )
143
 
144
- # Pour un Space `sdk=gradio`, Hugging Face attend une variable de haut niveau `app`
145
- # qui contient un objet gr.Blocks ou gr.Interface. C'est le cas ici.
 
1
  """
2
+ app.py (version debug)
3
+ ----------------------
4
+
5
+ Mode ultra-robuste pour Hugging Face sdk=gradio :
6
+ - Aucun import critique n'est exécuté sans capture.
7
+ - On affiche explicitement chaque étape dans les logs.
8
+ - Si le backend ccpu_parser plante à l'import, on démarre quand même
9
+ une mini UI Gradio d'erreur pour ne pas faire mourir le container.
 
 
 
 
 
 
 
10
  """
11
 
12
+ import traceback
 
 
 
 
13
  import gradio as gr
14
 
15
+ print(">>> [Startup] Import app.py lancé...")
16
+
17
+ # Tentative d'import du backend
18
+ BACKEND_OK = False
19
+ try:
20
+ from ccpu_parser.extract import extract_ccpu_from_pdf
21
+ from ccpu_parser.schemas import CCPUResult
22
+ from ccpu_parser.utils import logger
23
+ BACKEND_OK = True
24
+ print(">>> [Startup] Backend ccpu_parser importé avec succès.")
25
+ except Exception as e:
26
+ print(">>> [Startup ERROR] Échec import backend :", e)
27
+ traceback.print_exc()
28
+ logger = None
29
+
30
+
31
+ def _fallback_app() -> gr.Blocks:
32
+ """Mini UI affichée si le backend ne se charge pas."""
33
+ with gr.Blocks(title="CCPU Parser - erreur import") as demo:
34
+ gr.Markdown(
35
+ "### ❌ Erreur d'initialisation du backend CCPU\n"
36
+ "Le module `ccpu_parser` n'a pas pu être importé.\n\n"
37
+ "Vérifie la console pour les détails (import PyMuPDF, dépendances, etc.)."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  )
39
+ return demo
40
 
 
 
41
 
42
+ if BACKEND_OK:
43
+ # Version normale (backend chargé)
44
+ def analyze_ccpu_bytes(pdf_bytes: bytes | None) -> dict:
 
 
 
 
 
 
 
 
 
45
  if pdf_bytes is None:
46
+ raise gr.Error("Merci de déposer un fichier PDF de certificat matière (CCPU).")
47
+ try:
48
+ logger.info(
49
+ "Analyse CCPU via Gradio (taille PDF = %d octets).", len(pdf_bytes)
50
+ )
51
+ result: CCPUResult = extract_ccpu_from_pdf(pdf_bytes)
52
+ logger.info(
53
+ "Analyse terminée : %d paramètre(s), %d warning(s).",
54
+ len(result.parameters),
55
+ len(result.warnings),
56
+ )
57
+ return result.dict()
58
+ except Exception as exc:
59
+ traceback.print_exc()
60
+ raise gr.Error(f"Erreur lors de l'analyse du PDF : {exc}") from exc
61
+
62
+ with gr.Blocks(title="CCPU Certificate Parser") as app:
63
+ gr.Markdown(
64
+ """
65
+ # 🧾 CCPU Certificate Parser
66
+
67
+ Téléverse un certificat matière (EN 10204 2.2 / 3.1) au format PDF,
68
+ et obtiens la structure JSON extraite automatiquement.
69
+ """
70
  )
71
+ file_input = gr.File(label="Certificat CCPU (.pdf)", type="binary")
72
+ analyze_btn = gr.Button("Analyser", variant="primary")
73
+ json_output = gr.JSON(label="Résultat JSON")
74
+ status_box = gr.Markdown("Status : en attente...")
 
 
 
 
 
 
 
75
 
76
+ def _wrapped(pdf_bytes):
77
+ if pdf_bytes is None:
78
+ raise gr.Error("Merci de déposer un PDF.")
79
+ data = analyze_ccpu_bytes(pdf_bytes)
80
+ return data, f"Analyse terminée ({len(data.get('parameters', []))} paramètres)."
81
 
82
+ analyze_btn.click(fn=_wrapped, inputs=file_input, outputs=[json_output, status_box])
 
83
 
84
+ else:
85
+ # Backend KO : fallback interface pour éviter crash HF
86
+ app = _fallback_app()
 
87
 
88
+ print(">>> [Startup] Gradio app initialisée.")