goldrode commited on
Commit
efa8cc0
·
verified ·
1 Parent(s): 30efe3c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -0
app.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ from fastapi import FastAPI
4
+ from sentence_transformers import SentenceTransformer
5
+ from fastapi.middleware.cors import CORSMiddleware
6
+ import fitz # PyMuPDF pour extraction du texte PDF
7
+ import faiss
8
+ import numpy as np
9
+ import requests
10
+ import pytesseract
11
+ from PIL import Image
12
+ import gradio as gr
13
+
14
+ # Installation automatique de Tesseract pour Windows
15
+ def install_tesseract_windows():
16
+ tesseract_installer_url = "https://github.com/tesseract-ocr/tesseract/releases/download/5.3.0/tesseract-5.3.0.20221214.exe"
17
+ installer_path = "tesseract_installer.exe"
18
+
19
+ if not os.path.exists("C:\\Program Files\\Tesseract-OCR"):
20
+ print("Installation de Tesseract OCR...")
21
+ # Télécharger l'installateur
22
+ subprocess.run(["curl", "-L", tesseract_installer_url, "-o", installer_path], shell=True, check=True)
23
+ # Exécuter l'installateur silencieusement
24
+ subprocess.run([installer_path, "/S"], shell=True, check=True)
25
+ os.environ["TESSDATA_PREFIX"] = "C:\\Program Files\\Tesseract-OCR\\"
26
+ pytesseract.pytesseract.tesseract_cmd = "C:\\Program Files\\Tesseract-OCR\\tesseract.exe"
27
+ print("Tesseract OCR installé avec succès.")
28
+ else:
29
+ pytesseract.pytesseract.tesseract_cmd = "C:\\Program Files\\Tesseract-OCR\\tesseract.exe"
30
+ print("Tesseract OCR déjà installé.")
31
+
32
+ install_tesseract_windows()
33
+
34
+ # Configuration de l'API Gemini
35
+ GEMINI_API_KEY = "AIzaSyArbgg_p_HlmpgrcjVYemdSJeMCP9OTj3E"
36
+ GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent"
37
+
38
+ # Configuration FAISS et embeddings
39
+ EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
40
+ model = SentenceTransformer(EMBEDDING_MODEL)
41
+ INDEX_PATH = "medical_faiss_index"
42
+ documents = []
43
+
44
+ if os.path.exists(INDEX_PATH):
45
+ index = faiss.read_index(INDEX_PATH)
46
+ print("Index FAISS chargé avec succès.")
47
+ else:
48
+ index = faiss.IndexFlatL2(model.get_sentence_embedding_dimension())
49
+ print("Nouvel index FAISS créé.")
50
+
51
+ # Fonction d'extraction de texte
52
+ def extract_text_from_pdf(file_content: bytes):
53
+ pdf = fitz.open(stream=file_content, filetype="pdf")
54
+ paragraphs = []
55
+ for page in pdf:
56
+ text = page.get_text()
57
+ if text.strip():
58
+ paragraphs.extend([p.strip() for p in text.split("\n\n") if p.strip()])
59
+ return paragraphs
60
+
61
+ def extract_text_from_image(file_path):
62
+ return pytesseract.image_to_string(Image.open(file_path))
63
+
64
+ # Fonction pour ajouter les documents de référence
65
+ def add_medical_reference(file):
66
+ with open(file.name, "rb") as f:
67
+ file_content = f.read()
68
+ paragraphs = extract_text_from_pdf(file_content)
69
+ embeddings = model.encode(paragraphs)
70
+ index.add(np.array(embeddings, dtype="float32"))
71
+ documents.extend(paragraphs)
72
+ faiss.write_index(index, INDEX_PATH)
73
+ return "Référence médicale ajoutée avec succès."
74
+
75
+ # Fonction pour analyser un fichier (PDF ou Image)
76
+ def analyze_blood_test(file):
77
+ try:
78
+ if file.name.endswith((".png", ".jpg", ".jpeg")):
79
+ extracted_text = extract_text_from_image(file.name)
80
+ elif file.name.endswith(".pdf"):
81
+ with open(file.name, "rb") as f:
82
+ file_content = f.read()
83
+ paragraphs = extract_text_from_pdf(file_content)
84
+ extracted_text = "\n".join(paragraphs)
85
+ else:
86
+ return "Format non supporté. Utilisez un PDF ou une image."
87
+
88
+ if not extracted_text.strip():
89
+ return "Aucun texte valide extrait."
90
+
91
+ # Recherche et appel Gemini
92
+ relevant_docs = search_faiss(extracted_text, k=5)
93
+ context = "\n".join(relevant_docs)
94
+ enriched_prompt = f"Voici les résultats d'analyse :\n{extracted_text}\n\nContexte pertinent :\n{context}"
95
+ gemini_response = call_gemini_api(enriched_prompt)
96
+
97
+ return f"Réponse générée :\n{gemini_response}\n\nDocuments pertinents :\n{relevant_docs}"
98
+ except Exception as e:
99
+ return f"Erreur : {str(e)}"
100
+
101
+ # Recherche FAISS
102
+ def search_faiss(query, k=5):
103
+ query_embedding = model.encode([query])
104
+ distances, indices = index.search(np.array(query_embedding, dtype="float32"), k)
105
+ return [documents[i] for i in indices[0] if i < len(documents)]
106
+
107
+ # Appel API Gemini
108
+ def call_gemini_api(prompt):
109
+ headers = {"Content-Type": "application/json"}
110
+ payload = {"contents": [{"parts": [{"text": prompt}]}]}
111
+ try:
112
+ response = requests.post(f"{GEMINI_API_URL}?key={GEMINI_API_KEY}", json=payload, headers=headers)
113
+ return response.json().get("candidates", [{}])[0].get("content", {}).get("parts", [{}])[0].get("text", "Pas de réponse.")
114
+ except Exception as e:
115
+ return f"Erreur API : {str(e)}"
116
+
117
+ # Interface Gradio
118
+ with gr.Blocks() as demo:
119
+ gr.Markdown("## Analyse Médicale avec RAG et Gemini")
120
+
121
+ with gr.Tab("Ajouter Références Médicales"):
122
+ ref_file = gr.File(label="Téléchargez un fichier PDF de référence médicale")
123
+ ref_output = gr.Textbox(label="Résultat")
124
+ ref_button = gr.Button("Ajouter")
125
+ ref_button.click(add_medical_reference, inputs=ref_file, outputs=ref_output)
126
+
127
+ with gr.Tab("Analyser un Résultat d'Analyse"):
128
+ test_file = gr.File(label="Téléchargez un fichier PDF ou image (JPG/PNG)")
129
+ analysis_output = gr.Textbox(label="Résultat")
130
+ analyze_button = gr.Button("Analyser")
131
+ analyze_button.click(analyze_blood_test, inputs=test_file, outputs=analysis_output)
132
+
133
+ demo.launch()