Spaces:
Sleeping
Sleeping
translate
Browse files
app.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
-
from fastapi import FastAPI, File, UploadFile
|
| 2 |
from fastapi.responses import JSONResponse, RedirectResponse
|
| 3 |
from fastapi.staticfiles import StaticFiles
|
| 4 |
-
from transformers import pipeline
|
| 5 |
import shutil
|
| 6 |
import os
|
| 7 |
import logging
|
|
@@ -9,7 +9,18 @@ from fastapi.middleware.cors import CORSMiddleware
|
|
| 9 |
from PyPDF2 import PdfReader
|
| 10 |
import docx
|
| 11 |
from PIL import Image # Pour ouvrir les images avant analyse
|
| 12 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
# Configuration du logging
|
| 15 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -28,7 +39,7 @@ app.add_middleware(
|
|
| 28 |
UPLOAD_DIR = "uploads"
|
| 29 |
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
| 30 |
|
| 31 |
-
# Charger les modèles avec gestion des erreurs
|
| 32 |
try:
|
| 33 |
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
|
| 34 |
logging.info("✅ Modèle de résumé chargé avec succès !")
|
|
@@ -43,13 +54,7 @@ except Exception as e:
|
|
| 43 |
image_captioning = None
|
| 44 |
logging.error(f"❌ Erreur chargement modèle image : {e}")
|
| 45 |
|
| 46 |
-
|
| 47 |
-
translator = pipeline("translation", model="facebook/m2m100_418M")
|
| 48 |
-
logging.info("✅ Modèle de traduction chargé avec succès !")
|
| 49 |
-
except Exception as e:
|
| 50 |
-
translator = None
|
| 51 |
-
logging.error(f"❌ Erreur chargement modèle traduction : {e}")
|
| 52 |
-
|
| 53 |
|
| 54 |
# ✅ Déclare les routes AVANT le montage des fichiers statiques
|
| 55 |
@app.post("/summarize/")
|
|
@@ -112,31 +117,111 @@ async def interpret_image(file: UploadFile = File(...)):
|
|
| 112 |
except Exception as e:
|
| 113 |
logging.error(f"❌ Erreur interprétation image : {e}")
|
| 114 |
return JSONResponse(content={"error": "Échec de l'analyse de l'image"}, status_code=400)
|
|
|
|
| 115 |
|
| 116 |
-
class TranslationRequest(BaseModel):
|
| 117 |
-
text: str
|
| 118 |
-
source_lang: str
|
| 119 |
-
target_lang: str
|
| 120 |
|
| 121 |
-
@app.post("/translate/")
|
| 122 |
-
async def translate_text(request: TranslationRequest):
|
| 123 |
-
if not request.text.strip():
|
| 124 |
-
return JSONResponse(content={"error": "Texte vide"}, status_code=400)
|
| 125 |
|
| 126 |
-
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
try:
|
| 130 |
-
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
except Exception as e:
|
| 133 |
-
|
| 134 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
-
#
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
# Redirection vers index.html
|
| 140 |
@app.get("/")
|
| 141 |
async def root():
|
| 142 |
-
return RedirectResponse(url="/index.html")
|
|
|
|
| 1 |
+
from fastapi import FastAPI, File, UploadFile, Form
|
| 2 |
from fastapi.responses import JSONResponse, RedirectResponse
|
| 3 |
from fastapi.staticfiles import StaticFiles
|
| 4 |
+
from transformers import pipeline, M2M100ForConditionalGeneration, M2M100Tokenizer
|
| 5 |
import shutil
|
| 6 |
import os
|
| 7 |
import logging
|
|
|
|
| 9 |
from PyPDF2 import PdfReader
|
| 10 |
import docx
|
| 11 |
from PIL import Image # Pour ouvrir les images avant analyse
|
| 12 |
+
from transformers import MarianMTModel, MarianTokenizer
|
| 13 |
+
import os
|
| 14 |
+
import fitz
|
| 15 |
+
from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer
|
| 16 |
+
|
| 17 |
+
import logging
|
| 18 |
+
import openpyxl
|
| 19 |
+
import io
|
| 20 |
+
from docx import Document
|
| 21 |
+
from pptx import Presentation
|
| 22 |
+
from fastapi.responses import JSONResponse
|
| 23 |
+
|
| 24 |
|
| 25 |
# Configuration du logging
|
| 26 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 39 |
UPLOAD_DIR = "uploads"
|
| 40 |
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
| 41 |
|
| 42 |
+
# 🔹 Charger les modèles avec gestion des erreurs
|
| 43 |
try:
|
| 44 |
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
|
| 45 |
logging.info("✅ Modèle de résumé chargé avec succès !")
|
|
|
|
| 54 |
image_captioning = None
|
| 55 |
logging.error(f"❌ Erreur chargement modèle image : {e}")
|
| 56 |
|
| 57 |
+
# 🔹 Chargement du modèle de traduction
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
# ✅ Déclare les routes AVANT le montage des fichiers statiques
|
| 60 |
@app.post("/summarize/")
|
|
|
|
| 117 |
except Exception as e:
|
| 118 |
logging.error(f"❌ Erreur interprétation image : {e}")
|
| 119 |
return JSONResponse(content={"error": "Échec de l'analyse de l'image"}, status_code=400)
|
| 120 |
+
|
| 121 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
|
| 124 |
+
# 🔹 Chargement du modèle de traduction
|
| 125 |
+
try:
|
| 126 |
+
model_name = "facebook/m2m100_418M"
|
| 127 |
+
tokenizer = M2M100Tokenizer.from_pretrained(model_name)
|
| 128 |
+
model = M2M100ForConditionalGeneration.from_pretrained(model_name)
|
| 129 |
+
logging.info("✅ Modèle de traduction chargé avec succès !")
|
| 130 |
+
except Exception as e:
|
| 131 |
+
logging.error(f"❌ Erreur chargement modèle de traduction : {e}")
|
| 132 |
+
model, tokenizer = None, None
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def extract_text_from_pdf(file):
|
| 136 |
+
"""Extrait le texte d'un fichier PDF."""
|
| 137 |
+
doc = fitz.open(stream=file.file.read(), filetype="pdf")
|
| 138 |
+
text = "\n".join([page.get_text() for page in doc])
|
| 139 |
+
return text.strip()
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def extract_text_from_docx(file):
|
| 143 |
+
"""Extrait le texte d'un fichier DOCX."""
|
| 144 |
+
doc = Document(io.BytesIO(file.file.read()))
|
| 145 |
+
text = "\n".join([para.text for para in doc.paragraphs])
|
| 146 |
+
return text.strip()
|
| 147 |
|
| 148 |
+
|
| 149 |
+
def extract_text_from_pptx(file):
|
| 150 |
+
"""Extrait le texte d'un fichier PPTX."""
|
| 151 |
+
prs = Presentation(io.BytesIO(file.file.read()))
|
| 152 |
+
text = []
|
| 153 |
+
for slide in prs.slides:
|
| 154 |
+
for shape in slide.shapes:
|
| 155 |
+
if hasattr(shape, "text"):
|
| 156 |
+
text.append(shape.text)
|
| 157 |
+
return "\n".join(text).strip()
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def extract_text_from_excel(file):
|
| 161 |
+
"""Extrait le texte d'un fichier Excel (XLSX)."""
|
| 162 |
try:
|
| 163 |
+
print("📥 Début extraction texte depuis Excel...")
|
| 164 |
+
wb = openpyxl.load_workbook(io.BytesIO(file.file.read()), data_only=True)
|
| 165 |
+
print("✅ Fichier Excel chargé avec succès !")
|
| 166 |
+
|
| 167 |
+
text = []
|
| 168 |
+
for sheet in wb.worksheets:
|
| 169 |
+
print(f"📄 Feuille trouvée : {sheet.title}")
|
| 170 |
+
for row in sheet.iter_rows(values_only=True):
|
| 171 |
+
text.extend([str(cell) for cell in row if cell])
|
| 172 |
+
|
| 173 |
+
extracted_text = "\n".join(text).strip()
|
| 174 |
+
print(f"✅ Texte extrait (début) : {extracted_text[:100]}...")
|
| 175 |
+
return extracted_text
|
| 176 |
except Exception as e:
|
| 177 |
+
print(f"❌ Erreur lors de l'extraction du fichier Excel : {e}")
|
| 178 |
+
return None
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
@app.post("/translate/")
|
| 183 |
+
async def translate_document(file: UploadFile = File(...), target_lang: str = Form(...)):
|
| 184 |
+
"""API pour traduocire un dument."""
|
| 185 |
+
try:
|
| 186 |
+
logging.info(f"📥 Fichier reçu : {file.filename}")
|
| 187 |
+
logging.info(f"🌍 Langue cible reçue : {target_lang}")
|
| 188 |
+
|
| 189 |
+
if model is None or tokenizer is None:
|
| 190 |
+
return JSONResponse(status_code=500, content={"error": "Modèle de traduction non chargé"})
|
| 191 |
|
| 192 |
+
# Extraction du texte en fonction du type de fichier
|
| 193 |
+
if file.filename.endswith(".pdf"):
|
| 194 |
+
text = extract_text_from_pdf(file)
|
| 195 |
+
elif file.filename.endswith(".docx"):
|
| 196 |
+
text = extract_text_from_docx(file)
|
| 197 |
+
elif file.filename.endswith(".pptx"):
|
| 198 |
+
text = extract_text_from_pptx(file)
|
| 199 |
+
elif file.filename.endswith(".xlsx"):
|
| 200 |
+
text = extract_text_from_excel(file)
|
| 201 |
+
else:
|
| 202 |
+
return JSONResponse(status_code=400, content={"error": "Format non supporté"})
|
| 203 |
+
|
| 204 |
+
logging.info(f"📜 Texte extrait : {text[:50]}...") # Affiche un extrait du texte
|
| 205 |
+
|
| 206 |
+
if not text:
|
| 207 |
+
return JSONResponse(status_code=400, content={"error": "Aucun texte trouvé dans le document"})
|
| 208 |
+
|
| 209 |
+
# Traduire le texte
|
| 210 |
+
tokenizer.src_lang = "fr"
|
| 211 |
+
encoded_text = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
|
| 212 |
+
|
| 213 |
+
generated_tokens = model.generate(**encoded_text, forced_bos_token_id=tokenizer.get_lang_id(target_lang))
|
| 214 |
+
translated_text = tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)[0]
|
| 215 |
+
|
| 216 |
+
logging.info(f"✅ Traduction réussie : {translated_text[:50]}...") # Affiche un extrait de la traduction
|
| 217 |
+
|
| 218 |
+
return {"translated_text": translated_text}
|
| 219 |
+
|
| 220 |
+
except Exception as e:
|
| 221 |
+
logging.error(f"❌ Erreur lors de la traduction : {e}")
|
| 222 |
+
return JSONResponse(status_code=500, content={"error": "Échec de la traduction"})
|
| 223 |
|
| 224 |
# Redirection vers index.html
|
| 225 |
@app.get("/")
|
| 226 |
async def root():
|
| 227 |
+
return RedirectResponse(url="/index.html")
|