Spaces:
Sleeping
Sleeping
Download app.py from chouchouvs/ccpu: direct link, hf CLI and curl.
- Browser
- Download file 11.3 kB
-
https://huggingface.co/spaces/chouchouvs/ccpu/resolve/main/app.py
- Command line
-
hf download hf://spaces/chouchouvs/ccpu/app.py
-
curl -L -o app.py https://huggingface.co/spaces/chouchouvs/ccpu/resolve/main/app.py
11.3 kB
| # app.py | |
| # -*- coding: utf-8 -*- | |
| """ | |
| app.py — Point d'entrée Gradio du Space CCPU | |
| ============================================ | |
| Ce que fait ce fichier | |
| ---------------------- | |
| - Initialise l'interface Gradio du Space CCPU. | |
| - Gère l'upload de certificats matière au format PDF ou image. | |
| - Appelle le pipeline haut niveau `extract_ccpu_from_pdf` pour produire | |
| un JSON structuré à partir du document. | |
| - Expose en plus un panneau d'administration permettant de pousser le dépôt | |
| courant du Space Hugging Face vers un dépôt GitHub via un token GitHub | |
| injecté dans les secrets d'environnement. | |
| Rôle du module | |
| -------------- | |
| - Servir d'orchestrateur UI entre : | |
| * l'analyse de certificats matière, | |
| * la future administration technique du Space, | |
| * et la synchronisation Git vers GitHub pour préparer une migration | |
| progressive vers un hébergement type Coolify / serveur personnel. | |
| Fonctions fournies | |
| ------------------ | |
| - analyze_ccpu_bytes(file_bytes: bytes) -> dict | |
| Point d'entrée métier pour l'analyse d'un certificat uploadé. | |
| - push_space_repo_to_github(commit_message: str | None) -> tuple[dict, str] | |
| Lance une synchronisation du dépôt courant vers GitHub et renvoie | |
| un résumé JSON + un message de statut lisible dans l'UI. | |
| - build_demo() -> gr.Blocks | |
| Construit l'interface complète du Space. | |
| Variables d'environnement attendues pour la sync GitHub | |
| ------------------------------------------------------- | |
| - GITHUB_TOKEN | |
| - GITHUB_REPO (format owner/repository) | |
| - GITHUB_BRANCH (optionnel, défaut côté module github_sync) | |
| - GITHUB_REMOTE_NAME (optionnel) | |
| - GITHUB_COMMITTER_NAME (optionnel) | |
| - GITHUB_COMMITTER_EMAIL (optionnel) | |
| Objet global | |
| ------------ | |
| - app : instance Gradio Blocks, utilisée par Hugging Face Spaces. | |
| """ | |
| from __future__ import annotations | |
| import os | |
| import traceback | |
| from typing import Any | |
| import gradio as gr | |
| from ccpu_parser.extract import extract_ccpu_from_pdf | |
| from ccpu_parser.utils import logger | |
| # --------------------------------------------------------------------------- | |
| # Import optionnel du module de synchronisation GitHub | |
| # --------------------------------------------------------------------------- | |
| try: | |
| from ccpu_parser.github_sync import sync_repo_to_github | |
| _GITHUB_SYNC_AVAILABLE = True | |
| except Exception as exc: | |
| sync_repo_to_github = None | |
| _GITHUB_SYNC_AVAILABLE = False | |
| logger.warning( | |
| "ccpu_parser - Module github_sync indisponible au démarrage : %s", | |
| exc, | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Fonction d'analyse appelée par Gradio | |
| # --------------------------------------------------------------------------- | |
| def analyze_ccpu_bytes(file_bytes: bytes) -> dict: | |
| """ | |
| Point d'entrée métier appelé par Gradio pour analyser un certificat matière. | |
| Paramètres | |
| ---------- | |
| file_bytes : bytes | |
| Contenu binaire du fichier uploadé. | |
| Peut être : | |
| - un PDF (texte ou scanné), | |
| - un fichier image (PNG, JPEG, JPG, etc.). | |
| Retour | |
| ------ | |
| dict | |
| Dictionnaire Python correspondant exactement au JSON structuré produit | |
| par le pipeline vision / LLM, typiquement de la forme : | |
| { | |
| "identification": { ... }, | |
| "detailsMateriau": { ... }, | |
| "analyseChimique": { ... }, | |
| "proprietesMecaniques": { ... }, | |
| "testsEffectues": { ... }, | |
| "conformite": { ... } | |
| } | |
| Exceptions | |
| ---------- | |
| gr.Error | |
| Si le fichier est vide ou si le pipeline d'analyse échoue. | |
| """ | |
| if not file_bytes: | |
| raise gr.Error("Aucun fichier reçu (0 octet). Merci d’uploader un PDF ou une image.") | |
| logger.info( | |
| "ccpu_parser - Analyse CCPU lancée via Gradio | taille_fichier_octets=%d", | |
| len(file_bytes), | |
| ) | |
| try: | |
| result = extract_ccpu_from_pdf(file_bytes) | |
| except Exception as exc: | |
| logger.error( | |
| "ccpu_parser - Erreur lors de l'analyse CCPU via Gradio : %s\n%s", | |
| exc, | |
| traceback.format_exc(), | |
| ) | |
| raise gr.Error(f"Erreur lors de l'analyse du fichier : {exc}") from exc | |
| logger.info( | |
| "ccpu_parser - Analyse CCPU terminée avec succès | type_resultat=%s", | |
| type(result).__name__, | |
| ) | |
| return result | |
| # --------------------------------------------------------------------------- | |
| # Fonction de synchronisation GitHub appelée par Gradio | |
| # --------------------------------------------------------------------------- | |
| def push_space_repo_to_github(commit_message: str | None) -> tuple[dict, str]: | |
| """ | |
| Lance une synchronisation du dépôt courant du Space vers GitHub. | |
| Paramètres | |
| ---------- | |
| commit_message : str | None | |
| Message de commit optionnel saisi dans l'UI. | |
| Si vide, le module github_sync utilise son message par défaut. | |
| Retour | |
| ------ | |
| tuple[dict, str] | |
| - dict : résumé JSON détaillé de la synchronisation | |
| - str : message de statut lisible par l'utilisateur | |
| Comportement | |
| ------------ | |
| - Vérifie que le module `ccpu_parser.github_sync` est disponible. | |
| - Appelle `sync_repo_to_github(...)`. | |
| - Journalise les informations utiles pour le debug console sur HF. | |
| - N'affiche jamais le token GitHub dans les logs ou dans l'UI. | |
| Exceptions | |
| ---------- | |
| gr.Error | |
| Si le module n'est pas disponible ou si la synchronisation échoue. | |
| """ | |
| cleaned_commit_message = (commit_message or "").strip() or None | |
| logger.info( | |
| "ccpu_parser - Demande de sync GitHub reçue via UI | custom_commit_message=%s", | |
| bool(cleaned_commit_message), | |
| ) | |
| if not _GITHUB_SYNC_AVAILABLE or sync_repo_to_github is None: | |
| logger.error( | |
| "ccpu_parser - Sync GitHub impossible : module ccpu_parser.github_sync indisponible." | |
| ) | |
| raise gr.Error( | |
| "Le module de synchronisation GitHub n'est pas disponible dans ce déploiement. " | |
| "Ajoute d'abord `ccpu_parser/github_sync.py` au Space." | |
| ) | |
| try: | |
| summary: dict[str, Any] = sync_repo_to_github( | |
| commit_message=cleaned_commit_message, | |
| ) | |
| except Exception as exc: | |
| logger.error( | |
| "ccpu_parser - Echec sync GitHub via UI : %s\n%s", | |
| exc, | |
| traceback.format_exc(), | |
| ) | |
| raise gr.Error(f"Erreur lors du push GitHub : {exc}") from exc | |
| status_message = ( | |
| f"Synchronisation GitHub OK | repo={summary.get('github_repo')} " | |
| f"| branch={summary.get('branch')} " | |
| f"| commit_created={summary.get('commit_created')} " | |
| f"| pushed={summary.get('pushed')}" | |
| ) | |
| logger.info("ccpu_parser - %s", status_message) | |
| return summary, status_message | |
| # --------------------------------------------------------------------------- | |
| # Construction de l'UI Gradio | |
| # --------------------------------------------------------------------------- | |
| def build_demo() -> gr.Blocks: | |
| """ | |
| Construit l'interface Gradio (Blocks) pour le Space CCPU. | |
| Contenu de l'interface | |
| ---------------------- | |
| 1) Zone principale d'analyse CCPU | |
| - Upload de fichier unique (PDF ou image) | |
| - Bouton de lancement | |
| - Affichage du JSON brut | |
| 2) Zone d'administration GitHub | |
| - Saisie optionnelle d'un message de commit | |
| - Bouton de synchronisation vers GitHub | |
| - Résumé JSON de synchronisation | |
| - Message texte de statut | |
| Retour | |
| ------ | |
| gr.Blocks | |
| Instance Gradio complète prête à être exposée par Hugging Face. | |
| """ | |
| with gr.Blocks() as demo: | |
| gr.Markdown( | |
| """ | |
| # 🧾 Analyse CCPU de certificats matière | |
| Charge un certificat au format **PDF** ou **image** (PNG, JPEG, etc.). | |
| Le backend : | |
| - convertit le document en image (première page pour les PDF), | |
| - envoie l'image au modèle vision, | |
| - récupère un JSON structuré avec notamment : | |
| - `identification` | |
| - `detailsMateriau` | |
| - `analyseChimique` | |
| - `proprietesMecaniques` | |
| - `testsEffectues` | |
| - `conformite` | |
| """ | |
| ) | |
| with gr.Row(): | |
| file_input = gr.File( | |
| label="Certificat matière (PDF ou image)", | |
| file_types=[".pdf", "image"], | |
| type="binary", | |
| show_label=True, | |
| ) | |
| run_btn = gr.Button("Analyser le certificat", variant="primary") | |
| json_output = gr.JSON( | |
| label="Résultat CCPU (JSON)", | |
| show_label=True, | |
| ) | |
| def _wrapped_analyze(file_bytes: bytes): | |
| return analyze_ccpu_bytes(file_bytes) | |
| run_btn.click( | |
| fn=_wrapped_analyze, | |
| inputs=[file_input], | |
| outputs=[json_output], | |
| ) | |
| gr.Markdown("---") | |
| gr.Markdown( | |
| """ | |
| ## ⚙️ Administration / Sync GitHub | |
| Cette section permet de pousser le dépôt courant du Space vers un dépôt GitHub cible. | |
| Secrets attendus côté Hugging Face : | |
| - `GITHUB_TOKEN` | |
| - `GITHUB_REPO` | |
| - `GITHUB_BRANCH` *(optionnel)* | |
| - `GITHUB_COMMITTER_NAME` *(optionnel)* | |
| - `GITHUB_COMMITTER_EMAIL` *(optionnel)* | |
| """ | |
| ) | |
| with gr.Row(): | |
| commit_message_input = gr.Textbox( | |
| label="Message de commit GitHub (optionnel)", | |
| placeholder="Ex. chore(sync): export HF Space before Coolify migration", | |
| lines=2, | |
| ) | |
| with gr.Row(): | |
| sync_btn = gr.Button("Pousser le dépôt vers GitHub", variant="secondary") | |
| sync_status_output = gr.Textbox( | |
| label="Statut synchronisation GitHub", | |
| interactive=False, | |
| ) | |
| sync_json_output = gr.JSON( | |
| label="Résumé sync GitHub", | |
| show_label=True, | |
| ) | |
| def _wrapped_sync(commit_message: str): | |
| return push_space_repo_to_github(commit_message) | |
| sync_btn.click( | |
| fn=_wrapped_sync, | |
| inputs=[commit_message_input], | |
| outputs=[sync_json_output, sync_status_output], | |
| ) | |
| return demo | |
| # --------------------------------------------------------------------------- | |
| # Initialisation pour Hugging Face | |
| # --------------------------------------------------------------------------- | |
| print(">>> [Startup] Import app.py lancé...") | |
| logger.info("ccpu_parser - Import app.py : initialisation de l'UI Gradio CCPU.") | |
| logger.info( | |
| "ccpu_parser - Etat module github_sync au démarrage | available=%s", | |
| _GITHUB_SYNC_AVAILABLE, | |
| ) | |
| demo = build_demo() | |
| print(">>> [Startup] Gradio Blocks créés. Lancement du serveur...") | |
| logger.info("ccpu_parser - UI Gradio construite avec succès.") | |
| # Objet que Hugging Face va lancer | |
| app = demo | |
| if __name__ == "__main__": | |
| logger.info( | |
| "ccpu_parser - Lancement local Gradio | host=0.0.0.0 | port=%s", | |
| os.environ.get("PORT", 7860), | |
| ) | |
| demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860))) |