Spaces:
Sleeping
Sleeping
Download ccpu_parser/llm_client.py from chouchouvs/ccpu: direct link, hf CLI and curl.
- Browser
- Download file 4.94 kB
-
https://huggingface.co/spaces/chouchouvs/ccpu/resolve/main/ccpu_parser/llm_client.py
- Command line
-
hf download hf://spaces/chouchouvs/ccpu/ccpu_parser/llm_client.py
-
curl -L -o llm_client.py https://huggingface.co/spaces/chouchouvs/ccpu/resolve/main/ccpu_parser/llm_client.py
4.94 kB
| """ | |
| ccpu_parser.llm_client | |
| ---------------------- | |
| Responsabilité : | |
| - Appeler le modèle multimodal hébergé sur DeepInfra via l'API OpenAI-compatible. | |
| - Envoyer une image encodée en base64 + un prompt texte. | |
| - Activer le JSON mode pour obtenir en sortie un JSON valide. | |
| Fonctions fournies : | |
| - call_vision_llm_to_json(image_jpeg: bytes, prompt: str) -> str | |
| Envoie l'image + le prompt, renvoie le texte brut de la complétion (censé être un JSON). | |
| """ | |
| from __future__ import annotations | |
| import base64 | |
| import os | |
| from typing import Any, Dict | |
| import requests | |
| from .utils import logger | |
| DEEPINFRA_API_URL = "https://api.deepinfra.com/v1/openai/chat/completions" | |
| DEFAULT_MODEL_ID = "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8" | |
| class LLMClientError(RuntimeError): | |
| """Erreur générique lors de l'appel au LLM DeepInfra.""" | |
| def _get_deepinfra_token() -> str: | |
| """ | |
| Récupère le token DeepInfra depuis les variables d'environnement. | |
| Utilise d'abord CCPU_LLM_API_KEY si présent, sinon DEEPINFRA_API_KEY. | |
| """ | |
| token = os.getenv("CCPU_LLM_API_KEY") or os.getenv("DEEPINFRA_API_KEY") | |
| if not token: | |
| raise LLMClientError( | |
| "Aucune clé API DeepInfra trouvée. " | |
| "Définis CCPU_LLM_API_KEY ou DEEPINFRA_API_KEY dans les secrets Hugging Face." | |
| ) | |
| return token | |
| def call_vision_llm_to_json(image_jpeg: bytes, prompt: str) -> str: | |
| """ | |
| Appelle le modèle vision DeepInfra (Llama-4 Maverick) avec : | |
| - une image JPEG encodée en base64, | |
| - un prompt texte détaillant le schéma JSON attendu. | |
| Renvoie : | |
| - Le texte brut de la complétion (normalement un JSON valide grâce au JSON mode). | |
| Exceptions : | |
| - LLMClientError en cas d'erreur HTTP ou de format de réponse inattendu. | |
| """ | |
| if not image_jpeg: | |
| raise ValueError("call_vision_llm_to_json: image_jpeg vide") | |
| token = _get_deepinfra_token() | |
| model_id = os.getenv("CCPU_LLM_MODEL_ID", DEFAULT_MODEL_ID) | |
| b64_image = base64.b64encode(image_jpeg).decode("ascii") | |
| payload: Dict[str, Any] = { | |
| "model": model_id, | |
| "messages": [ | |
| { | |
| "role": "user", | |
| "content": [ | |
| { | |
| "type": "image_url", | |
| "image_url": { | |
| "url": f"data:image/jpeg;base64,{b64_image}" | |
| }, | |
| }, | |
| { | |
| "type": "text", | |
| "text": prompt, | |
| }, | |
| ], | |
| } | |
| ], | |
| # On laisse un peu de marge mais ce JSON est compact. | |
| "max_tokens": 2048, | |
| "temperature": 0.1, | |
| # JSON mode DeepInfra (OpenAI-compatible). | |
| "response_format": {"type": "json_object"}, | |
| } | |
| headers = { | |
| "Authorization": f"Bearer {token}", | |
| "Content-Type": "application/json", | |
| } | |
| logger.info( | |
| "llm_client: appel vision DeepInfra model=%s (image=%d octets, prompt_len=%d)", | |
| model_id, | |
| len(image_jpeg), | |
| len(prompt), | |
| ) | |
| try: | |
| resp = requests.post( | |
| DEEPINFRA_API_URL, | |
| headers=headers, | |
| json=payload, | |
| timeout=120, | |
| ) | |
| except Exception as exc: # pragma: no cover | |
| logger.error("llm_client: requête HTTP vers DeepInfra échouée : %s", exc) | |
| raise LLMClientError(f"Erreur réseau vers DeepInfra: {exc}") from exc | |
| if resp.status_code >= 400: | |
| logger.error( | |
| "llm_client: DeepInfra HTTP %d – payload d'erreur: %s", | |
| resp.status_code, | |
| resp.text[:1000], | |
| ) | |
| raise LLMClientError(f"DeepInfra renvoie une erreur HTTP {resp.status_code}") | |
| data = resp.json() | |
| try: | |
| choice = data["choices"][0] | |
| message = choice["message"] | |
| content = message["content"] | |
| except Exception as exc: # pragma: no cover | |
| logger.error("llm_client: format de réponse inattendu: %s", data) | |
| raise LLMClientError(f"Format de réponse DeepInfra inattendu: {exc}") from exc | |
| # Selon l'API, content peut être une chaîne ou une liste de blocs. | |
| if isinstance(content, str): | |
| text = content | |
| elif isinstance(content, list): | |
| # Concatène tous les segments texte éventuels | |
| text_parts = [] | |
| for part in content: | |
| if isinstance(part, dict) and part.get("type") == "text": | |
| text_parts.append(part.get("text", "")) | |
| text = "".join(text_parts) | |
| else: | |
| raise LLMClientError( | |
| f"llm_client: type de content inattendu ({type(content)!r}) dans la réponse" | |
| ) | |
| logger.info( | |
| "llm_client: réponse DeepInfra reçue (len=%d caractères)", len(text) | |
| ) | |
| logger.debug("llm_client: extrait de la réponse (1k chars max): %s", text[:1000]) | |
| return text | |