Spaces:
Runtime error
Runtime error
| #!/usr/bin/env python3 | |
| """ | |
| Generate comprehensive medical Q&A pairs from test_medical_queries.json | |
| These will be indexed into the MedicalRetriever for knowledge-based responses. | |
| """ | |
| import json | |
| import os | |
| def load_test_queries(): | |
| """Load the test medical queries""" | |
| dataset_path = os.path.join(os.path.dirname(__file__), "datasets", "test_medical_queries.json") | |
| with open(dataset_path, 'r') as f: | |
| return json.load(f) | |
| def generate_qa_pairs(): | |
| """Generate comprehensive Q&A pairs for all test queries""" | |
| test_data = load_test_queries() | |
| qa_pairs = [] | |
| # Answers for common symptoms | |
| symptom_answers = { | |
| "I have a mild fever—should I rest or see a doctor?": | |
| "A mild fever (under 101°F/38.3°C) usually indicates your body is fighting an infection. Rest, stay hydrated, and take over-the-counter fever reducers like acetaminophen if needed. See a doctor if the fever persists beyond 3 days, rises above 103°F (39.4°C), or is accompanied by severe symptoms like difficulty breathing, chest pain, or confusion.", | |
| "What should I do if I feel dizzy suddenly?": | |
| "Sudden dizziness can be caused by dehydration, low blood sugar, inner ear issues, or standing up too quickly. Sit or lie down immediately to prevent falls. Drink water and eat something if you haven't recently. If dizziness is severe, persistent, accompanied by chest pain, shortness of breath, or vision changes, seek medical attention immediately.", | |
| "Is it normal to feel tired all the time?": | |
| "Persistent fatigue isn't normal and can have many causes including poor sleep quality, stress, anemia, thyroid issues, or nutritional deficiencies. Ensure you're getting 7-9 hours of quality sleep, eating a balanced diet, staying hydrated, and managing stress. If fatigue persists despite lifestyle improvements, consult a doctor for evaluation.", | |
| "I have a sore throat—when should I worry?": | |
| "Most sore throats are caused by viral infections and resolve on their own within a week. See a doctor if you have: severe pain that makes swallowing difficult, high fever (over 101°F), swollen glands lasting more than 2 weeks, difficulty breathing, blood in saliva, or symptoms lasting beyond 7 days. Strep throat requires antibiotics.", | |
| "What can cause nausea without vomiting?": | |
| "Nausea without vomiting can result from digestive issues, motion sickness, anxiety, medication side effects, pregnancy, or food sensitivities. Try eating small, bland meals, staying hydrated with clear fluids, avoiding strong odors, and getting fresh air. If nausea persists, is severe, or accompanied by severe abdominal pain or fever, consult a doctor.", | |
| "How long does a common cold usually last?": | |
| "A common cold typically lasts 7-10 days. Symptoms usually peak around days 2-3 and gradually improve. The first 3 days are usually the most contagious. Getting adequate rest, staying hydrated, and using over-the-counter remedies can help manage symptoms. See a doctor if symptoms worsen after 5 days or don't improve after 10 days.", | |
| "When is a headache considered serious?": | |
| "Seek immediate medical attention for headaches that are: sudden and severe ('thunderclap' headache), accompanied by fever, stiff neck, confusion, vision changes, or difficulty speaking, following a head injury, progressively worsening over days/weeks, or different from your usual headache pattern. Persistent headaches affecting daily life also warrant medical evaluation.", | |
| "I feel short of breath sometimes—is that normal?": | |
| "Occasional shortness of breath during intense exercise is normal, but unexplained or frequent breathlessness is not. It can indicate asthma, anxiety, heart conditions, or lung issues. Seek immediate care if breathlessness is sudden and severe, accompanied by chest pain, blue lips/fingernails, or occurs at rest. Mild but persistent symptoms should be evaluated by a doctor.", | |
| "I feel weak since morning, what could be the reason?": | |
| "Morning weakness can result from poor sleep quality, dehydration, low blood sugar, nutritional deficiencies (especially B12, iron), or electrolyte imbalances. It can also indicate viral infections or chronic conditions. Ensure you're eating a balanced breakfast, staying hydrated, and getting adequate sleep. If weakness persists or worsens, consult a healthcare provider.", | |
| "Why do I feel cold even when the weather is warm?": | |
| "Feeling cold in warm weather can indicate anemia (low iron), hypothyroidism (underactive thyroid), poor circulation, low body weight, or simply being sensitive to temperature. Other causes include dehydration or vitamin B12 deficiency. If this is persistent and bothersome, see a doctor for blood tests to check thyroid function, iron levels, and other markers.", | |
| "I wake up tired every day, is that normal?": | |
| "Consistently waking up tired suggests poor sleep quality and isn't normal. Common causes include sleep apnea, insomnia, stress, poor sleep hygiene, or underlying health conditions like thyroid disorders or depression. Improve sleep hygiene: maintain a consistent sleep schedule, avoid screens before bed, keep your bedroom cool and dark. If problems persist, consult a sleep specialist.", | |
| "I have chills but no fever, should I worry?": | |
| "Chills without fever can occur with sudden temperature changes, anxiety, hypoglycemia (low blood sugar), or the early stages of an infection before fever develops. It can also indicate hypothyroidism or anemia. If chills are isolated and brief, they're usually not concerning. Consult a doctor if accompanied by other symptoms or if they're frequent and unexplained.", | |
| "Why do I feel lightheaded when I stand up?": | |
| "Lightheadedness upon standing (orthostatic hypotension) occurs when blood pressure drops temporarily. It's common and usually harmless but can indicate dehydration, anemia, or medication side effects. Stand up slowly, stay hydrated, and avoid prolonged standing. If episodes are frequent, severe, or accompanied by fainting, heart palpitations, or chest pain, see a doctor." | |
| } | |
| # Answers for pain and discomfort | |
| pain_answers = { | |
| "What could cause stomach pain after eating?": | |
| "Stomach pain after eating can result from indigestion, food intolerances (lactose, gluten), acid reflux, gastritis, or overeating. It may also indicate gallstones, peptic ulcers, or irritable bowel syndrome (IBS). Try eating smaller meals, avoiding trigger foods (spicy, fatty, acidic), and eating slowly. See a doctor if pain is severe, persistent, or accompanied by vomiting, fever, or blood in stool.", | |
| "Is lower back pain common?": | |
| "Yes, lower back pain is very common and affects about 80% of adults at some point. Common causes include muscle strain, poor posture, prolonged sitting, or improper lifting. Most cases resolve with rest, stretching, and over-the-counter pain relievers. See a doctor if pain is severe, radiates down legs (sciatica), causes numbness/weakness, follows an injury, or persists beyond 6 weeks.", | |
| "What can help with joint pain at home?": | |
| "Home remedies for joint pain include: applying ice for acute pain/swelling or heat for chronic stiffness, gentle stretching and low-impact exercise (swimming, walking), maintaining a healthy weight, taking over-the-counter anti-inflammatories (ibuprofen, naproxen), using topical pain creams, getting adequate rest, and staying hydrated. If pain is severe, persistent, or limits mobility, consult a doctor.", | |
| "Why do I feel chest discomfort after exercise?": | |
| "Chest discomfort after exercise can be normal muscle soreness, acid reflux, or exercise-induced asthma. However, it can also indicate heart problems, especially if accompanied by shortness of breath, dizziness, or radiating pain to arms/jaw. If you're over 40, have risk factors (smoking, high blood pressure, diabetes), or if discomfort is new or worsening, seek immediate medical evaluation to rule out cardiac issues.", | |
| "What are common reasons for body aches?": | |
| "Common causes of body aches include viral infections (flu, cold), overexertion/muscle strain, stress/tension, dehydration, lack of sleep, fibromyalgia, or chronic fatigue syndrome. Medications (statins) can also cause muscle aches. Treatment includes rest, hydration, gentle stretching, warm baths, and over-the-counter pain relievers. See a doctor if aches are severe, persistent, or accompanied by fever, rash, or weakness.", | |
| "When should muscle pain be checked by a doctor?": | |
| "See a doctor for muscle pain that: is severe or getting worse, persists beyond 3-5 days despite home care, is accompanied by swelling, redness, or warmth, causes weakness or difficulty moving, follows a tick bite, is associated with new medications (especially statins), includes dark urine (possible rhabdomyolysis), or occurs without clear cause.", | |
| "I have pain on one side of my body, is that serious?": | |
| "Unilateral (one-sided) pain can have many causes. It may indicate kidney stones, appendicitis (if right lower abdomen), ovarian cyst, muscle strain, or nerve issues like shingles. The seriousness depends on location, severity, and accompanying symptoms. Seek immediate care for severe abdominal pain, fever, vomiting, or chest pain. Otherwise, consult a doctor if pain is persistent or worsening.", | |
| "Why does my neck hurt after waking up?": | |
| "Neck pain upon waking often results from poor sleeping posture, an unsupportive pillow, sleeping on your stomach, or muscle tension/stress. It can also indicate cervical spine issues. Use a supportive pillow that keeps your neck aligned with your spine, sleep on your back or side, and try gentle neck stretches. If pain is severe, persistent, or accompanied by numbness/tingling, see a doctor.", | |
| "My legs hurt after standing too long, is that normal?": | |
| "Yes, leg pain after prolonged standing is common, especially from muscle fatigue, poor circulation, or varicose veins. To prevent it: wear comfortable shoes, shift weight between legs, take sitting breaks, stretch, elevate legs when resting, and stay hydrated. If pain is severe, accompanied by swelling, discoloration, or warmth, or if you have risk factors for blood clots, consult a doctor.", | |
| "I feel sharp pain that comes and goes, what could it be?": | |
| "Intermittent sharp pain can have many causes depending on location: muscle spasms, nerve irritation, digestive issues (gas, cramping), kidney stones, or cardiac issues. The pattern, location, and triggers are important. If pain is severe, frequent, or in the chest/abdomen with other symptoms (shortness of breath, fever, vomiting), seek medical evaluation. Otherwise, monitor and discuss with your doctor." | |
| } | |
| # Answers for digestive health | |
| digestive_answers = { | |
| "What causes frequent bloating?": | |
| "Frequent bloating can result from swallowing air while eating, eating too quickly, consuming gas-producing foods (beans, cruciferous vegetables, carbonated drinks), food intolerances (lactose, gluten), constipation, or conditions like IBS or SIBO. To reduce bloating: eat slowly, avoid carbonated drinks, limit gas-producing foods, stay hydrated, exercise regularly, and consider a food diary to identify triggers. Persistent bloating should be evaluated by a doctor.", | |
| "Is occasional heartburn normal?": | |
| "Occasional heartburn (once or twice a month) is common and usually not concerning, often triggered by spicy/fatty foods, large meals, or lying down after eating. However, frequent heartburn (more than twice weekly) may indicate GERD (acid reflux disease). Manage with: smaller meals, avoiding trigger foods, not eating close to bedtime, elevating your head while sleeping, and antacids. See a doctor if heartburn is frequent, severe, or interferes with sleep.", | |
| "What should I do if I have constipation?": | |
| "For constipation, try: increasing fiber intake (fruits, vegetables, whole grains), drinking more water (8-10 glasses daily), exercising regularly, establishing a regular bathroom routine, and not ignoring the urge to go. Over-the-counter stool softeners or fiber supplements can help. Avoid overusing laxatives. See a doctor if constipation persists beyond 2 weeks, is accompanied by severe pain, blood in stool, or unexplained weight loss.", | |
| "What are common causes of diarrhea?": | |
| "Common causes include viral/bacterial infections ('stomach flu'), food poisoning, food intolerances (lactose, fructose), medications (antibiotics), stress/anxiety, or chronic conditions like IBS or inflammatory bowel disease. Treatment focuses on staying hydrated with water and electrolyte solutions, eating bland foods (BRAT diet: bananas, rice, applesauce, toast), and avoiding dairy/caffeine. See a doctor if diarrhea lasts over 3 days, includes blood/mucus, causes severe dehydration, or is accompanied by high fever.", | |
| "How can I improve my digestion naturally?": | |
| "Natural ways to improve digestion: eat slowly and chew thoroughly, consume adequate fiber (25-35g daily), stay well-hydrated, exercise regularly (aids gut motility), manage stress, eat smaller, more frequent meals, include probiotic foods (yogurt, kefir, sauerkraut), limit processed foods and sugar, and avoid eating large meals before bed. Identifying and avoiding personal food triggers also helps.", | |
| "When is stomach pain an emergency?": | |
| "Seek immediate medical care for stomach pain that is: sudden and severe (especially if accompanied by rigid abdomen), localized in the lower right abdomen (possible appendicitis), accompanied by vomiting blood, bloody or black tarry stools, high fever (over 102°F), pregnancy-related, after abdominal trauma, or prevents you from sitting still. Also seek care if pain spreads to chest/shoulder or you have difficulty breathing.", | |
| "I feel heavy after meals, what could help?": | |
| "Feeling heavy after meals often indicates overeating, eating too quickly, or consuming heavy/fatty foods. To help: eat smaller portions, chew food thoroughly, avoid lying down immediately after eating, limit fatty/fried foods, stay hydrated, take a light walk after meals, and don't skip meals (which leads to overeating later). If heaviness persists despite these changes or is accompanied by pain, see a doctor.", | |
| "Why do I feel gassy all the time?": | |
| "Excessive gas can result from swallowing air (eating/drinking quickly, chewing gum), consuming gas-producing foods (beans, broccoli, onions, carbonated drinks), food intolerances (lactose, gluten), or digestive disorders like IBS or SIBO. Reduce gas by: eating slowly, avoiding carbonated drinks and sugar alcohols, limiting gas-producing foods, staying active, and taking probiotics. If gas is persistent and bothersome, consult a doctor.", | |
| "Is it normal to skip bowel movements for a day or two?": | |
| "Bowel movement frequency varies widely—anywhere from 3 times a day to 3 times a week can be normal. Skipping a day or two is usually fine if it's normal for you and you feel comfortable. It becomes concerning if you notice a significant change from your regular pattern, experience discomfort, or have other symptoms. Maintain regular habits with adequate fiber, water, and physical activity.", | |
| "What foods commonly cause indigestion?": | |
| "Common indigestion triggers include: spicy foods, fatty/fried foods, acidic foods (citrus, tomatoes), chocolate, caffeine, alcohol, carbonated beverages, onions, garlic, and peppermint. Individual triggers vary. Keep a food diary to identify your specific triggers. Eating large meals, eating too quickly, or lying down right after eating can also cause indigestion regardless of food type." | |
| } | |
| # Process symptoms and health concerns | |
| for category, questions in test_data.get("symptoms_and_health_concerns", {}).items(): | |
| for question in questions: | |
| answer = None | |
| # Use predefined answers if available | |
| if question in symptom_answers: | |
| answer = symptom_answers[question] | |
| elif question in pain_answers: | |
| answer = pain_answers[question] | |
| elif question in digestive_answers: | |
| answer = digestive_answers[question] | |
| else: | |
| # Generate generic but helpful answer for remaining questions | |
| answer = generate_generic_answer(question, category) | |
| qa_pairs.append({ | |
| "question": question, | |
| "answer": answer, | |
| "source": "Generated", | |
| "category": category | |
| }) | |
| # Process general health knowledge | |
| general_answers = generate_general_health_answers() | |
| for category, questions in test_data.get("general_health_knowledge", {}).items(): | |
| for question in questions: | |
| answer = general_answers.get(question, generate_generic_answer(question, category)) | |
| qa_pairs.append({ | |
| "question": question, | |
| "answer": answer, | |
| "source": "Generated", | |
| "category": category | |
| }) | |
| return qa_pairs | |
| def generate_generic_answer(question, category): | |
| """Generate a generic but helpful answer based on question and category""" | |
| category_guidance = { | |
| "respiratory_and_ent": "For respiratory and ENT concerns, maintaining good hydration, using a humidifier, avoiding irritants like smoke, and getting adequate rest are important. If symptoms persist beyond 7-10 days, worsen, or are accompanied by high fever or difficulty breathing, consult a healthcare provider.", | |
| "skin_hair_and_allergies": "Skin and allergy issues often respond to gentle skincare, staying hydrated, avoiding known triggers, and using over-the-counter treatments. Persistent or worsening symptoms, signs of infection, or severe reactions warrant medical evaluation.", | |
| "mental_health_and_wellbeing": "Mental health is as important as physical health. Managing stress through regular exercise, adequate sleep, healthy eating, social connections, and relaxation techniques can help. Don't hesitate to seek professional support if you're struggling—therapy and counseling are valuable resources.", | |
| "womens_and_mens_health": "Hormonal and reproductive health concerns are common and often manageable. Maintaining a healthy lifestyle, managing stress, and regular check-ups are important. Don't hesitate to discuss concerns with a healthcare provider—these topics are important parts of overall health.", | |
| } | |
| return category_guidance.get(category, | |
| "This is a good question to discuss with a healthcare provider. They can provide personalized guidance based on your specific situation, medical history, and symptoms. In the meantime, maintaining a healthy lifestyle with adequate sleep, nutrition, hydration, and stress management supports overall wellbeing.") | |
| def generate_general_health_answers(): | |
| """Generate answers for general health knowledge questions""" | |
| return { | |
| "How much water should I drink daily?": | |
| "Most adults should aim for 8-10 cups (64-80 ounces) of water daily, but needs vary based on activity level, climate, and individual factors. A good indicator is urine color—pale yellow suggests adequate hydration. Increase intake during exercise, hot weather, or illness. Drink when thirsty and spread intake throughout the day.", | |
| "How many hours of sleep are healthy?": | |
| "Most adults need 7-9 hours of quality sleep per night. Teens need 8-10 hours, and younger children need more. Individual needs vary slightly. Prioritize consistent sleep schedule, good sleep hygiene (cool, dark, quiet room), and avoiding screens before bed. Quality matters as much as quantity.", | |
| "What are signs of dehydration?": | |
| "Signs of dehydration include: dark yellow urine, dry mouth and lips, feeling thirsty, headache, dizziness, fatigue, decreased urination, and dry skin. Severe dehydration causes confusion, rapid heartbeat, sunken eyes, and lack of urination. Mild dehydration responds to drinking water; severe cases require medical attention.", | |
| "How often should I exercise?": | |
| "Aim for at least 150 minutes of moderate aerobic activity (brisk walking) or 75 minutes of vigorous activity (running) per week, plus strength training twice weekly. This can be broken into 30 minutes, 5 days a week. Any movement is beneficial—start where you are and gradually increase. Consistency matters more than intensity.", | |
| "What is a balanced diet?": | |
| "A balanced diet includes: plenty of fruits and vegetables (half your plate), whole grains, lean proteins (fish, poultry, beans, nuts), healthy fats (olive oil, avocado, nuts), and limited processed foods, sugar, and sodium. Focus on variety, appropriate portions, and staying hydrated. Individual needs vary based on age, activity, and health conditions.", | |
| "How does smoking affect health?": | |
| "Smoking damages nearly every organ and increases risk of lung cancer, heart disease, stroke, COPD, and many other conditions. It reduces life expectancy by about 10 years on average. Secondhand smoke also harms others. Quitting at any age provides significant health benefits—lungs begin healing within weeks, and long-term disease risk decreases substantially. Resources like nicotine replacement and counseling improve quit success.", | |
| "What are the benefits of regular walking?": | |
| "Regular walking provides numerous benefits: improves cardiovascular health, helps maintain healthy weight, strengthens bones and muscles, boosts mood and mental health, reduces risk of chronic diseases (diabetes, heart disease), improves balance and coordination, and is low-impact and accessible. Aim for 30 minutes most days. Even short walks provide benefits.", | |
| "Is skipping meals bad for health?": | |
| "Regularly skipping meals, especially breakfast, can lead to: low energy, difficulty concentrating, overeating later, blood sugar fluctuations, slower metabolism, and nutrient deficiencies. It may also affect mood and stress levels. Eating regular, balanced meals helps maintain steady energy and supports overall health. If time is limited, choose quick, nutritious options over skipping.", | |
| "How does screen time affect health?": | |
| "Excessive screen time can cause: eye strain and dry eyes, disrupted sleep (especially before bed), poor posture leading to neck/back pain, reduced physical activity, and potential impacts on mental health. To minimize effects: follow 20-20-20 rule (every 20 minutes, look 20 feet away for 20 seconds), limit screens before bed, take regular breaks, maintain good posture, and balance with physical activity.", | |
| "Is sitting for long hours unhealthy?": | |
| "Yes, prolonged sitting increases risk of obesity, cardiovascular disease, diabetes, and mortality, even with regular exercise. Sitting reduces muscle activity and slows metabolism. Combat this by: taking standing/walking breaks every 30-60 minutes, using a standing desk, stretching regularly, exercising daily, and moving throughout the day. 'Movement snacks' help break up sitting time.", | |
| "What are easy habits for a healthier lifestyle?": | |
| "Simple healthy habits: drink water throughout the day, take short walking breaks, eat more vegetables, get 7-9 hours sleep, practice stress management (deep breathing, meditation), limit processed foods, connect with others socially, express gratitude, limit screen time before bed, and have regular health check-ups. Start with one or two habits and build gradually.", | |
| "Why are regular health checkups important?": | |
| "Regular check-ups allow early detection of health issues when they're most treatable, establish baseline health metrics, catch conditions before symptoms appear (high blood pressure, diabetes, high cholesterol), provide preventive care (vaccinations, screenings), and build a relationship with your healthcare provider. Frequency depends on age and risk factors, but annual check-ups are generally recommended.", | |
| "What vaccines are recommended for adults?": | |
| "Common adult vaccines include: annual flu shot, COVID-19 vaccine and boosters, Tdap (tetanus, diphtheria, pertussis) every 10 years, pneumonia vaccine (age 65+), shingles vaccine (age 50+), and HPV vaccine (up to age 26, sometimes 45). Travel may require additional vaccines. Specific recommendations depend on age, health conditions, and risk factors—consult your doctor.", | |
| "How can I boost my immune system naturally?": | |
| "Support your immune system by: getting adequate sleep (7-9 hours), eating a varied diet rich in fruits, vegetables, and whole foods, staying physically active, managing stress, maintaining healthy weight, not smoking, limiting alcohol, staying hydrated, practicing good hygiene (handwashing), and keeping up with vaccinations. No single food or supplement 'boosts' immunity significantly—overall lifestyle matters most.", | |
| "What are early warning signs of common illnesses?": | |
| "General warning signs include: persistent fatigue, unexplained weight changes, prolonged fever, changes in bathroom habits, unusual pain, skin changes (new moles, sores that don't heal), persistent cough or hoarseness, difficulty swallowing, unusual bleeding, changes in mental function, and symptoms that worsen or don't improve with typical treatment. When in doubt, consult a healthcare provider.", | |
| "How can I prevent lifestyle diseases?": | |
| "Prevent lifestyle diseases (heart disease, diabetes, stroke) by: maintaining healthy weight, eating a balanced diet low in processed foods, exercising regularly (150 minutes weekly), not smoking, limiting alcohol, managing stress, getting adequate sleep, controlling blood pressure and cholesterol, and having regular health screenings. These habits significantly reduce disease risk.", | |
| "How often should adults get health screenings?": | |
| "General guidelines: blood pressure check annually, cholesterol every 4-6 years (more often if high), diabetes screening every 3 years after age 45, cancer screenings (colonoscopy at 45, mammogram at 40-50, depending on guidelines), skin checks annually, and dental/eye exams regularly. Frequency varies based on age, family history, and risk factors. Discuss personal schedule with your doctor.", | |
| "What health tests should be done yearly?": | |
| "Annual tests typically include: blood pressure, BMI/weight, and depending on age/risk factors: cholesterol panel, blood glucose, complete blood count, thyroid function, and age-appropriate cancer screenings. Women may have pelvic exams and Pap smears. Men may have prostate checks after 50. Your doctor determines which tests you need based on your individual health profile." | |
| } | |
| def save_qa_pairs(qa_pairs): | |
| """Save generated Q&A pairs to the processed directory""" | |
| output_path = os.path.join( | |
| os.path.dirname(__file__), | |
| "datasets", | |
| "processed", | |
| "comprehensive_medical_qa.json" | |
| ) | |
| os.makedirs(os.path.dirname(output_path), exist_ok=True) | |
| with open(output_path, 'w') as f: | |
| json.dump(qa_pairs, f, indent=2) | |
| print(f"✓ Generated {len(qa_pairs)} Q&A pairs") | |
| print(f"✓ Saved to: {output_path}") | |
| # Also update the medquad_index.json to include all our data | |
| medquad_path = os.path.join( | |
| os.path.dirname(__file__), | |
| "datasets", | |
| "processed", | |
| "medquad_index.json" | |
| ) | |
| # Keep simpler format for medquad_index.json | |
| simplified_qa = [ | |
| { | |
| "question": qa["question"], | |
| "answer": qa["answer"], | |
| "source": qa["source"] | |
| } | |
| for qa in qa_pairs | |
| ] | |
| with open(medquad_path, 'w') as f: | |
| json.dump(simplified_qa, f, indent=2) | |
| print(f"✓ Updated medquad_index.json with {len(simplified_qa)} entries") | |
| if __name__ == "__main__": | |
| print("Generating comprehensive medical Q&A pairs...") | |
| qa_pairs = generate_qa_pairs() | |
| save_qa_pairs(qa_pairs) | |
| print("\n✓ Medical Q&A generation complete!") | |