malaknihed commited on
Commit
89e09ba
·
verified ·
1 Parent(s): 48a7895
Files changed (1) hide show
  1. app.py +20 -4
app.py CHANGED
@@ -102,20 +102,36 @@ async def interpret_image(file: UploadFile = File(...)):
102
  @app.post("/translate/")
103
  async def translate_document(file: UploadFile = File(...), target_lang: str = "fr"):
104
  logging.info(f"📂 Requête reçue - Traduction : {file.filename}")
 
 
 
 
 
105
  try:
 
106
  if file.filename.endswith(".pdf"):
107
- text = "\n".join([page.get_text() for page in fitz.open(stream=file.file.read(), filetype="pdf")])
 
 
108
  elif file.filename.endswith(".docx"):
109
- doc = docx.Document(file.file)
110
  text = "\n".join([para.text for para in doc.paragraphs])
 
111
  else:
112
  return JSONResponse(status_code=400, content={"error": "Format non supporté"})
113
-
114
- translated_text = translator(text, src_lang="en", tgt_lang=target_lang)
 
 
 
 
115
  return {"translated_text": translated_text[0]["translation_text"]}
 
116
  except Exception as e:
 
117
  return JSONResponse(status_code=500, content={"error": str(e)})
118
 
 
119
  app.mount("/", StaticFiles(directory="static", html=True), name="static")
120
 
121
  @app.get("/")
 
102
  @app.post("/translate/")
103
  async def translate_document(file: UploadFile = File(...), target_lang: str = "fr"):
104
  logging.info(f"📂 Requête reçue - Traduction : {file.filename}")
105
+
106
+ file_path = os.path.join(UPLOAD_DIR, file.filename)
107
+ with open(file_path, "wb") as buffer:
108
+ shutil.copyfileobj(file.file, buffer)
109
+
110
  try:
111
+ text = ""
112
  if file.filename.endswith(".pdf"):
113
+ doc = fitz.open(file_path) # Correction ici
114
+ text = "\n".join([page.get_text("text") for page in doc]) # Extraction correcte
115
+
116
  elif file.filename.endswith(".docx"):
117
+ doc = docx.Document(file_path) # Correction ici
118
  text = "\n".join([para.text for para in doc.paragraphs])
119
+
120
  else:
121
  return JSONResponse(status_code=400, content={"error": "Format non supporté"})
122
+
123
+ if not text.strip():
124
+ return JSONResponse(status_code=400, content={"error": "Le document est vide ou non lisible"})
125
+
126
+ translated_text = translator(text, src_lang="en", target_lang=target_lang) # Correction ici
127
+
128
  return {"translated_text": translated_text[0]["translation_text"]}
129
+
130
  except Exception as e:
131
+ logging.error(f"❌ Erreur lors de la traduction : {e}")
132
  return JSONResponse(status_code=500, content={"error": str(e)})
133
 
134
+
135
  app.mount("/", StaticFiles(directory="static", html=True), name="static")
136
 
137
  @app.get("/")