Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -14,9 +14,9 @@ import logging
|
|
14 |
from PyPDF2 import PdfReader
|
15 |
import docx
|
16 |
from PIL import Image
|
17 |
-
import openpyxl
|
18 |
from pptx import Presentation
|
19 |
-
import fitz
|
20 |
import io
|
21 |
from docx import Document
|
22 |
import matplotlib.pyplot as plt
|
@@ -149,7 +149,6 @@ async def translate_document(file: UploadFile = File(...), target_lang: str = Fo
|
|
149 |
if not text:
|
150 |
return JSONResponse(status_code=400, content={"error": "Aucun texte trouvé dans le document"})
|
151 |
|
152 |
-
# Vérifier si la langue cible est supportée
|
153 |
target_lang_id = tokenizer.get_lang_id(target_lang)
|
154 |
|
155 |
if target_lang_id is None:
|
@@ -158,7 +157,6 @@ async def translate_document(file: UploadFile = File(...), target_lang: str = Fo
|
|
158 |
content={"error": f"Langue cible '{target_lang}' non supportée. Langues disponibles : {list(tokenizer.lang_code_to_id.keys())}"}
|
159 |
)
|
160 |
|
161 |
-
# Traduction
|
162 |
tokenizer.src_lang = "fr"
|
163 |
encoded_text = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
|
164 |
|
@@ -176,12 +174,6 @@ async def translate_document(file: UploadFile = File(...), target_lang: str = Fo
|
|
176 |
return JSONResponse(status_code=500, content={"error": "Échec de la traduction"})
|
177 |
|
178 |
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
# Charger le modèle pour la génération de code
|
185 |
codegen_model_name = "Salesforce/codegen-350M-mono"
|
186 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
187 |
|
@@ -208,7 +200,6 @@ async def generate_viz(file: UploadFile = File(...), query: str = Form(...)):
|
|
208 |
x_col = numeric_cols[0]
|
209 |
y_col = numeric_cols[1] if query != "histplot" and len(numeric_cols) > 1 else None
|
210 |
|
211 |
-
# ➔ CONSTRUCTION du prompt avec encadrement ```python
|
212 |
prompt = f"""
|
213 |
### Génère uniquement du code Python fonctionnel pour tracer un {query} avec Matplotlib et Seaborn
|
214 |
```python
|
@@ -267,10 +258,6 @@ plt.close()
|
|
267 |
print(f"🔴 Erreur serveur : {e}")
|
268 |
return JSONResponse(content={"error": f"Erreur lors de la génération du graphique : {str(e)}"}, status_code=500)
|
269 |
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
# Charger le modèle de résumé
|
274 |
summarizer = None
|
275 |
try:
|
276 |
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
|
@@ -285,20 +272,19 @@ except Exception as e:
|
|
285 |
image_captioning = None
|
286 |
logging.error(f"❌ Erreur chargement modèle image : {e}")
|
287 |
|
288 |
-
|
289 |
def extract_text_from_docx(docx_file):
|
290 |
doc = Document(BytesIO(docx_file))
|
291 |
text = "\n".join([para.text for para in doc.paragraphs])
|
292 |
return text
|
293 |
|
294 |
-
|
295 |
def extract_text_from_excel(xlsx_file):
|
296 |
-
|
297 |
df = pd.read_excel(BytesIO(xlsx_file))
|
298 |
text = df.to_string(index=False)
|
299 |
return text
|
300 |
|
301 |
-
# Fonction pour extraire le texte d'un fichier PowerPoint
|
302 |
def extract_text_from_pptx(pptx_file):
|
303 |
presentation = Presentation(BytesIO(pptx_file))
|
304 |
text = ""
|
@@ -308,17 +294,16 @@ def extract_text_from_pptx(pptx_file):
|
|
308 |
text += shape.text + "\n"
|
309 |
return text
|
310 |
|
311 |
-
|
312 |
@app.post("/summarize/")
|
313 |
async def summarize(file: UploadFile = File(...)):
|
314 |
-
|
315 |
if summarizer is None:
|
316 |
return {"message": "Le modèle est en cours de chargement, veuillez patienter..."}
|
317 |
-
|
318 |
-
# Extraire le contenu du fichier téléchargé
|
319 |
contents = await file.read()
|
320 |
|
321 |
-
|
322 |
if file.filename.endswith(".pdf"):
|
323 |
text = extract_text(BytesIO(contents))
|
324 |
elif file.filename.endswith(".docx"):
|
@@ -330,17 +315,15 @@ async def summarize(file: UploadFile = File(...)):
|
|
330 |
else:
|
331 |
return {"summary": "Résumé non disponible pour ce format de fichier."}
|
332 |
|
333 |
-
# Si un modèle de résumé est chargé, effectuer le résumé
|
334 |
try:
|
335 |
if summarizer:
|
336 |
-
summary = summarizer(text[:1024])
|
337 |
summary_text = summary[0]['summary_text']
|
338 |
else:
|
339 |
summary_text = "❌ Modèle de résumé non disponible."
|
340 |
except Exception as e:
|
341 |
summary_text = f"❌ Erreur lors de la génération du résumé : {e}"
|
342 |
|
343 |
-
# Retourner le résumé généré
|
344 |
return {"summary": summary_text}
|
345 |
|
346 |
|
@@ -425,8 +408,6 @@ async def image_qa(file: UploadFile = File(...), question: str = Form(...)):
|
|
425 |
return JSONResponse(content={"error": str(e)}, status_code=500)
|
426 |
|
427 |
|
428 |
-
|
429 |
-
# Servir les fichiers statiques (HTML, CSS, JS)
|
430 |
app.mount("/static", StaticFiles(directory="static", html=True), name="static")
|
431 |
|
432 |
|
|
|
14 |
from PyPDF2 import PdfReader
|
15 |
import docx
|
16 |
from PIL import Image
|
17 |
+
import openpyxl
|
18 |
from pptx import Presentation
|
19 |
+
import fitz
|
20 |
import io
|
21 |
from docx import Document
|
22 |
import matplotlib.pyplot as plt
|
|
|
149 |
if not text:
|
150 |
return JSONResponse(status_code=400, content={"error": "Aucun texte trouvé dans le document"})
|
151 |
|
|
|
152 |
target_lang_id = tokenizer.get_lang_id(target_lang)
|
153 |
|
154 |
if target_lang_id is None:
|
|
|
157 |
content={"error": f"Langue cible '{target_lang}' non supportée. Langues disponibles : {list(tokenizer.lang_code_to_id.keys())}"}
|
158 |
)
|
159 |
|
|
|
160 |
tokenizer.src_lang = "fr"
|
161 |
encoded_text = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
|
162 |
|
|
|
174 |
return JSONResponse(status_code=500, content={"error": "Échec de la traduction"})
|
175 |
|
176 |
|
|
|
|
|
|
|
|
|
|
|
|
|
177 |
codegen_model_name = "Salesforce/codegen-350M-mono"
|
178 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
179 |
|
|
|
200 |
x_col = numeric_cols[0]
|
201 |
y_col = numeric_cols[1] if query != "histplot" and len(numeric_cols) > 1 else None
|
202 |
|
|
|
203 |
prompt = f"""
|
204 |
### Génère uniquement du code Python fonctionnel pour tracer un {query} avec Matplotlib et Seaborn
|
205 |
```python
|
|
|
258 |
print(f"🔴 Erreur serveur : {e}")
|
259 |
return JSONResponse(content={"error": f"Erreur lors de la génération du graphique : {str(e)}"}, status_code=500)
|
260 |
|
|
|
|
|
|
|
|
|
261 |
summarizer = None
|
262 |
try:
|
263 |
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
|
|
|
272 |
image_captioning = None
|
273 |
logging.error(f"❌ Erreur chargement modèle image : {e}")
|
274 |
|
275 |
+
|
276 |
def extract_text_from_docx(docx_file):
|
277 |
doc = Document(BytesIO(docx_file))
|
278 |
text = "\n".join([para.text for para in doc.paragraphs])
|
279 |
return text
|
280 |
|
281 |
+
|
282 |
def extract_text_from_excel(xlsx_file):
|
283 |
+
|
284 |
df = pd.read_excel(BytesIO(xlsx_file))
|
285 |
text = df.to_string(index=False)
|
286 |
return text
|
287 |
|
|
|
288 |
def extract_text_from_pptx(pptx_file):
|
289 |
presentation = Presentation(BytesIO(pptx_file))
|
290 |
text = ""
|
|
|
294 |
text += shape.text + "\n"
|
295 |
return text
|
296 |
|
297 |
+
|
298 |
@app.post("/summarize/")
|
299 |
async def summarize(file: UploadFile = File(...)):
|
300 |
+
|
301 |
if summarizer is None:
|
302 |
return {"message": "Le modèle est en cours de chargement, veuillez patienter..."}
|
303 |
+
|
|
|
304 |
contents = await file.read()
|
305 |
|
306 |
+
|
307 |
if file.filename.endswith(".pdf"):
|
308 |
text = extract_text(BytesIO(contents))
|
309 |
elif file.filename.endswith(".docx"):
|
|
|
315 |
else:
|
316 |
return {"summary": "Résumé non disponible pour ce format de fichier."}
|
317 |
|
|
|
318 |
try:
|
319 |
if summarizer:
|
320 |
+
summary = summarizer(text[:1024])
|
321 |
summary_text = summary[0]['summary_text']
|
322 |
else:
|
323 |
summary_text = "❌ Modèle de résumé non disponible."
|
324 |
except Exception as e:
|
325 |
summary_text = f"❌ Erreur lors de la génération du résumé : {e}"
|
326 |
|
|
|
327 |
return {"summary": summary_text}
|
328 |
|
329 |
|
|
|
408 |
return JSONResponse(content={"error": str(e)}, status_code=500)
|
409 |
|
410 |
|
|
|
|
|
411 |
app.mount("/static", StaticFiles(directory="static", html=True), name="static")
|
412 |
|
413 |
|