Update app.py
Browse files
app.py
CHANGED
|
@@ -1,106 +1,134 @@
|
|
| 1 |
-
import
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
import faiss
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
import
|
|
|
|
| 9 |
|
| 10 |
-
#
|
| 11 |
-
GEMINI_API_KEY = "
|
| 12 |
GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent"
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
"""Parse blood test results from extracted PDF text."""
|
| 53 |
-
results = {}
|
| 54 |
-
|
| 55 |
-
# Regular expression to match the table format: Component, Value, Min, Max, Units, State
|
| 56 |
-
pattern = r"(?P<component>\w+)\s+(?P<value>[\d.]+)\s+(?P<min>[\d.]+)\s+(?P<max>[\d.]+)\s+(?P<units>\w+/?.*)\s+(?P<state>\w+)"
|
| 57 |
-
|
| 58 |
-
matches = re.finditer(pattern, text, re.IGNORECASE)
|
| 59 |
-
|
| 60 |
-
for match in matches:
|
| 61 |
-
component = match.group("component")
|
| 62 |
-
value = float(match.group("value"))
|
| 63 |
-
state = match.group("state")
|
| 64 |
-
results[component] = {"value": value, "state": state}
|
| 65 |
-
|
| 66 |
return results
|
| 67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
-
# Step 6: Generate Personalized Advice
|
| 70 |
-
def generate_advice(test_results):
|
| 71 |
-
"""Generate personalized health advice using Gemini API."""
|
| 72 |
-
advice = {}
|
| 73 |
-
for parameter, value in test_results.items():
|
| 74 |
-
medical_info = retrieve_medical_knowledge(parameter)
|
| 75 |
-
prompt = (
|
| 76 |
-
f"The patient's {parameter} level is {value}. {medical_info} "
|
| 77 |
-
"Provide a clear, concise health recommendation."
|
| 78 |
-
)
|
| 79 |
-
response = gemini.generate_text(prompt=prompt) # Fixed API call
|
| 80 |
-
advice[parameter] = response.result
|
| 81 |
-
return advice
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
# Step 7: Main Function for Gradio Interface
|
| 85 |
-
def analyze_blood_test(pdf_file):
|
| 86 |
-
"""Main function to analyze the uploaded blood test PDF."""
|
| 87 |
-
text = extract_text_from_pdf(pdf_file)
|
| 88 |
-
test_results = parse_blood_test_results(text)
|
| 89 |
if not test_results:
|
| 90 |
-
return
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
#
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from sentence_transformers import SentenceTransformer
|
| 4 |
+
import fitz # PyMuPDF pour extraction du texte PDF
|
| 5 |
import faiss
|
| 6 |
+
import os
|
| 7 |
+
import numpy as np
|
| 8 |
+
import requests
|
| 9 |
+
import gradio as gr
|
| 10 |
|
| 11 |
+
# Configuration de l'API Gemini
|
| 12 |
+
GEMINI_API_KEY = "AIzaSyArbgg_p_HlmpgrcjVYemdSJeMCP9OTj3E"
|
| 13 |
GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent"
|
| 14 |
|
| 15 |
+
# Configuration des embeddings et FAISS
|
| 16 |
+
EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
|
| 17 |
+
model = SentenceTransformer(EMBEDDING_MODEL)
|
| 18 |
+
INDEX_PATH = "medical_faiss_index"
|
| 19 |
+
documents = [] # Liste pour stocker les textes indexés
|
| 20 |
+
|
| 21 |
+
# Chargement ou création de l'index FAISS
|
| 22 |
+
if os.path.exists(INDEX_PATH):
|
| 23 |
+
index = faiss.read_index(INDEX_PATH)
|
| 24 |
+
print("Index FAISS chargé avec succès.")
|
| 25 |
+
else:
|
| 26 |
+
index = faiss.IndexFlatL2(model.get_sentence_embedding_dimension())
|
| 27 |
+
print("Nouvel index FAISS créé.")
|
| 28 |
+
|
| 29 |
+
# Fonction pour extraire le texte des fichiers PDF
|
| 30 |
+
def extract_text_from_pdf(file_content: bytes):
|
| 31 |
+
pdf = fitz.open(stream=file_content, filetype="pdf")
|
| 32 |
+
paragraphs = []
|
| 33 |
+
for page in pdf:
|
| 34 |
+
text = page.get_text()
|
| 35 |
+
if text.strip():
|
| 36 |
+
paragraphs.extend([p.strip() for p in text.split("\n\n") if p.strip()])
|
| 37 |
+
return paragraphs
|
| 38 |
+
|
| 39 |
+
# Ajouter des documents médicaux à l'index FAISS
|
| 40 |
+
def add_medical_reference(file_content: bytes):
|
| 41 |
+
global index, documents
|
| 42 |
+
paragraphs = extract_text_from_pdf(file_content)
|
| 43 |
+
embeddings = model.encode(paragraphs)
|
| 44 |
+
index.add(np.array(embeddings, dtype="float32"))
|
| 45 |
+
documents.extend(paragraphs)
|
| 46 |
+
faiss.write_index(index, INDEX_PATH)
|
| 47 |
+
|
| 48 |
+
# Recherche dans FAISS pour trouver les documents pertinents
|
| 49 |
+
def search_faiss(query, k=5):
|
| 50 |
+
query_embedding = model.encode([query])
|
| 51 |
+
distances, indices = index.search(np.array(query_embedding, dtype="float32"), k)
|
| 52 |
+
results = [documents[i] for i in indices[0] if i < len(documents)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
return results
|
| 54 |
|
| 55 |
+
# Appel à l'API Gemini
|
| 56 |
+
def call_gemini_api(prompt):
|
| 57 |
+
headers = {"Content-Type": "application/json"}
|
| 58 |
+
payload = {
|
| 59 |
+
"contents": [
|
| 60 |
+
{
|
| 61 |
+
"parts": [
|
| 62 |
+
{"text": prompt}
|
| 63 |
+
]
|
| 64 |
+
}
|
| 65 |
+
]
|
| 66 |
+
}
|
| 67 |
+
try:
|
| 68 |
+
response = requests.post(f"{GEMINI_API_URL}?key={GEMINI_API_KEY}", json=payload, headers=headers)
|
| 69 |
+
response.raise_for_status()
|
| 70 |
+
response_json = response.json()
|
| 71 |
+
candidates = response_json.get("candidates", [])
|
| 72 |
+
if candidates:
|
| 73 |
+
return candidates[0]["content"]["parts"][0]["text"]
|
| 74 |
+
return "Pas de réponse disponible depuis Gemini."
|
| 75 |
+
except requests.exceptions.RequestException as e:
|
| 76 |
+
return f"Erreur API Gemini : {str(e)}"
|
| 77 |
+
|
| 78 |
+
# Ajouter un PDF de référence médicale
|
| 79 |
+
def upload_reference(file):
|
| 80 |
+
file_content = file.read()
|
| 81 |
+
add_medical_reference(file_content)
|
| 82 |
+
return "Référence médicale ajoutée avec succès."
|
| 83 |
+
|
| 84 |
+
# Analyser un PDF d'analyse de sang
|
| 85 |
+
def analyze_blood_test(file):
|
| 86 |
+
file_content = file.read()
|
| 87 |
+
test_results = extract_text_from_pdf(file_content)
|
| 88 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
if not test_results:
|
| 90 |
+
return "Aucun texte valide extrait du fichier d'analyse."
|
| 91 |
+
|
| 92 |
+
# Combine tous les résultats d'analyse dans un seul texte
|
| 93 |
+
query = "\n".join(test_results)
|
| 94 |
+
|
| 95 |
+
# Recherche dans l'index FAISS
|
| 96 |
+
relevant_docs = search_faiss(query, k=5)
|
| 97 |
+
context = "\n".join(relevant_docs)
|
| 98 |
+
|
| 99 |
+
# Enrichir le prompt avec les informations pertinentes
|
| 100 |
+
enriched_prompt = f"Voici les résultats d'analyse :\n{query}\n\nContexte pertinent :\n{context}"
|
| 101 |
+
gemini_response = call_gemini_api(enriched_prompt)
|
| 102 |
+
|
| 103 |
+
return {
|
| 104 |
+
"Réponse générée": gemini_response,
|
| 105 |
+
"Documents pertinents": relevant_docs
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
# Interface Gradio
|
| 109 |
+
def gradio_upload_reference(file):
|
| 110 |
+
return upload_reference(file)
|
| 111 |
+
|
| 112 |
+
def gradio_analyze_blood_test(file):
|
| 113 |
+
response = analyze_blood_test(file)
|
| 114 |
+
if isinstance(response, dict):
|
| 115 |
+
return f"Réponse générée :\n{response['Réponse générée']}\n\nDocuments pertinents :\n{response['Documents pertinents']}"
|
| 116 |
+
return response
|
| 117 |
+
|
| 118 |
+
# Lancer l'application Gradio
|
| 119 |
+
with gr.Blocks() as demo:
|
| 120 |
+
gr.Markdown("## Analyse Médicale avec RAG et Gemini")
|
| 121 |
+
|
| 122 |
+
with gr.Tab("Ajouter Références Médicales"):
|
| 123 |
+
ref_file = gr.File(label="Téléchargez un fichier PDF de référence médicale")
|
| 124 |
+
ref_output = gr.Textbox(label="Résultat")
|
| 125 |
+
ref_button = gr.Button("Ajouter")
|
| 126 |
+
ref_button.click(gradio_upload_reference, inputs=ref_file, outputs=ref_output)
|
| 127 |
+
|
| 128 |
+
with gr.Tab("Analyser un Résultat d'Analyse"):
|
| 129 |
+
test_file = gr.File(label="Téléchargez un fichier PDF d'analyse de sang")
|
| 130 |
+
analysis_output = gr.Textbox(label="Résultat")
|
| 131 |
+
analyze_button = gr.Button("Analyser")
|
| 132 |
+
analyze_button.click(gradio_analyze_blood_test, inputs=test_file, outputs=analysis_output)
|
| 133 |
+
|
| 134 |
+
demo.launch()
|