File size: 10,648 Bytes
300a0b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
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