File size: 19,211 Bytes
89bb3a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import torch
import gradio as gr
import faiss
import numpy as np

from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
from sentence_transformers import SentenceTransformer

# Models
GEN_MODEL_NAME = "google/flan-t5-small"
EMB_MODEL_NAME = "sentence-transformers/all-MiniLM-L6-v2"

DEVICE = "cuda" if torch.cuda.is_available() else "cpu"

tokenizer = AutoTokenizer.from_pretrained(GEN_MODEL_NAME)
gen_model = AutoModelForSeq2SeqLM.from_pretrained(GEN_MODEL_NAME).to(DEVICE)
embedder = SentenceTransformer(EMB_MODEL_NAME, device=DEVICE)

DISCLAIMER = (
    "Disclaimer: This tool provides general health information only. "
    "It does not give medical advice, diagnosis, or prescriptions. "
    "Always speak to a qualified healthcare professional for personal medical concerns or emergencies."
)

health_facts =  [
    {
        "id": 1,
        "topic": "Hypertension",
        "text": (
            "Hypertension is a long-term condition in which the force of blood against the walls of the arteries is consistently too high. "
            "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. "
            "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. "
            "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."
        )
    },
    {
        "id": 2,
        "topic": "Diabetes",
        "text": (
            "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. "
            "If blood sugar remains high for many years, it can damage blood vessels and nerves, affecting the eyes, kidneys, heart, and feet. "
            "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. "
            "Early detection, lifestyle changes, and appropriate medical follow-up can significantly reduce the risk of serious long-term problems."
        )
    },
    {
        "id": 3,
        "topic": "Pregnancy nutrition",
        "text": (
            "During pregnancy, good nutrition supports the health of both the mother and the developing baby. "
            "Balanced meals that include vegetables, fruits, whole grains, sources of protein, and healthy fats help supply essential vitamins and minerals. "
            "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. "
            "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."
        )
    },
    {
        "id": 4,
        "topic": "Vaccination",
        "text": (
            "Vaccination is a safe and effective way to train the immune system to recognize and fight specific infections without causing the actual disease. "
            "Many vaccines are given during childhood, but some are also recommended in adulthood, in pregnancy, and for people with certain health conditions. "
            "Keeping vaccination schedules up to date helps protect not only the individual but also the wider community by reducing the spread of infectious diseases. "
            "Delaying or skipping recommended vaccines can increase the risk of outbreaks and leave vulnerable groups, such as young children and older adults, unprotected."
        )
    },
    {
        "id": 5,
        "topic": "Common cold",
        "text": (
            "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. "
            "Most colds improve on their own within a week or two, and complications are uncommon in otherwise healthy people. "
            "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. "
            "Because the common cold is viral, antibiotics, which are designed to treat bacterial infections, do not cure it and are generally not needed."
        )
    },
    {
        "id": 6,
        "topic": "Asthma",
        "text": (
            "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. "
            "People with asthma may experience episodes of wheezing, chest tightness, coughing, and shortness of breath, which can be mild or severe. "
            "Common triggers include dust, smoke, cold air, respiratory infections, strong smells, and sometimes exercise. "
            "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."
        )
    },
    {
        "id": 7,
        "topic": "Malaria prevention",
        "text": (
            "Malaria is a potentially serious disease transmitted by the bite of infected Anopheles mosquitoes, and it is common in many tropical and subtropical regions. "
            "Early symptoms often include fever, chills, headache, and body pains, which can resemble other illnesses, so testing is important when malaria is suspected. "
            "Prevention strategies include sleeping under insecticide-treated mosquito nets, using protective clothing, and reducing mosquito breeding sites such as stagnant water around the home. "
            "Prompt testing and treatment when fever occurs in malaria-endemic areas help prevent severe illness and complications."
        )
    },
    {
        "id": 8,
        "topic": "Tuberculosis",
        "text": (
            "Tuberculosis (TB) is an infectious disease caused by bacteria that most often affect the lungs. "
            "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. "
            "Common symptoms include a persistent cough lasting more than a few weeks, chest pain, weight loss, night sweats, and fever. "
            "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."
        )
    },
    {
        "id": 9,
        "topic": "HIV basics",
        "text": (
            "HIV is a virus that weakens the immune system by attacking specific cells that help the body fight infections. "
            "Without proper treatment and care, ongoing damage to the immune system can eventually lead to AIDS, which is the advanced stage of HIV infection. "
            "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. "
            "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."
        )
    },
    {
        "id": 10,
        "topic": "Mental health",
        "text": (
            "Mental health refers to a person’s emotional, psychological, and social well-being, influencing how they think, feel, and behave in daily life. "
            "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. "
            "Life events, ongoing stress, physical illness, and social or economic pressures can all affect mental health. "
            "Talking to trusted people, seeking professional support, and reducing stigma around mental health conditions are important steps in promoting overall wellbeing."
        )
    },
    {
        "id": 11,
        "topic": "Healthy eating",
        "text": (
            "Healthy eating means choosing a variety of foods that provide the nutrients the body needs to function well and stay strong. "
            "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. "
            "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. "
            "Regular meal patterns, mindful portion sizes, and drinking enough safe water are also important parts of a healthy eating routine."
        )
    },
    {
        "id": 12,
        "topic": "Physical activity",
        "text": (
            "Physical activity includes any body movement that uses energy, from walking and household chores to structured exercise and sports. "
            "Regular movement helps maintain a healthy weight, supports heart and lung function, strengthens muscles and bones, and can improve mood and sleep quality. "
            "Even small amounts of daily activity are beneficial, especially for people who have been mostly inactive, and it can be built up gradually. "
            "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."
        )
    },
    {
        "id": 13,
        "topic": "Childhood fever",
        "text": (
            "Fever in children is usually a sign that the body is fighting an infection, which may be caused by viruses, bacteria, or other germs. "
            "Caregivers should pay attention to the child’s overall behavior, ability to drink fluids, and level of alertness, not just the temperature reading. "
            "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. "
            "Keeping the child comfortable, offering fluids, and seeking professional advice when worried helps ensure that serious conditions are not missed."
        )
    },
    {
        "id": 14,
        "topic": "Diarrhoea and dehydration",
        "text": (
            "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. "
            "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. "
            "Signs of dehydration include dry mouth, reduced urination, unusual tiredness, dizziness, and in children, sunken eyes or a sunken soft spot on the head. "
            "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."
        )
    },
    {
        "id": 15,
        "topic": "Menstrual health",
        "text": (
            "Menstruation is a normal monthly process in people with a uterus, where the lining of the womb is shed if pregnancy has not occurred. "
            "Cycle length and flow can vary between individuals, but sudden major changes, very heavy bleeding, or severe pain may require medical evaluation. "
            "Using clean menstrual products, changing them regularly, and maintaining good personal hygiene help prevent irritation and infections. "
            "Open, accurate information about menstruation supports dignity, reduces shame, and enables people to manage their periods safely and confidently."
        )
    },
    {
        "id": 16,
        "topic": "Oral and dental hygiene",
        "text": (
            "Good oral hygiene helps keep the teeth, gums, and mouth healthy, which also supports overall wellbeing. "
            "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. "
            "Cleaning between the teeth, limiting sugary snacks and drinks, and visiting a dental professional for regular checks are also important. "
            "Ignoring oral health problems can lead to pain, infection, tooth loss, and difficulties with eating and speaking."
        )
    },
    {
        "id": 17,
        "topic": "Smoking and health",
        "text": (
            "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. "
            "People who smoke are more likely to develop chronic respiratory diseases, heart disease, stroke, and complications from infections. "
            "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. "
            "Support from healthcare professionals, support groups, and smoke-free environments can make it easier for people who smoke to reduce or quit."
        )
    },
    {
        "id": 18,
        "topic": "Alcohol and health",
        "text": (
            "Alcohol affects the brain, liver, heart, and many other organs, and drinking large amounts or drinking frequently can harm physical and mental health. "
            "Heavy or risky drinking is linked to liver disease, certain cancers, high blood pressure, injuries, violence, and relationship and work problems. "
            "Some people are more vulnerable to the effects of alcohol due to age, health conditions, pregnancy, or the medicines they take. "
            "Reducing alcohol intake, avoiding drinking in unsafe situations, and seeking help when alcohol use feels out of control can lower the risk of harm."
        )
    },
    {
        "id": 19,
        "topic": "Obesity and weight management",
        "text": (
            "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. "
            "It increases the risk of several conditions, including type 2 diabetes, hypertension, heart disease, joint problems, and some cancers. "
            "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. "
            "Small, realistic changes maintained over time tend to be more sustainable than extreme short-term diets."
        )
    },
    {
        "id": 20,
        "topic": "Kidney health",
        "text": (
            "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. "
            "Long-term uncontrolled hypertension, diabetes, repeated kidney infections, and some medications or toxins can gradually damage the kidneys. "
            "Early kidney problems often cause few or no symptoms, so regular checkups are important for people at higher risk. "
            "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."
        )
    },
]

corpus_texts = [item["text"] for item in health_facts]
corpus_embeddings = embedder.encode(corpus_texts, convert_to_numpy=True)

dimension = corpus_embeddings.shape[1]
index = faiss.IndexFlatL2(dimension)
index.add(corpus_embeddings)

unsafe_keywords = [
    "dose", "dosage", "mg", "milligram", "tablet", "capsule",
    "prescribe", "prescription", "how many times", "self medicate",
    "diagnose", "diagnosis"
]

def is_potentially_unsafe(question: str) -> bool:
    q_lower = question.lower()
    return any(keyword in q_lower for keyword in unsafe_keywords)

def retrieve_facts(query: str, k: int = 3):
    query_embedding = embedder.encode([query], convert_to_numpy=True)
    distances, indices = index.search(query_embedding, k)
    results = []
    for idx in indices[0]:
        results.append(health_facts[idx]["text"])
    return results

def generate_answer_from_context(question: str, contexts, max_tokens: int = 200) -> str:
    context_str = "\n\n".join(contexts)
    prompt = f"""
You are a healthcare information assistant. Use ONLY the information in the context below to answer the user's question in simple language.

Context:
{context_str}

Rules:
- Do not make a diagnosis.
- Do not give medication doses or prescriptions.
- Encourage the user to talk to a qualified healthcare professional for personal decisions.
- If the answer is not in the context, say you are not sure and ask them to speak to a professional.

Question: {question}

Answer:
"""
    inputs = tokenizer(
        prompt,
        return_tensors="pt",
        truncation=True,
        max_length=1024
    ).to(DEVICE)

    with torch.no_grad():
        outputs = gen_model.generate(
            **inputs,
            max_new_tokens=max_tokens,
            num_beams=4,
            early_stopping=True
        )

    answer = tokenizer.decode(outputs[0], skip_special_tokens=True)
    return answer.strip()

def health_qa_pipeline(question: str) -> str:
    question = question.strip()
    if len(question) == 0:
        return "Please type a question."

    if is_potentially_unsafe(question):
        safe_msg = (
            "I cannot provide medication doses, prescriptions, or make diagnoses. "
            "Please consult a qualified healthcare professional for that. "
            "I can help with general information only."
        )
        return f"{safe_msg}\n\n{DISCLAIMER}"

    contexts = retrieve_facts(question, k=3)
    answer = generate_answer_from_context(question, contexts)
    return f"{answer}\n\n{DISCLAIMER}"

def qa_interface(question: str) -> str:
    return health_qa_pipeline(question)

with gr.Blocks() as demo:
    gr.Markdown("# 🧠 Health Facts Q&A Bot (Educational Only)")
    gr.Markdown(
        "Ask general health questions covered by the internal facts. "
        "The bot uses retrieval augmented generation and will not give doses or diagnoses."
    )

    question_box = gr.Textbox(
        label="Your question",
        placeholder="e.g. How can I reduce my risk of hypertension?",
        lines=2
    )
    answer_box = gr.Textbox(
        label="Answer",
        lines=10
    )
    ask_button = gr.Button("Ask")

    ask_button.click(
        qa_interface,
        inputs=question_box,
        outputs=answer_box,
    )

if __name__ == "__main__":
    demo.launch()