bash98 commited on
Commit
89bb3a5
·
verified ·
1 Parent(s): 60c1cb4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +334 -0
app.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import gradio as gr
3
+ import faiss
4
+ import numpy as np
5
+
6
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
7
+ from sentence_transformers import SentenceTransformer
8
+
9
+ # Models
10
+ GEN_MODEL_NAME = "google/flan-t5-small"
11
+ EMB_MODEL_NAME = "sentence-transformers/all-MiniLM-L6-v2"
12
+
13
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
14
+
15
+ tokenizer = AutoTokenizer.from_pretrained(GEN_MODEL_NAME)
16
+ gen_model = AutoModelForSeq2SeqLM.from_pretrained(GEN_MODEL_NAME).to(DEVICE)
17
+ embedder = SentenceTransformer(EMB_MODEL_NAME, device=DEVICE)
18
+
19
+ DISCLAIMER = (
20
+ "Disclaimer: This tool provides general health information only. "
21
+ "It does not give medical advice, diagnosis, or prescriptions. "
22
+ "Always speak to a qualified healthcare professional for personal medical concerns or emergencies."
23
+ )
24
+
25
+ health_facts = [
26
+ {
27
+ "id": 1,
28
+ "topic": "Hypertension",
29
+ "text": (
30
+ "Hypertension is a long-term condition in which the force of blood against the walls of the arteries is consistently too high. "
31
+ "Over time, uncontrolled high blood pressure can damage blood vessels and organs such as the heart, brain, kidneys, and eyes, increasing the risk of heart disease and stroke. "
32
+ "Many people with hypertension do not have obvious symptoms, which is why it is sometimes called a 'silent killer', so regular blood pressure checks are important. "
33
+ "Lifestyle measures such as reducing salt intake, engaging in regular physical activity, managing stress, maintaining a healthy weight, and avoiding tobacco products play a major role in controlling blood pressure."
34
+ )
35
+ },
36
+ {
37
+ "id": 2,
38
+ "topic": "Diabetes",
39
+ "text": (
40
+ "Type 2 diabetes is a chronic condition in which the body does not use insulin properly or does not produce enough insulin, leading to elevated blood sugar levels over time. "
41
+ "If blood sugar remains high for many years, it can damage blood vessels and nerves, affecting the eyes, kidneys, heart, and feet. "
42
+ "People with type 2 diabetes are encouraged to adopt habits such as eating balanced meals with controlled portions, staying physically active, and attending regular medical checkups to monitor blood sugar and related complications. "
43
+ "Early detection, lifestyle changes, and appropriate medical follow-up can significantly reduce the risk of serious long-term problems."
44
+ )
45
+ },
46
+ {
47
+ "id": 3,
48
+ "topic": "Pregnancy nutrition",
49
+ "text": (
50
+ "During pregnancy, good nutrition supports the health of both the mother and the developing baby. "
51
+ "Balanced meals that include vegetables, fruits, whole grains, sources of protein, and healthy fats help supply essential vitamins and minerals. "
52
+ "Nutrients such as folic acid and iron are especially important in pregnancy because they support the baby’s development and help prevent certain birth defects and anemia. "
53
+ "Pregnant women are advised to avoid alcohol, smoking, and recreational drugs, and to discuss any supplements or herbal remedies with a qualified healthcare professional during antenatal visits."
54
+ )
55
+ },
56
+ {
57
+ "id": 4,
58
+ "topic": "Vaccination",
59
+ "text": (
60
+ "Vaccination is a safe and effective way to train the immune system to recognize and fight specific infections without causing the actual disease. "
61
+ "Many vaccines are given during childhood, but some are also recommended in adulthood, in pregnancy, and for people with certain health conditions. "
62
+ "Keeping vaccination schedules up to date helps protect not only the individual but also the wider community by reducing the spread of infectious diseases. "
63
+ "Delaying or skipping recommended vaccines can increase the risk of outbreaks and leave vulnerable groups, such as young children and older adults, unprotected."
64
+ )
65
+ },
66
+ {
67
+ "id": 5,
68
+ "topic": "Common cold",
69
+ "text": (
70
+ "The common cold is usually a mild infection of the nose and throat caused by viruses, often leading to symptoms such as a runny nose, sore throat, sneezing, and mild cough. "
71
+ "Most colds improve on their own within a week or two, and complications are uncommon in otherwise healthy people. "
72
+ "Simple measures such as resting, drinking enough fluids, and using home remedies for comfort can help people feel better while the body fights the infection. "
73
+ "Because the common cold is viral, antibiotics, which are designed to treat bacterial infections, do not cure it and are generally not needed."
74
+ )
75
+ },
76
+ {
77
+ "id": 6,
78
+ "topic": "Asthma",
79
+ "text": (
80
+ "Asthma is a long-term condition in which the airways become inflamed and narrow, making it harder for air to move in and out of the lungs. "
81
+ "People with asthma may experience episodes of wheezing, chest tightness, coughing, and shortness of breath, which can be mild or severe. "
82
+ "Common triggers include dust, smoke, cold air, respiratory infections, strong smells, and sometimes exercise. "
83
+ "Understanding personal triggers, avoiding them when possible, and following an asthma action plan from a healthcare professional helps reduce symptoms and improve quality of life."
84
+ )
85
+ },
86
+ {
87
+ "id": 7,
88
+ "topic": "Malaria prevention",
89
+ "text": (
90
+ "Malaria is a potentially serious disease transmitted by the bite of infected Anopheles mosquitoes, and it is common in many tropical and subtropical regions. "
91
+ "Early symptoms often include fever, chills, headache, and body pains, which can resemble other illnesses, so testing is important when malaria is suspected. "
92
+ "Prevention strategies include sleeping under insecticide-treated mosquito nets, using protective clothing, and reducing mosquito breeding sites such as stagnant water around the home. "
93
+ "Prompt testing and treatment when fever occurs in malaria-endemic areas help prevent severe illness and complications."
94
+ )
95
+ },
96
+ {
97
+ "id": 8,
98
+ "topic": "Tuberculosis",
99
+ "text": (
100
+ "Tuberculosis (TB) is an infectious disease caused by bacteria that most often affect the lungs. "
101
+ "It spreads through the air when a person with active TB in the lungs coughs, sneezes, or speaks, and someone nearby breathes in the droplets. "
102
+ "Common symptoms include a persistent cough lasting more than a few weeks, chest pain, weight loss, night sweats, and fever. "
103
+ "Early detection, adherence to the full course of treatment prescribed by a healthcare professional, and support from TB programs are important to cure the disease and reduce transmission."
104
+ )
105
+ },
106
+ {
107
+ "id": 9,
108
+ "topic": "HIV basics",
109
+ "text": (
110
+ "HIV is a virus that weakens the immune system by attacking specific cells that help the body fight infections. "
111
+ "Without proper treatment and care, ongoing damage to the immune system can eventually lead to AIDS, which is the advanced stage of HIV infection. "
112
+ "HIV can be transmitted through unprotected sex, sharing needles or sharp instruments that break the skin, and from mother to child during pregnancy, birth, or breastfeeding without preventive measures. "
113
+ "Regular HIV testing, safer sex practices, and access to appropriate medical care help people living with HIV maintain their health and reduce the risk of transmission to others."
114
+ )
115
+ },
116
+ {
117
+ "id": 10,
118
+ "topic": "Mental health",
119
+ "text": (
120
+ "Mental health refers to a person’s emotional, psychological, and social well-being, influencing how they think, feel, and behave in daily life. "
121
+ "Challenges such as prolonged sadness, strong anxiety, loss of interest in usual activities, difficulty concentrating, or major changes in sleep and appetite can signal a mental health concern. "
122
+ "Life events, ongoing stress, physical illness, and social or economic pressures can all affect mental health. "
123
+ "Talking to trusted people, seeking professional support, and reducing stigma around mental health conditions are important steps in promoting overall wellbeing."
124
+ )
125
+ },
126
+ {
127
+ "id": 11,
128
+ "topic": "Healthy eating",
129
+ "text": (
130
+ "Healthy eating means choosing a variety of foods that provide the nutrients the body needs to function well and stay strong. "
131
+ "Meals that include vegetables, fruits, whole grains, beans or lean animal proteins, and small amounts of healthy fats help support energy, growth, and disease prevention. "
132
+ "Limiting foods and drinks that are very high in sugar, salt, and unhealthy fats can reduce the risk of conditions such as obesity, hypertension, and type 2 diabetes. "
133
+ "Regular meal patterns, mindful portion sizes, and drinking enough safe water are also important parts of a healthy eating routine."
134
+ )
135
+ },
136
+ {
137
+ "id": 12,
138
+ "topic": "Physical activity",
139
+ "text": (
140
+ "Physical activity includes any body movement that uses energy, from walking and household chores to structured exercise and sports. "
141
+ "Regular movement helps maintain a healthy weight, supports heart and lung function, strengthens muscles and bones, and can improve mood and sleep quality. "
142
+ "Even small amounts of daily activity are beneficial, especially for people who have been mostly inactive, and it can be built up gradually. "
143
+ "Choosing activities that are enjoyable and suitable for a person’s age and health status makes it easier to stay active over the long term."
144
+ )
145
+ },
146
+ {
147
+ "id": 13,
148
+ "topic": "Childhood fever",
149
+ "text": (
150
+ "Fever in children is usually a sign that the body is fighting an infection, which may be caused by viruses, bacteria, or other germs. "
151
+ "Caregivers should pay attention to the child’s overall behavior, ability to drink fluids, and level of alertness, not just the temperature reading. "
152
+ "Warning signs that require urgent medical attention include difficulty breathing, convulsions, persistent vomiting, inability to drink, unusual sleepiness, or a fever that lasts several days. "
153
+ "Keeping the child comfortable, offering fluids, and seeking professional advice when worried helps ensure that serious conditions are not missed."
154
+ )
155
+ },
156
+ {
157
+ "id": 14,
158
+ "topic": "Diarrhoea and dehydration",
159
+ "text": (
160
+ "Diarrhoea is the passing of loose or watery stools more often than usual and can be caused by infections, food-related issues, or other conditions. "
161
+ "One of the main dangers of diarrhoea, especially in young children and older adults, is dehydration, which happens when the body loses too much water and salts. "
162
+ "Signs of dehydration include dry mouth, reduced urination, unusual tiredness, dizziness, and in children, sunken eyes or a sunken soft spot on the head. "
163
+ "Offering safe fluids, watching for warning signs, and seeking medical care when diarrhoea is severe, persistent, or accompanied by blood or high fever are important steps."
164
+ )
165
+ },
166
+ {
167
+ "id": 15,
168
+ "topic": "Menstrual health",
169
+ "text": (
170
+ "Menstruation is a normal monthly process in people with a uterus, where the lining of the womb is shed if pregnancy has not occurred. "
171
+ "Cycle length and flow can vary between individuals, but sudden major changes, very heavy bleeding, or severe pain may require medical evaluation. "
172
+ "Using clean menstrual products, changing them regularly, and maintaining good personal hygiene help prevent irritation and infections. "
173
+ "Open, accurate information about menstruation supports dignity, reduces shame, and enables people to manage their periods safely and confidently."
174
+ )
175
+ },
176
+ {
177
+ "id": 16,
178
+ "topic": "Oral and dental hygiene",
179
+ "text": (
180
+ "Good oral hygiene helps keep the teeth, gums, and mouth healthy, which also supports overall wellbeing. "
181
+ "Brushing teeth at least twice a day with a suitable toothbrush and fluoride toothpaste helps remove food particles and plaque, reducing the risk of tooth decay and gum disease. "
182
+ "Cleaning between the teeth, limiting sugary snacks and drinks, and visiting a dental professional for regular checks are also important. "
183
+ "Ignoring oral health problems can lead to pain, infection, tooth loss, and difficulties with eating and speaking."
184
+ )
185
+ },
186
+ {
187
+ "id": 17,
188
+ "topic": "Smoking and health",
189
+ "text": (
190
+ "Smoking exposes the body to many harmful chemicals that damage the lungs, heart, and blood vessels, and it greatly increases the risk of several cancers. "
191
+ "People who smoke are more likely to develop chronic respiratory diseases, heart disease, stroke, and complications from infections. "
192
+ "Stopping smoking, even after many years, brings health benefits, such as improved breathing, circulation, and reduced risk of heart attack and some cancers over time. "
193
+ "Support from healthcare professionals, support groups, and smoke-free environments can make it easier for people who smoke to reduce or quit."
194
+ )
195
+ },
196
+ {
197
+ "id": 18,
198
+ "topic": "Alcohol and health",
199
+ "text": (
200
+ "Alcohol affects the brain, liver, heart, and many other organs, and drinking large amounts or drinking frequently can harm physical and mental health. "
201
+ "Heavy or risky drinking is linked to liver disease, certain cancers, high blood pressure, injuries, violence, and relationship and work problems. "
202
+ "Some people are more vulnerable to the effects of alcohol due to age, health conditions, pregnancy, or the medicines they take. "
203
+ "Reducing alcohol intake, avoiding drinking in unsafe situations, and seeking help when alcohol use feels out of control can lower the risk of harm."
204
+ )
205
+ },
206
+ {
207
+ "id": 19,
208
+ "topic": "Obesity and weight management",
209
+ "text": (
210
+ "Obesity refers to having excessive body fat that may affect health and is often related to an imbalance between energy taken in from food and energy used by the body. "
211
+ "It increases the risk of several conditions, including type 2 diabetes, hypertension, heart disease, joint problems, and some cancers. "
212
+ "Healthy weight management focuses on long-term habits, such as eating balanced meals, being physically active, getting enough sleep, and reducing long periods of sitting. "
213
+ "Small, realistic changes maintained over time tend to be more sustainable than extreme short-term diets."
214
+ )
215
+ },
216
+ {
217
+ "id": 20,
218
+ "topic": "Kidney health",
219
+ "text": (
220
+ "The kidneys are organs that filter waste products and excess fluid from the blood and help regulate blood pressure, mineral balance, and red blood cell production. "
221
+ "Long-term uncontrolled hypertension, diabetes, repeated kidney infections, and some medications or toxins can gradually damage the kidneys. "
222
+ "Early kidney problems often cause few or no symptoms, so regular checkups are important for people at higher risk. "
223
+ "Protecting kidney health includes managing chronic conditions with professional guidance, staying hydrated with safe fluids, and avoiding unnecessary use of substances that can harm the kidneys."
224
+ )
225
+ },
226
+ ]
227
+
228
+ corpus_texts = [item["text"] for item in health_facts]
229
+ corpus_embeddings = embedder.encode(corpus_texts, convert_to_numpy=True)
230
+
231
+ dimension = corpus_embeddings.shape[1]
232
+ index = faiss.IndexFlatL2(dimension)
233
+ index.add(corpus_embeddings)
234
+
235
+ unsafe_keywords = [
236
+ "dose", "dosage", "mg", "milligram", "tablet", "capsule",
237
+ "prescribe", "prescription", "how many times", "self medicate",
238
+ "diagnose", "diagnosis"
239
+ ]
240
+
241
+ def is_potentially_unsafe(question: str) -> bool:
242
+ q_lower = question.lower()
243
+ return any(keyword in q_lower for keyword in unsafe_keywords)
244
+
245
+ def retrieve_facts(query: str, k: int = 3):
246
+ query_embedding = embedder.encode([query], convert_to_numpy=True)
247
+ distances, indices = index.search(query_embedding, k)
248
+ results = []
249
+ for idx in indices[0]:
250
+ results.append(health_facts[idx]["text"])
251
+ return results
252
+
253
+ def generate_answer_from_context(question: str, contexts, max_tokens: int = 200) -> str:
254
+ context_str = "\n\n".join(contexts)
255
+ prompt = f"""
256
+ You are a healthcare information assistant. Use ONLY the information in the context below to answer the user's question in simple language.
257
+
258
+ Context:
259
+ {context_str}
260
+
261
+ Rules:
262
+ - Do not make a diagnosis.
263
+ - Do not give medication doses or prescriptions.
264
+ - Encourage the user to talk to a qualified healthcare professional for personal decisions.
265
+ - If the answer is not in the context, say you are not sure and ask them to speak to a professional.
266
+
267
+ Question: {question}
268
+
269
+ Answer:
270
+ """
271
+ inputs = tokenizer(
272
+ prompt,
273
+ return_tensors="pt",
274
+ truncation=True,
275
+ max_length=1024
276
+ ).to(DEVICE)
277
+
278
+ with torch.no_grad():
279
+ outputs = gen_model.generate(
280
+ **inputs,
281
+ max_new_tokens=max_tokens,
282
+ num_beams=4,
283
+ early_stopping=True
284
+ )
285
+
286
+ answer = tokenizer.decode(outputs[0], skip_special_tokens=True)
287
+ return answer.strip()
288
+
289
+ def health_qa_pipeline(question: str) -> str:
290
+ question = question.strip()
291
+ if len(question) == 0:
292
+ return "Please type a question."
293
+
294
+ if is_potentially_unsafe(question):
295
+ safe_msg = (
296
+ "I cannot provide medication doses, prescriptions, or make diagnoses. "
297
+ "Please consult a qualified healthcare professional for that. "
298
+ "I can help with general information only."
299
+ )
300
+ return f"{safe_msg}\n\n{DISCLAIMER}"
301
+
302
+ contexts = retrieve_facts(question, k=3)
303
+ answer = generate_answer_from_context(question, contexts)
304
+ return f"{answer}\n\n{DISCLAIMER}"
305
+
306
+ def qa_interface(question: str) -> str:
307
+ return health_qa_pipeline(question)
308
+
309
+ with gr.Blocks() as demo:
310
+ gr.Markdown("# 🧠 Health Facts Q&A Bot (Educational Only)")
311
+ gr.Markdown(
312
+ "Ask general health questions covered by the internal facts. "
313
+ "The bot uses retrieval augmented generation and will not give doses or diagnoses."
314
+ )
315
+
316
+ question_box = gr.Textbox(
317
+ label="Your question",
318
+ placeholder="e.g. How can I reduce my risk of hypertension?",
319
+ lines=2
320
+ )
321
+ answer_box = gr.Textbox(
322
+ label="Answer",
323
+ lines=10
324
+ )
325
+ ask_button = gr.Button("Ask")
326
+
327
+ ask_button.click(
328
+ qa_interface,
329
+ inputs=question_box,
330
+ outputs=answer_box,
331
+ )
332
+
333
+ if __name__ == "__main__":
334
+ demo.launch()