Devansh Kumar commited on
Commit
fdadb3e
·
1 Parent(s): c443cac

Add application file

Browse files
Files changed (3) hide show
  1. app.py +299 -0
  2. health_meta.json +0 -0
  3. output_with_descriptions.json +0 -0
app.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from sentence_transformers import SentenceTransformer
3
+ import google.generativeai as genai
4
+ import faiss
5
+ import json
6
+ import time
7
+ import os
8
+ from dotenv import load_dotenv
9
+ import speech_recognition as sr
10
+
11
+ # Load resources
12
+ index = faiss.read_index("health_index.faiss")
13
+ with open("health_meta.json") as f:
14
+ data = json.load(f)
15
+ model = SentenceTransformer("BAAI/bge-base-en-v1.5")
16
+
17
+ # Set your Gemini API key
18
+ load_dotenv()
19
+ API_KEY = os.getenv("GEMINI_API")
20
+ genai.configure(api_key=API_KEY) # Replace with your actual API key
21
+
22
+ # Initialize the Gemini model
23
+ gen_model = genai.GenerativeModel('gemini-2.5-flash-lite-preview-06-17')
24
+
25
+ def get_health_response(user_query: str, user_query_org: str, k=3):
26
+ query_emb = model.encode([user_query], convert_to_numpy=True)
27
+ _, indices = index.search(query_emb, k=k)
28
+
29
+ context = "\n".join([f"Disease: {data[idx]['disease']}\nSymptoms: {data[idx]['symptoms']}"
30
+ f"\nDescription: {data[idx]['description']}"
31
+ for idx in indices[0]])
32
+
33
+ prompt = f"""You are a medical health assistant which answers health related queries or tells the disease based on the symptoms provided
34
+ For the given context: {context}
35
+ Answer this question in the same language as the question: {user_query_org}
36
+ and cite a trustworthy source (like healthline, WebMD, wikipedia or WHO).
37
+ Also if you recieve non-medical queries, tell the user to ask only health related queries.
38
+ Answer:"""
39
+
40
+ response = gen_model.generate_content(prompt)
41
+
42
+ return response.text.strip()
43
+
44
+ def generate_translation(text):
45
+ prompt = f"Give only the most accurate English translation of the given text if it is any other language except English, if the input is already in English return it as it is, nothing else: {text}"
46
+ try:
47
+ response = gen_model.generate_content(prompt)
48
+ return response.text.strip()
49
+ except Exception as e:
50
+ print(f"Error for {text}")
51
+ return "Description not available."
52
+
53
+ from gradio.themes.utils import fonts
54
+ from gradio.themes.base import Base
55
+
56
+ class HealthTheme(Base):
57
+ def __init__(self):
58
+ super().__init__(
59
+ font=[
60
+ fonts.GoogleFont("Asap"),
61
+ fonts.Font("ui-sans-serif"),
62
+ fonts.Font("sans-serif")
63
+ ],
64
+ font_mono=[
65
+ fonts.GoogleFont("Fira Code"),
66
+ fonts.Font("ui-monospace"),
67
+ fonts.Font("monospace")
68
+ ]
69
+ )
70
+
71
+ self.set(
72
+ body_background_fill="#FFFFFF",
73
+ body_background_fill_dark="linear-gradient(to right, #001027, #00112e, #001235, #00123c, #001142)",
74
+ background_fill_primary="#FFFFFF",
75
+ background_fill_primary_dark="#19191956",
76
+ background_fill_secondary="#ECF2F7",
77
+ background_fill_secondary_dark="linear-gradient(to right, #000b1a, #000b1e, #000b22, #000b26, #000b2a)",
78
+ block_background_fill="#ECF2F7",
79
+ block_background_fill_dark="linear-gradient(to right, #000b1a, #000b1e, #000b22, #000b26, #000b2a)",
80
+ block_border_color="#dce3e8",
81
+ block_border_color_dark="#000431",
82
+ button_primary_background_fill="#338AC9",
83
+ button_primary_background_fill_dark="#0c6ebd",
84
+ button_primary_background_fill_hover="#0c6ebd",
85
+ button_primary_background_fill_hover_dark="#000538",
86
+ button_primary_text_color="#ECF2F7",
87
+ button_primary_text_color_dark="#08003BFF",
88
+ button_primary_text_color_hover_dark="#ECF2F7",
89
+ input_background_fill="#dce3e8",
90
+ input_background_fill_dark="#FF0000FF",
91
+ block_label_text_color="#4EACEF",
92
+ block_label_text_color_dark="#4EACEF",
93
+ block_title_text_color="#4EACEF",
94
+ loader_color="#4EACEF",
95
+ loader_color_dark="#4EACEF",
96
+ body_text_color="#191919",
97
+ body_text_color_dark="#ECF2F7",
98
+ body_text_color_subdued="#636668",
99
+ body_text_color_subdued_dark="#c4c4c4",
100
+ body_text_size="*text_md",
101
+ body_text_weight="400",
102
+ border_color_accent="#dce3e8",
103
+ border_color_accent_dark="#242424",
104
+ border_color_accent_subdued="#dce3e867",
105
+ border_color_accent_subdued_dark="#24242467",
106
+ border_color_primary="#dce3e8",
107
+ border_color_primary_dark="#242424",
108
+ button_border_width="*input_border_width",
109
+ button_border_width_dark="*input_border_width",
110
+ button_cancel_background_fill="#dce3e8",
111
+ button_cancel_background_fill_dark="#242424",
112
+ button_cancel_background_fill_hover="#d0d7db",
113
+ button_cancel_background_fill_hover_dark="#202020",
114
+ button_cancel_border_color="#191919",
115
+ button_cancel_border_color_dark="#ECF2F7",
116
+ button_cancel_border_color_hover="#202020",
117
+ button_cancel_border_color_hover_dark="#a1c3d8",
118
+ button_cancel_text_color="#4EACEF",
119
+ button_cancel_text_color_dark="#4EACEF",
120
+ button_cancel_text_color_hover="#0c6ebd",
121
+ button_cancel_text_color_hover_dark="#0c6ebd",
122
+ button_large_padding="*spacing_lg calc(2 * *spacing_lg)",
123
+ button_large_radius="*radius_lg",
124
+ button_large_text_size="*text_lg",
125
+ button_large_text_weight="600",
126
+ button_primary_border_color="#191919",
127
+ button_primary_border_color_dark="#ECF2F7",
128
+ button_primary_border_color_hover="#202020",
129
+ button_primary_border_color_hover_dark="#a1c3d8",
130
+ button_primary_text_color_hover="#e1eaf0",
131
+ button_secondary_background_fill="#dce3e8",
132
+ button_secondary_background_fill_dark="#040052",
133
+ button_secondary_background_fill_hover="#d0d7db",
134
+ button_secondary_background_fill_hover_dark="#000644",
135
+ button_secondary_border_color="#dce3e8",
136
+ button_secondary_border_color_dark="#242424",
137
+ button_secondary_border_color_hover="#d0d7db",
138
+ button_secondary_border_color_hover_dark="#202020",
139
+ button_secondary_text_color ="#4EACEF",
140
+ button_secondary_text_color_dark="#4EACEF",
141
+ button_secondary_text_color_hover="#0c6ebd",
142
+ button_secondary_text_color_hover_dark="#d9eeff",
143
+ button_small_padding="*spacing_sm calc(2 * *spacing_sm)",
144
+ button_small_radius ="*radius_lg",
145
+ button_small_text_size="*text_md",
146
+ button_small_text_weight="400",
147
+ button_transition ="background-color 0.2s ease",
148
+ color_accent="*primary_500",
149
+ color_accent_soft="#dce3e8",
150
+ color_accent_soft_dark="#0e1834",
151
+ container_radius="*radius_lg",
152
+ embed_radius="*radius_lg",
153
+ error_background_fill="#dce3e8",
154
+ error_background_fill_dark="#242424",
155
+ error_border_color="#191919",
156
+ error_border_color_dark="#ECF2F7",
157
+ error_border_width="1px",
158
+ error_border_width_dark="1px",
159
+ error_icon_color="#b91c1c",
160
+ error_icon_color_dark="#ef4444",
161
+ error_text_color="#4EACEF",
162
+ error_text_color_dark="#4EACEF",
163
+ form_gap_width="0px",
164
+ input_background_fill_focus="#dce3e8",
165
+ input_background_fill_focus_dark="#2F2626",
166
+ input_background_fill_hover="#d0d7db",
167
+ input_background_fill_hover_dark="#202020",
168
+ input_border_color="#191919",
169
+ input_border_color_dark="#ECF2F7",
170
+ input_border_color_focus="#191919",
171
+ input_border_color_focus_dark="#ECF2F7",
172
+ input_border_color_hover="#202020",
173
+ input_border_color_hover_dark="#a1c3d8",
174
+ input_border_width="0px",
175
+ input_padding="*spacing_xl",
176
+ input_placeholder_color="#19191930",
177
+ input_placeholder_color_dark="#FFFFFF4F",
178
+ input_radius="*radius_lg",
179
+ input_shadow="#19191900",
180
+ input_shadow_dark="#ECF2F700",
181
+ input_shadow_focus="#19191900",
182
+ input_shadow_focus_dark="#ECF2F700",
183
+ input_text_size="*text_md",
184
+ input_text_weight="400",
185
+ layout_gap="*spacing_xxl",
186
+ link_text_color="#4EACEF",
187
+ link_text_color_active="#4EACEF",
188
+ link_text_color_active_dark="#4EACEF",
189
+ link_text_color_dark ="#4EACEF",
190
+ link_text_color_hover ="#0c6ebd",
191
+ link_text_color_hover_dark="#0c6ebd",
192
+ link_text_color_visited ="#4EACEF",
193
+ link_text_color_visited_dark="#4EACEF",
194
+ )
195
+
196
+ # Use the theme
197
+ custom_theme = HealthTheme()
198
+
199
+ # Add audio transcription function
200
+ def transcribe_audio(audio_path):
201
+ r = sr.Recognizer()
202
+ with sr.AudioFile(audio_path) as source:
203
+ audio = r.record(source)
204
+ try:
205
+ return r.recognize_google(audio)
206
+ except sr.UnknownValueError:
207
+ return "[Could not understand audio]"
208
+ except sr.RequestError:
209
+ return "[Audio service error]"
210
+
211
+ def print_like_dislike(x: gr.LikeData):
212
+ print(f"Message #{x.index} was {'liked' if x.liked else 'disliked'}: {x.value}")
213
+
214
+ # Modified add_message function
215
+ def add_message(history, message):
216
+ # Process text input
217
+ if message["text"]:
218
+ history.append({"role": "user", "content": message["text"]})
219
+
220
+ # Process files (including audio)
221
+ if message.get("files"):
222
+ for file in message["files"]:
223
+ # Transcribe audio files
224
+ if file.endswith(('.wav', '.mp3', '.ogg', '.flac')):
225
+ transcribed = transcribe_audio(file)
226
+ history.append({"role": "user", "content": f"[Audio]: {transcribed}"})
227
+ # Handle other file types
228
+ else:
229
+ history.append({"role": "user", "content": f"[File received: {file}]"})
230
+
231
+ return history, gr.MultimodalTextbox(value=None, interactive=False)
232
+
233
+ def bot(history):
234
+ # Context window of last N turns
235
+ N = 6
236
+ memory_context = ""
237
+ for turn in history[-N:]:
238
+ if isinstance(turn["content"], str):
239
+ role = turn["role"]
240
+ prefix = "User" if role == "user" else "Assistant"
241
+ memory_context += f"{prefix}: {turn['content']}\n"
242
+
243
+ user_input = history[-1]["content"]
244
+ translated = generate_translation(user_input)
245
+ full_prompt = f"{memory_context}User: {translated}\nAssistant:"
246
+
247
+ response = get_health_response(full_prompt, user_input)
248
+
249
+ history.append({"role": "assistant", "content": ""})
250
+ for char in response:
251
+ history[-1]['content'] += char
252
+ time.sleep(0.02)
253
+ yield history
254
+
255
+ def undo(history):
256
+ if len(history) >= 2:
257
+ return history[:-2]
258
+ return []
259
+
260
+ def retry(history):
261
+ if len(history) >= 2:
262
+ last_user = history[-2]
263
+ history = history[:-2] + [last_user]
264
+ return history
265
+ return history
266
+
267
+ # --- UI Setup ---
268
+ with gr.Blocks(theme = custom_theme) as demo:
269
+ gr.Markdown("""<h1 style='font-weight:600;'>🩺 Clinikit</h1>
270
+ <p style='color:#666;font-size:15px'>Ask health-related questions or enter symptoms below. Built with memory, streaming, multilingual text support and voice inputs(english only).</p>""")
271
+
272
+ chatbot = gr.Chatbot(
273
+ label="Assistant",
274
+ type="messages",
275
+ avatar_images=(None, "https://e7.pngegg.com/pngimages/369/865/png-clipart-physician-hospital-dr-mary-c-kirk-md-doctor-of-medicine-computer-icons-the-doctor-miscellaneous-black-thumbnail.png")
276
+ )
277
+ msg = gr.MultimodalTextbox(
278
+ interactive=True,
279
+ file_count="multiple",
280
+ placeholder="Enter symptoms or ask a health question...",
281
+ show_label=False,
282
+ sources=["microphone"]
283
+ )
284
+ with gr.Row():
285
+ retry_btn = gr.Button("🔁 Retry")
286
+ undo_btn = gr.Button("↩️ Undo")
287
+
288
+ chat_msg = msg.submit(add_message, [chatbot, msg], [chatbot, msg])
289
+ bot_msg = chat_msg.then(bot, chatbot, chatbot)
290
+ bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [msg])
291
+
292
+ retry_btn.click(retry, chatbot, chatbot).then(bot, chatbot, chatbot).then(lambda h: h, chatbot, chatbot)
293
+ undo_btn.click(undo, chatbot, chatbot).then(lambda h: h, chatbot, chatbot)
294
+
295
+ chatbot.like(print_like_dislike, None, None, like_user_message=True)
296
+
297
+ gr.Markdown("""<footer style='text-align:center;margin-top:20px;color:#aaa;'>Built using Gradio, Hugging Face & Gemini API</footer>""")
298
+
299
+ demo.launch(share=True, pwa=True)
health_meta.json ADDED
The diff for this file is too large to render. See raw diff
 
output_with_descriptions.json ADDED
The diff for this file is too large to render. See raw diff