Spaces:
No application file
No application file
Download main2.py from imenebenzerga99/web: direct link, hf CLI and curl.
- Browser
- Download file 13.4 kB
-
https://huggingface.co/spaces/imenebenzerga99/web/resolve/main/main2.py
- Command line
-
hf download hf://spaces/imenebenzerga99/web/main2.py
-
curl -L -o main2.py https://huggingface.co/spaces/imenebenzerga99/web/resolve/main/main2.py
13.4 kB
| from fastapi import FastAPI, File, UploadFile, Form, Request, HTTPException | |
| from fastapi.responses import HTMLResponse, FileResponse, JSONResponse | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.templating import Jinja2Templates | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from app.utils import summarize_text, caption_image, translate_text, extract_text_from_file | |
| import docx | |
| from docx import Document | |
| from pptx import Presentation | |
| import fitz | |
| import io | |
| import shutil | |
| import sys | |
| import os | |
| import logging | |
| from typing import Optional, Dict, Any | |
| from datetime import datetime | |
| # Configuration du logging | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', | |
| handlers=[ | |
| logging.FileHandler('app.log'), | |
| logging.StreamHandler() | |
| ] | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # Configuration de l'application | |
| app = FastAPI(title="Document Processing API", version="1.0.0") | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # Configuration des dossiers statiques et templates | |
| app.mount("/static", StaticFiles(directory="static"), name="static") | |
| templates = Jinja2Templates(directory="app/templates") | |
| # Configuration des chemins | |
| UPLOAD_DIR = "uploads" | |
| os.makedirs(UPLOAD_DIR, exist_ok=True) | |
| # Types de fichiers supportés | |
| SUPPORTED_DOCUMENTS = { | |
| 'documents': ['.docx', '.pptx', '.pdf', '.txt', '.xlsx', '.xls'], | |
| 'images': ['.png', '.jpg', '.jpeg', '.gif', '.bmp'] | |
| } | |
| async def home(request: Request): | |
| """Page d'accueil de l'application""" | |
| return templates.TemplateResponse("r.html", {"request": request}) | |
| async def process_file( | |
| file: UploadFile = File(...), | |
| operation: str = Form(...), | |
| target_lang: Optional[str] = Form(None) | |
| ) -> Dict[str, Any]: | |
| """ | |
| Traite un fichier selon l'opération demandée (résumé, traduction, analyse d'image) | |
| """ | |
| filepath = None | |
| try: | |
| # Vérification du type de fichier | |
| extension = os.path.splitext(file.filename)[1].lower() | |
| if extension not in SUPPORTED_DOCUMENTS['documents'] + SUPPORTED_DOCUMENTS['images']: | |
| raise HTTPException( | |
| status_code=400, | |
| detail=f"Type de fichier non supporté. Extensions supportées: {', '.join(SUPPORTED_DOCUMENTS['documents'] + SUPPORTED_DOCUMENTS['images'])}" | |
| ) | |
| # Sauvegarde du fichier | |
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") | |
| filename = f"{timestamp}_{file.filename}" | |
| filepath = os.path.join(UPLOAD_DIR, filename) | |
| with open(filepath, "wb") as buffer: | |
| shutil.copyfileobj(file.file, buffer) | |
| logger.info(f"Fichier sauvegardé: {filepath}") | |
| # Traitement selon l'opération | |
| if operation == "summarize": | |
| if extension not in SUPPORTED_DOCUMENTS['documents']: | |
| raise HTTPException(status_code=400, detail="Le résumé n'est disponible que pour les documents") | |
| text = extract_text_from_file(filepath) | |
| if not text.strip(): | |
| return {"result": "Aucun texte n'a pu être extrait du document."} | |
| summary = summarize_text(text) | |
| return {"result": summary, "operation": "summarize"} | |
| elif operation == "translate": | |
| if not target_lang: | |
| raise HTTPException(status_code=400, detail="La langue cible est requise pour la traduction") | |
| if extension in ['.docx', '.pptx', '.pdf']: | |
| translated_content = await translate_document(filepath, target_lang, extension) | |
| translated_filename = f"translated_{filename}" | |
| translated_filepath = os.path.join(UPLOAD_DIR, translated_filename) | |
| with open(translated_filepath, "wb") as f: | |
| f.write(translated_content) | |
| return FileResponse( | |
| path=translated_filepath, | |
| filename=translated_filename, | |
| media_type=get_media_type(extension) | |
| ) | |
| else: | |
| text = extract_text_from_file(filepath) | |
| translated = translate_text(text, target_lang) | |
| return {"result": translated, "operation": "translate"} | |
| elif operation == "analyze_image": | |
| if extension not in SUPPORTED_DOCUMENTS['images']: | |
| raise HTTPException(status_code=400, detail="L'analyse d'image n'est disponible que pour les fichiers image") | |
| caption = caption_image(filepath) | |
| return {"result": caption, "operation": "analyze_image"} | |
| else: | |
| raise HTTPException(status_code=400, detail="Opération non supportée") | |
| except Exception as e: | |
| logger.error(f"Erreur lors du traitement: {str(e)}") | |
| raise HTTPException(status_code=500, detail=f"Une erreur est survenue: {str(e)}") | |
| finally: | |
| # Nettoyage des fichiers temporaires | |
| if filepath and os.path.exists(filepath): | |
| try: | |
| os.remove(filepath) | |
| logger.info(f"Fichier temporaire supprimé: {filepath}") | |
| except Exception as e: | |
| logger.warning(f"Erreur lors de la suppression du fichier temporaire: {str(e)}") | |
| async def translate_document(file_path: str, target_lang: str, extension: str) -> bytes: | |
| """Traduit un document selon son type""" | |
| try: | |
| if extension == '.docx': | |
| return await translate_docx(file_path, target_lang) | |
| elif extension == '.pptx': | |
| return await translate_pptx(file_path, target_lang) | |
| elif extension == '.pdf': | |
| return await translate_pdf(file_path, target_lang) | |
| else: | |
| raise HTTPException(status_code=400, detail="Type de document non supporté pour la traduction") | |
| except Exception as e: | |
| logger.error(f"Erreur lors de la traduction du document: {str(e)}") | |
| raise HTTPException(status_code=500, detail=f"Erreur lors de la traduction: {str(e)}") | |
| def get_media_type(extension: str) -> str: | |
| """Retourne le type MIME approprié pour l'extension de fichier""" | |
| media_types = { | |
| '.docx': "application/vnd.openxmlformats-officedocument.wordprocessingml.document", | |
| '.pptx': "application/vnd.openxmlformats-officedocument.presentationml.presentation", | |
| '.pdf': "application/pdf", | |
| '.txt': "text/plain", | |
| '.xlsx': "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", | |
| '.xls': "application/vnd.ms-excel" | |
| } | |
| return media_types.get(extension, "application/octet-stream") | |
| async def translate_pptx(file_path: str, target_lang: str) -> bytes: | |
| try: | |
| logger.info(f"Traduction du fichier PPTX: {file_path}") | |
| prs = Presentation(file_path) | |
| for i, slide in enumerate(prs.slides): | |
| for j, shape in enumerate(slide.shapes): | |
| if hasattr(shape, "text") and shape.text.strip(): | |
| logger.info(f"Traduction de la forme {j+1} de la diapositive {i+1}") | |
| translated_text = translate_text(shape.text, target_lang) | |
| shape.text = translated_text | |
| output = io.BytesIO() | |
| prs.save(output) | |
| output.seek(0) | |
| logger.info("Traduction PPTX terminée avec succès") | |
| return output.getvalue() | |
| except Exception as e: | |
| logger.error(f"Erreur lors de la traduction du fichier PPTX: {str(e)}") | |
| raise HTTPException(status_code=500, detail=f"Erreur lors de la traduction du fichier PPTX: {str(e)}") | |
| async def translate_pdf(file_path: str, target_lang: str) -> bytes: | |
| try: | |
| logger.info(f"Traduction du fichier PDF: {file_path}") | |
| doc = fitz.open(file_path) | |
| output = fitz.open() | |
| for i, page_num in enumerate(range(len(doc))): | |
| page = doc[page_num] | |
| text = page.get_text() | |
| if text.strip(): | |
| logger.info(f"Traduction de la page {i+1}") | |
| translated_text = translate_text(text, target_lang) | |
| # Créer une nouvelle page avec le texte traduit | |
| new_page = output.new_page(width=page.rect.width, height=page.rect.height) | |
| new_page.insert_text((50, 50), translated_text) | |
| # Sauvegarder dans un buffer en mémoire | |
| output_buffer = io.BytesIO() | |
| output.save(output_buffer) | |
| output_buffer.seek(0) | |
| # Fermer les documents | |
| doc.close() | |
| output.close() | |
| logger.info("Traduction PDF terminée avec succès") | |
| return output_buffer.getvalue() | |
| except Exception as e: | |
| logger.error(f"Erreur lors de la traduction du fichier PDF: {str(e)}") | |
| raise HTTPException(status_code=500, detail=f"Erreur lors de la traduction du fichier PDF: {str(e)}") | |
| async def translate_file( | |
| file: UploadFile = File(...), | |
| target_lang: str = Form(...) | |
| ): | |
| filepath = None | |
| translated_filepath = None | |
| try: | |
| logger.info(f"Début du traitement de la traduction pour le fichier: {file.filename}") | |
| # Vérification de l'extension du fichier | |
| file_extension = os.path.splitext(file.filename)[1].lower() | |
| supported_extensions = ['.docx', '.pptx', '.pdf', '.txt'] | |
| if file_extension not in supported_extensions: | |
| logger.error(f"Extension de fichier non supportée: {file_extension}") | |
| raise HTTPException( | |
| status_code=400, | |
| detail=f"Type de fichier non supporté. Extensions supportées: {', '.join(supported_extensions)}" | |
| ) | |
| # Création du répertoire de téléchargement si nécessaire | |
| if not os.path.exists(UPLOAD_DIR): | |
| os.makedirs(UPLOAD_DIR) | |
| logger.info(f"Création du répertoire de téléchargement: {UPLOAD_DIR}") | |
| # Sauvegarde du fichier | |
| filepath = os.path.join(UPLOAD_DIR, file.filename) | |
| with open(filepath, "wb") as buffer: | |
| shutil.copyfileobj(file.file, buffer) | |
| logger.info(f"Fichier sauvegardé avec succès: {filepath}") | |
| # Traduction selon le type de fichier | |
| if file_extension == '.docx': | |
| translated_content = await translate_pptx(filepath, target_lang) | |
| content_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" | |
| elif file_extension == '.pptx': | |
| translated_content = await translate_pptx(filepath, target_lang) | |
| content_type = "application/vnd.openxmlformats-officedocument.presentationml.presentation" | |
| elif file_extension == '.pdf': | |
| translated_content = await translate_pdf(filepath, target_lang) | |
| content_type = "application/pdf" | |
| else: | |
| # Pour les fichiers texte | |
| logger.info("Traitement d'un fichier texte") | |
| with open(filepath, 'r', encoding='utf-8') as f: | |
| text = f.read() | |
| translated = translate_text(text, target_lang) | |
| translated_content = translated.encode('utf-8') | |
| content_type = "text/plain" | |
| # Création du fichier traduit | |
| translated_filename = f"translated_{file.filename}" | |
| translated_filepath = os.path.join(UPLOAD_DIR, translated_filename) | |
| with open(translated_filepath, "wb") as f: | |
| f.write(translated_content) | |
| logger.info(f"Fichier traduit créé avec succès: {translated_filepath}") | |
| return FileResponse( | |
| path=translated_filepath, | |
| filename=translated_filename, | |
| media_type=content_type, | |
| headers={"Content-Disposition": f"attachment; filename={translated_filename}"} | |
| ) | |
| except Exception as e: | |
| logger.error(f"Erreur générale: {str(e)}", exc_info=True) | |
| raise HTTPException( | |
| status_code=500, | |
| detail=f"Une erreur est survenue lors du traitement de votre demande: {str(e)}" | |
| ) | |
| finally: | |
| # Nettoyage des fichiers temporaires | |
| if filepath: | |
| try: | |
| os.remove(filepath) | |
| logger.info(f"Fichier temporaire supprimé: {filepath}") | |
| except Exception as e: | |
| logger.warning(f"Erreur lors de la suppression du fichier temporaire: {str(e)}") | |
| if translated_filepath: | |
| try: | |
| os.remove(translated_filepath) | |
| logger.info(f"Fichier traduit supprimé: {translated_filepath}") | |
| except Exception as e: | |
| logger.warning(f"Erreur lors de la suppression du fichier traduit: {str(e)}") | |
| async def analyze(file: UploadFile = File(...), option: str = Form(...), lang: str = Form(...)): | |
| content = await file.read() | |
| # Traitement fictif : change ici pour résumé/traduction réel | |
| if option == "summarization": | |
| result = f"Résumé du fichier {file.filename}..." | |
| elif option == "translation": | |
| result = f"Traduction de {file.filename} en {lang}..." | |
| else: | |
| result = "Option inconnue." | |
| return {"result": result} | |