goldrode commited on
Commit
391e3e0
·
verified ·
1 Parent(s): da222c7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -98
app.py CHANGED
@@ -1,106 +1,134 @@
1
- import gradio as gr
2
- import fitz # PyMuPDF
3
- import re
4
- import numpy as np
5
  import faiss
6
- from sklearn.feature_extraction.text import TfidfVectorizer
7
- from sklearn.preprocessing import normalize
8
- import google.generativeai as gemini
 
9
 
10
- # Step 1: Configure Gemini API
11
- GEMINI_API_KEY = "AIzaSyDiyT3x5563LM3k277sR8qQ2wAwWIpb-lQ"
12
  GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent"
13
 
14
-
15
- # Step 2: Define Medical Knowledge Base
16
- medical_knowledge = [
17
- "Normal hemoglobin levels are 13.8 to 17.2 g/dL for men and 12.1 to 15.1 g/dL for women.",
18
- "Low hemoglobin levels indicate anemia, causing fatigue and weakness.",
19
- "High hemoglobin levels may suggest polycythemia or dehydration.",
20
- "Normal fasting blood glucose levels are 70 to 99 mg/dL.",
21
- "Elevated glucose levels indicate diabetes or prediabetes and require further testing.",
22
- ]
23
-
24
- # Step 3: Build FAISS Index
25
- vectorizer = TfidfVectorizer()
26
- knowledge_vectors = vectorizer.fit_transform(medical_knowledge).toarray()
27
- knowledge_vectors = normalize(knowledge_vectors) # Normalize vectors for cosine similarity
28
-
29
- # Initialize FAISS Index
30
- dimension = knowledge_vectors.shape[1]
31
- faiss_index = faiss.IndexFlatL2(dimension)
32
- faiss_index.add(knowledge_vectors)
33
-
34
- def retrieve_medical_knowledge(parameter):
35
- """Retrieve relevant knowledge using FAISS."""
36
- query_vector = vectorizer.transform([parameter]).toarray()
37
- query_vector = normalize(query_vector) # Normalize the query vector
38
- _, indices = faiss_index.search(query_vector, 1) # Retrieve top 1 result
39
- return medical_knowledge[indices[0][0]]
40
-
41
- # Step 4: Extract Text from PDF
42
- def extract_text_from_pdf(pdf_file):
43
- """Extract text from the uploaded PDF file."""
44
- text = ""
45
- with fitz.open(pdf_file.name) as pdf: # Use file path directly
46
- for page in pdf:
47
- text += page.get_text()
48
- return text
49
-
50
- # Step 5: Parse Blood Test Results
51
- def parse_blood_test_results(text):
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 {"error": "No recognizable blood test results found in the PDF."} # Always return a dictionary
91
- advice = generate_advice(test_results)
92
- return advice # This is a dictionary
93
-
94
-
95
- # Gradio Interface
96
- iface = gr.Interface(
97
- fn=analyze_blood_test,
98
- inputs=gr.File(label="Upload Blood Test PDF"),
99
- outputs=gr.JSON(label="Health Advice"), # Ensure valid JSON is returned
100
- title="Blood Test Analysis with RAG and Gemini (FAISS)",
101
- description="Upload a PDF with blood test results to receive personalized health advice."
102
- )
103
-
104
-
105
- if __name__ == "__main__":
106
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()