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
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, File, UploadFile # type: ignore
|
| 2 |
+
from transformers import pipeline, AutoTokenizer
|
| 3 |
+
import pdfplumber # type: ignore
|
| 4 |
+
import docx # type: ignore
|
| 5 |
+
import pptx # type: ignore
|
| 6 |
+
import pandas as pd # type: ignore
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import io
|
| 9 |
+
from fastapi.middleware.cors import CORSMiddleware # type: ignore
|
| 10 |
+
import uvicorn
|
| 11 |
|
| 12 |
app = FastAPI()
|
| 13 |
|
| 14 |
+
# Activer CORS pour autoriser les requêtes depuis le navigateur
|
| 15 |
+
app.add_middleware(
|
| 16 |
+
CORSMiddleware,
|
| 17 |
+
allow_origins=["*"], # Autoriser toutes les origines (mettre ["http://127.0.0.1:5500"] si nécessaire)
|
| 18 |
+
allow_credentials=True,
|
| 19 |
+
allow_methods=["*"], # Autoriser toutes les méthodes (GET, POST, etc.)
|
| 20 |
+
allow_headers=["*"], # Autoriser tous les headers
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
# 🔹 TEST : Vérifier si FastAPI démarre bien
|
| 24 |
+
@app.get("/")
|
| 25 |
+
def home():
|
| 26 |
+
return {"message": "Serveur FastAPI en ligne 🚀"}
|
| 27 |
+
|
| 28 |
+
# Charger les modèles Hugging Face avec debug
|
| 29 |
+
print("⏳ Chargement du modèle de résumé...")
|
| 30 |
+
try:
|
| 31 |
+
summarizer = pipeline("summarization", model="google/flan-t5-large")
|
| 32 |
+
print("✅ Modèle de résumé chargé.")
|
| 33 |
+
except Exception as e:
|
| 34 |
+
print(f"❌ Erreur lors du chargement du modèle de résumé : {e}")
|
| 35 |
+
|
| 36 |
+
print("⏳ Chargement du modèle d'interprétation d'image...")
|
| 37 |
+
try:
|
| 38 |
+
image_captioner = pipeline("image-to-text", model="nlpconnect/vit-gpt2-image-captioning")
|
| 39 |
+
print("✅ Modèle d'interprétation d'image chargé.")
|
| 40 |
+
except Exception as e:
|
| 41 |
+
print(f"❌ Erreur lors du chargement du modèle d'interprétation d'image : {e}")
|
| 42 |
+
|
| 43 |
+
# Charger le tokenizer pour limiter la taille du texte
|
| 44 |
+
tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-large")
|
| 45 |
+
|
| 46 |
+
# Fonction pour extraire le texte d'un fichier
|
| 47 |
+
def extract_text_from_file(file: UploadFile):
|
| 48 |
+
print(f"🔹 Extraction du texte depuis : {file.filename}")
|
| 49 |
+
|
| 50 |
+
try:
|
| 51 |
+
if file.filename.endswith(".pdf"):
|
| 52 |
+
with pdfplumber.open(file.file) as pdf:
|
| 53 |
+
text = " ".join([page.extract_text() for page in pdf.pages if page.extract_text()])
|
| 54 |
+
print("✅ Texte extrait depuis PDF :", text[:500]) # Afficher les 500 premiers caractères
|
| 55 |
+
return text
|
| 56 |
+
elif file.filename.endswith(".docx"):
|
| 57 |
+
doc = docx.Document(file.file)
|
| 58 |
+
text = " ".join([para.text for para in doc.paragraphs])
|
| 59 |
+
print("✅ Texte extrait depuis DOCX :", text[:500])
|
| 60 |
+
return text
|
| 61 |
+
elif file.filename.endswith(".pptx"):
|
| 62 |
+
ppt = pptx.Presentation(file.file)
|
| 63 |
+
text = " ".join([shape.text for slide in ppt.slides for shape in slide.shapes if hasattr(shape, "text")])
|
| 64 |
+
print("✅ Texte extrait depuis PPTX :", text[:500])
|
| 65 |
+
return text
|
| 66 |
+
elif file.filename.endswith(".xlsx"):
|
| 67 |
+
df = pd.read_excel(file.file)
|
| 68 |
+
text = " ".join(df.astype(str).values.flatten())
|
| 69 |
+
print("✅ Texte extrait depuis XLSX :", text[:500])
|
| 70 |
+
return text
|
| 71 |
+
else:
|
| 72 |
+
print("❌ Format non supporté :", file.filename)
|
| 73 |
+
return None
|
| 74 |
+
except Exception as e:
|
| 75 |
+
print(f"❌ Erreur lors de l'extraction du texte : {e}")
|
| 76 |
+
return None
|
| 77 |
+
|
| 78 |
+
# Fonction pour résumer du texte
|
| 79 |
+
def summarize_text(text):
|
| 80 |
+
print(f"🔍 Texte envoyé au modèle : {text[:500]}") # Afficher les 500 premiers caractères
|
| 81 |
+
tokens = tokenizer.tokenize(text)
|
| 82 |
+
truncated_text = tokenizer.convert_tokens_to_string(tokens[:1024]) # Limite à 1024 tokens
|
| 83 |
+
print(f"📏 Texte après troncature : {truncated_text[:500]}")
|
| 84 |
+
|
| 85 |
+
try:
|
| 86 |
+
summary = summarizer(truncated_text, max_length=130, min_length=30, do_sample=False)
|
| 87 |
+
print(f"📝 Résumé généré : {summary[0]['summary_text']}")
|
| 88 |
+
return summary[0]['summary_text']
|
| 89 |
+
except Exception as e:
|
| 90 |
+
print(f"❌ Erreur du modèle de résumé : {e}")
|
| 91 |
+
return None
|
| 92 |
+
|
| 93 |
+
# ✅ TEST : Extraire le texte d'un fichier
|
| 94 |
+
@app.post("/test_extraction/")
|
| 95 |
+
async def test_extraction(file: UploadFile = File(...)):
|
| 96 |
+
text = extract_text_from_file(file)
|
| 97 |
+
|
| 98 |
+
if not text or not text.strip():
|
| 99 |
+
return {"error": "Aucun texte extrait du fichier"}
|
| 100 |
+
|
| 101 |
+
return {"extracted_text": text[:500]} # Affichage limité à 500 caractères
|
| 102 |
+
|
| 103 |
+
# ✅ TEST : Vérifier le résumé d'un texte simple
|
| 104 |
+
@app.post("/test_summary_text/")
|
| 105 |
+
async def test_summary_text(text: str):
|
| 106 |
+
if not text or not text.strip():
|
| 107 |
+
return {"error": "Texte vide"}
|
| 108 |
+
|
| 109 |
+
summary = summarize_text(text)
|
| 110 |
+
if not summary:
|
| 111 |
+
return {"error": "Échec du résumé"}
|
| 112 |
+
|
| 113 |
+
return {"summary": summary}
|
| 114 |
+
|
| 115 |
+
# ✅ DEBUG : Voir toutes les étapes du résumé
|
| 116 |
+
@app.post("/debug_summary/")
|
| 117 |
+
async def debug_summary(text: str):
|
| 118 |
+
if not text or not text.strip():
|
| 119 |
+
return {"error": "Texte vide"}
|
| 120 |
+
|
| 121 |
+
try:
|
| 122 |
+
tokens = tokenizer.tokenize(text)
|
| 123 |
+
truncated_text = tokenizer.convert_tokens_to_string(tokens[:1024])
|
| 124 |
+
summary = summarizer(truncated_text, max_length=130, min_length=30, do_sample=False)
|
| 125 |
+
|
| 126 |
+
return {
|
| 127 |
+
"original_text": text[:500],
|
| 128 |
+
"truncated_text": truncated_text[:500],
|
| 129 |
+
"summary": summary[0]['summary_text']
|
| 130 |
+
}
|
| 131 |
+
except Exception as e:
|
| 132 |
+
return {"error": str(e)}
|
| 133 |
+
|
| 134 |
+
# 🔹 Endpoint principal : Résumer un fichier
|
| 135 |
+
@app.post("/summarize/")
|
| 136 |
+
async def summarize_file(file: UploadFile = File(...)):
|
| 137 |
+
text = extract_text_from_file(file)
|
| 138 |
+
if not text or not text.strip():
|
| 139 |
+
return {"error": "Aucun texte extrait du fichier"}
|
| 140 |
+
|
| 141 |
+
summary = summarize_text(text)
|
| 142 |
+
if not summary:
|
| 143 |
+
return {"error": "Échec du résumé"}
|
| 144 |
+
|
| 145 |
+
return {"summary": summary}
|
| 146 |
+
|
| 147 |
+
# 🔹 Endpoint : Interpréter une image
|
| 148 |
+
@app.post("/interpret/")
|
| 149 |
+
async def interpret_image(file: UploadFile = File(...)):
|
| 150 |
+
image = Image.open(io.BytesIO(await file.read()))
|
| 151 |
+
caption = image_captioner(image)
|
| 152 |
+
return {"caption": caption[0]['generated_text']}
|
| 153 |
+
|
| 154 |
|
| 155 |
+
if __name__ == "__main__":
|
| 156 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|