Spaces:
Build error
Build error
Download utils.py from imenebenzerga99/IA_space: direct link, hf CLI and curl.
- Browser
- Download file 10.6 kB
-
https://huggingface.co/spaces/imenebenzerga99/IA_space/resolve/main/utils.py
- Command line
-
hf download hf://spaces/imenebenzerga99/IA_space/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/imenebenzerga99/IA_space/resolve/main/utils.py
10.6 kB
| from transformers import pipeline | |
| from PIL import Image | |
| import pytesseract | |
| import docx, fitz, pptx | |
| import pandas as pd | |
| import mimetypes | |
| import logging | |
| from typing import Dict, Optional, Union, List | |
| import torch | |
| import os | |
| # Configuration du logging avec plus de détails | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', | |
| handlers=[ | |
| logging.StreamHandler(), | |
| logging.FileHandler('document_processing.log') | |
| ] | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # Initialisation des modèles | |
| DEVICE = "cuda" if torch.cuda.is_available() else "cpu" | |
| logger.info(f"Utilisation du device: {DEVICE}") | |
| # Modèles pour différentes tâches | |
| summarizer = pipeline("summarization", model="facebook/bart-large-cnn", device=DEVICE) | |
| image_captioner = pipeline("image-to-text", model="nlpconnect/vit-gpt2-image-captioning", device=DEVICE) | |
| # Modèles de traduction pour différentes paires de langues | |
| TRANSLATION_MODELS: Dict[str, Dict[str, str]] = { | |
| "en": { | |
| "fr": "Helsinki-NLP/opus-mt-en-fr", | |
| "es": "Helsinki-NLP/opus-mt-en-es", | |
| "de": "Helsinki-NLP/opus-mt-en-de", | |
| "it": "Helsinki-NLP/opus-mt-en-it", | |
| "pt": "Helsinki-NLP/opus-mt-en-pt", | |
| "ru": "Helsinki-NLP/opus-mt-en-ru", | |
| "zh": "Helsinki-NLP/opus-mt-en-zh", | |
| "ja": "Helsinki-NLP/opus-mt-en-jap", | |
| "ko": "Helsinki-NLP/opus-mt-en-ko" | |
| }, | |
| "fr": { | |
| "en": "Helsinki-NLP/opus-mt-fr-en", | |
| "es": "Helsinki-NLP/opus-mt-fr-es", | |
| "de": "Helsinki-NLP/opus-mt-fr-de", | |
| "it": "Helsinki-NLP/opus-mt-fr-it", | |
| "pt": "Helsinki-NLP/opus-mt-fr-pt", | |
| "ru": "Helsinki-NLP/opus-mt-fr-ru", | |
| "zh": "Helsinki-NLP/opus-mt-fr-zh", | |
| "ja": "Helsinki-NLP/opus-mt-fr-jap", | |
| "ko": "Helsinki-NLP/opus-mt-fr-ko" | |
| } | |
| } | |
| # Cache pour les modèles de traduction | |
| translation_models = {} | |
| def get_translator(source_lang: str, target_lang: str): | |
| """Obtient ou crée un modèle de traduction pour la paire de langues spécifiée.""" | |
| model_key = f"{source_lang}-{target_lang}" | |
| if model_key not in translation_models: | |
| try: | |
| if source_lang in TRANSLATION_MODELS and target_lang in TRANSLATION_MODELS[source_lang]: | |
| model_name = TRANSLATION_MODELS[source_lang][target_lang] | |
| logger.info(f"Chargement du modèle de traduction: {model_name}") | |
| translation_models[model_key] = pipeline("translation", model=model_name) | |
| else: | |
| # Fallback to English if the language pair is not supported | |
| if target_lang in TRANSLATION_MODELS["en"]: | |
| model_name = TRANSLATION_MODELS["en"][target_lang] | |
| logger.info(f"Paire de langues non supportée, utilisation du modèle anglais: {model_name}") | |
| translation_models[model_key] = pipeline("translation", model=model_name) | |
| else: | |
| logger.error(f"Traduction de {source_lang} vers {target_lang} non supportée") | |
| raise ValueError(f"Translation from {source_lang} to {target_lang} is not supported") | |
| except Exception as e: | |
| logger.error(f"Erreur lors du chargement du modèle de traduction: {str(e)}") | |
| raise | |
| return translation_models[model_key] | |
| def process_excel(file_path: str) -> str: | |
| """Extrait le texte d'un fichier Excel.""" | |
| try: | |
| logger.info(f"Lecture du fichier Excel: {file_path}") | |
| df = pd.read_excel(file_path) | |
| text_content = [] | |
| # Traitement des en-têtes | |
| if not df.empty: | |
| headers = df.columns.tolist() | |
| text_content.append(" | ".join(str(h) for h in headers)) | |
| # Traitement des données | |
| for _, row in df.iterrows(): | |
| row_text = " | ".join(str(cell) for cell in row) | |
| text_content.append(row_text) | |
| return "\n".join(text_content) | |
| except Exception as e: | |
| logger.error(f"Erreur lors de la lecture du fichier Excel: {str(e)}") | |
| return "" | |
| def summarize_text(text: str, max_length: int = 150, min_length: int = 40) -> str: | |
| """ | |
| Résume un texte donné. | |
| """ | |
| try: | |
| logger.info(f"Génération du résumé pour un texte de {len(text)} caractères") | |
| if len(text) < min_length: | |
| logger.info("Texte trop court pour être résumé") | |
| return text | |
| # Diviser le texte en chunks si nécessaire | |
| max_chunk = 1024 | |
| chunks = [text[i:i+max_chunk] for i in range(0, len(text), max_chunk)] | |
| summaries = [] | |
| for chunk in chunks: | |
| if len(chunk.strip()) > min_length: | |
| summary = summarizer(chunk, max_length=max_length, min_length=min_length, do_sample=False)[0]['summary_text'] | |
| summaries.append(summary) | |
| final_summary = " ".join(summaries) | |
| logger.info(f"Résumé généré: {len(final_summary)} caractères") | |
| return final_summary | |
| except Exception as e: | |
| logger.error(f"Erreur lors de la génération du résumé: {str(e)}") | |
| return text | |
| def caption_image(image_path: str) -> str: | |
| """ | |
| Génère une description pour une image. | |
| """ | |
| try: | |
| logger.info(f"Génération de la description pour l'image: {image_path}") | |
| image = Image.open(image_path) | |
| # Extraction de texte si présent dans l'image | |
| try: | |
| ocr_text = pytesseract.image_to_string(image) | |
| if ocr_text.strip(): | |
| logger.info("Texte détecté dans l'image") | |
| except Exception as ocr_error: | |
| logger.warning(f"Erreur OCR: {str(ocr_error)}") | |
| ocr_text = "" | |
| # Génération de la description | |
| caption = image_captioner(image)[0]['generated_text'] | |
| # Combiner OCR et description si disponible | |
| if ocr_text.strip(): | |
| result = f"Description: {caption}\nTexte détecté: {ocr_text}" | |
| else: | |
| result = f"Description: {caption}" | |
| logger.info("Description d'image générée avec succès") | |
| return result | |
| except Exception as e: | |
| logger.error(f"Erreur lors de la génération de la description d'image: {str(e)}") | |
| return "Impossible de générer une description pour cette image." | |
| def extract_text_from_file(filepath: str) -> str: | |
| """ | |
| Extrait le texte d'un fichier selon son type. | |
| """ | |
| try: | |
| mime = mimetypes.guess_type(filepath)[0] | |
| extension = os.path.splitext(filepath)[1].lower() | |
| logger.info(f"Extraction du texte depuis {filepath} (type: {mime})") | |
| if extension == '.xlsx' or extension == '.xls': | |
| return process_excel(filepath) | |
| elif mime == "application/pdf": | |
| doc = fitz.open(filepath) | |
| text = " ".join([page.get_text() for page in doc]) | |
| doc.close() | |
| return text | |
| elif mime == "application/vnd.openxmlformats-officedocument.wordprocessingml.document": | |
| doc = docx.Document(filepath) | |
| return "\n".join([para.text for para in doc.paragraphs if para.text.strip()]) | |
| elif mime == "application/vnd.openxmlformats-officedocument.presentationml.presentation": | |
| prs = pptx.Presentation(filepath) | |
| texts = [] | |
| for slide in prs.slides: | |
| slide_texts = [] | |
| for shape in slide.shapes: | |
| if hasattr(shape, "text") and shape.text.strip(): | |
| slide_texts.append(shape.text) | |
| if slide_texts: | |
| texts.append("\n".join(slide_texts)) | |
| return "\n\n".join(texts) | |
| elif mime and mime.startswith("image/"): | |
| return caption_image(filepath) | |
| elif mime and mime.startswith("text/"): | |
| with open(filepath, 'r', encoding='utf-8') as f: | |
| return f.read() | |
| else: | |
| logger.warning(f"Type de fichier non supporté: {mime}") | |
| return "" | |
| except Exception as e: | |
| logger.error(f"Erreur lors de l'extraction du texte: {str(e)}") | |
| return "" | |
| def translate_text(text: str, target_lang: str, source_lang: str = "fr") -> str: | |
| """ | |
| Traduit le texte de la langue source vers la langue cible. | |
| """ | |
| if not text.strip(): | |
| logger.warning("Texte vide reçu pour la traduction") | |
| return text | |
| try: | |
| logger.info(f"Début de la traduction: {len(text)} caractères") | |
| logger.info(f"Source: {source_lang}, Cible: {target_lang}") | |
| # Vérification des langues supportées | |
| if source_lang not in TRANSLATION_MODELS: | |
| logger.error(f"Langue source non supportée: {source_lang}") | |
| raise ValueError(f"Langue source non supportée: {source_lang}") | |
| if target_lang not in TRANSLATION_MODELS[source_lang]: | |
| logger.error(f"Langue cible non supportée: {target_lang}") | |
| raise ValueError(f"Langue cible non supportée: {target_lang}") | |
| translator = get_translator(source_lang, target_lang) | |
| # Diviser le texte en plus petits morceaux | |
| max_chunk_size = 400 # Réduit pour éviter les problèmes de mémoire | |
| chunks = [text[i:i+max_chunk_size] for i in range(0, len(text), max_chunk_size)] | |
| logger.info(f"Texte divisé en {len(chunks)} morceaux pour la traduction") | |
| translated_chunks = [] | |
| for i, chunk in enumerate(chunks, 1): | |
| try: | |
| logger.info(f"Traduction du morceau {i}/{len(chunks)} ({len(chunk)} caractères)") | |
| result = translator(chunk, max_length=512)[0]['translation_text'] | |
| translated_chunks.append(result) | |
| logger.info(f"Morceau {i} traduit avec succès") | |
| except Exception as chunk_error: | |
| logger.error(f"Erreur lors de la traduction du morceau {i}: {str(chunk_error)}") | |
| translated_chunks.append(chunk) # Garde le texte original en cas d'erreur | |
| translated_text = " ".join(translated_chunks) | |
| logger.info(f"Traduction terminée: {len(translated_text)} caractères générés") | |
| return translated_text | |
| except Exception as e: | |
| logger.error(f"Erreur critique lors de la traduction: {str(e)}", exc_info=True) | |
| return text # Retourne le texte original en cas d'erreur | |