khalil2233 commited on
Commit
2bfc0c2
·
verified ·
1 Parent(s): cfd4e0d
Files changed (2) hide show
  1. app.py +105 -64
  2. requirements.txt +7 -1
app.py CHANGED
@@ -1,64 +1,105 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
-
62
-
63
- if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import numpy as np
4
+ import faiss
5
+ import gradio as gr
6
+ from sentence_transformers import SentenceTransformer
7
+ from groq import Groq
8
+
9
+ # Load FAISS index
10
+ FAISS_INDEX_PATH = "faiss_medical.index"
11
+ index = faiss.read_index(FAISS_INDEX_PATH)
12
+
13
+ # Load embedding model
14
+ embed_model = SentenceTransformer("all-MiniLM-L6-v2")
15
+
16
+ # Load FAISS ID → Text Mapping
17
+ with open("id_to_text.json", "r") as f:
18
+ id_to_text = json.load(f)
19
+
20
+ # Convert JSON keys to integers (FAISS returns int IDs)
21
+ id_to_text = {int(k): v for k, v in id_to_text.items()}
22
+
23
+ # Initialize Groq client
24
+ client = Groq(api_key=os.getenv("GROQ_API_KEY"))
25
+
26
+ def retrieve_medical_summary(query, k=3):
27
+ """
28
+ Retrieve the most relevant medical literature from FAISS.
29
+
30
+ Args:
31
+ query (str): The medical question.
32
+ k (int, optional): Number of closest documents to retrieve. Defaults to 3.
33
+
34
+ Returns:
35
+ str: The most relevant retrieved medical documents.
36
+ """
37
+ # Convert query to embedding
38
+ query_embedding = embed_model.encode([query])
39
+
40
+ # Perform FAISS search
41
+ D, I = index.search(np.array(query_embedding).astype("float32"), k)
42
+
43
+ # Retrieve the closest matching text using FAISS index IDs
44
+ retrieved_docs = [id_to_text.get(int(idx), "No relevant data found.") for idx in I[0]]
45
+
46
+ # Ensure all retrieved texts are strings (Flatten lists if needed)
47
+ retrieved_docs = [doc if isinstance(doc, str) else " ".join(doc) for doc in retrieved_docs]
48
+
49
+ # Join multiple retrieved documents into one response
50
+ return "\n\n---\n\n".join(retrieved_docs) if retrieved_docs else "No relevant data found."
51
+
52
+ def generate_medical_answer_groq(query, model="llama-3.3-70b-versatile", max_tokens=500, temperature=0.3):
53
+ """
54
+ Generates a medical response using Groq's API with LLaMA 3.3-70B, after retrieving relevant literature from FAISS.
55
+
56
+ Args:
57
+ query (str): The patient's medical question.
58
+ model (str, optional): The model to use. Defaults to "llama-3.3-70b-versatile".
59
+ max_tokens (int, optional): Max number of tokens to generate. Defaults to 200.
60
+ temperature (float, optional): Sampling temperature (higher = more creative). Defaults to 0.7.
61
+
62
+ Returns:
63
+ str: The AI-generated medical advice.
64
+ """
65
+
66
+ # Retrieve relevant medical literature from FAISS
67
+ retrieved_summary = retrieve_medical_summary(query)
68
+ print("\n🔍 Retrieved Medical Text for Query:", query)
69
+ print(retrieved_summary, "\n")
70
+
71
+ if not retrieved_summary or retrieved_summary == "No relevant data found.":
72
+ return "No relevant medical data found. Please consult a healthcare professional."
73
+
74
+ try:
75
+ # Send request to Groq API
76
+ response = client.chat.completions.create(
77
+ model=model,
78
+ messages=[
79
+ {"role": "system", "content": "You are an expert AI specializing in medical knowledge."},
80
+ {"role": "user", "content": f"Summarize the following medical literature and provide a structured medical answer:\n\n### Medical Literature ###\n{retrieved_summary}\n\n### Patient Question ###\n{query}\n\n### Medical Advice ###"}
81
+ ],
82
+ max_tokens=max_tokens,
83
+ temperature=temperature
84
+ )
85
+
86
+ return response.choices[0].message.content.strip() # Ensure clean output
87
+
88
+ except Exception as e:
89
+ return f"Error generating response: {str(e)}"
90
+
91
+ # Gradio Interface
92
+ def ask_medical_question(question):
93
+ return generate_medical_answer_groq(question)
94
+
95
+ # Create Gradio Interface
96
+ iface = gr.Interface(
97
+ fn=ask_medical_question,
98
+ inputs=gr.Textbox(lines=2, placeholder="Enter your medical question here..."),
99
+ outputs=gr.Textbox(lines=10, placeholder="AI-generated medical advice will appear here..."),
100
+ title="Medical Question Answering System",
101
+ description="Ask any medical question, and the AI will provide an answer based on medical literature."
102
+ )
103
+
104
+ # Launch the Gradio app
105
+ iface.launch()
requirements.txt CHANGED
@@ -1 +1,7 @@
1
- huggingface_hub==0.25.2
 
 
 
 
 
 
 
1
+ sentence-transformers
2
+ faiss-cpu
3
+ groq
4
+ gradio
5
+ numpy
6
+ nltk
7
+ shutil