Update app.py
Browse files
app.py
CHANGED
@@ -1,52 +1,25 @@
|
|
1 |
-
from fastapi import FastAPI,
|
2 |
from transformers import pipeline
|
3 |
-
import PyPDF2
|
4 |
-
import docx
|
5 |
-
import os
|
6 |
-
import uvicorn
|
7 |
-
from io import BytesIO
|
8 |
|
9 |
-
|
|
|
10 |
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
def extract_text_from_pdf(file: BytesIO) -> str:
|
15 |
-
"""Extrait le texte d'un fichier PDF."""
|
16 |
-
reader = PyPDF2.PdfReader(file)
|
17 |
-
text = "\n".join([page.extract_text() for page in reader.pages if page.extract_text()])
|
18 |
-
return text
|
19 |
-
|
20 |
-
def extract_text_from_docx(file: BytesIO) -> str:
|
21 |
-
"""Extrait le texte d'un fichier DOCX."""
|
22 |
-
doc = docx.Document(file)
|
23 |
-
text = "\n".join([para.text for para in doc.paragraphs])
|
24 |
-
return text
|
25 |
|
26 |
@app.post("/translate/")
|
27 |
-
|
28 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
29 |
try:
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
if file_extension == "pdf":
|
35 |
-
text = extract_text_from_pdf(file_io)
|
36 |
-
elif file_extension == "docx":
|
37 |
-
text = extract_text_from_docx(file_io)
|
38 |
-
else:
|
39 |
-
return {"error": "Format non supporté. Utilisez PDF ou DOCX."}
|
40 |
-
|
41 |
-
# Traduire le texte
|
42 |
-
translation = translator(text, max_length=1000)
|
43 |
-
translated_text = " ".join([t["translation_text"] for t in translation])
|
44 |
-
|
45 |
-
return {"original_text": text[:500], "translated_text": translated_text[:500]} # Limite pour affichage
|
46 |
except Exception as e:
|
47 |
-
|
48 |
-
|
49 |
-
if __name__ == "__main__":
|
50 |
-
port = int(os.environ.get("PORT", 7860))
|
51 |
-
uvicorn.run(app, host="0.0.0.0", port=port)
|
52 |
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException
|
2 |
from transformers import pipeline
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
+
# Création de l'application FastAPI
|
5 |
+
app = FastAPI(title="Traduction Anglais → Français")
|
6 |
|
7 |
+
@app.get("/")
|
8 |
+
def home():
|
9 |
+
return {"message": "Bienvenue sur l'API de traduction !"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
@app.post("/translate/")
|
12 |
+
def translate(text: str):
|
13 |
+
"""
|
14 |
+
Traduit un texte de l'anglais vers le français.
|
15 |
+
"""
|
16 |
+
if not text:
|
17 |
+
raise HTTPException(status_code=400, detail="Le texte est vide.")
|
18 |
+
|
19 |
try:
|
20 |
+
translator = pipeline("translation", model="facebook/wmt19-en-fr")
|
21 |
+
translated_text = translator(text)[0]['translation_text']
|
22 |
+
return {"original": text, "translated": translated_text}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
except Exception as e:
|
24 |
+
raise HTTPException(status_code=500, detail=f"Erreur de traduction : {e}")
|
|
|
|
|
|
|
|
|
25 |
|