import gradio as gr import requests import json import os # Get HF token from environment variable HF_TOKEN = os.getenv("HF_TOKEN") def get_medical_response(symptoms, medical_history): """ Get medical AI response using Hugging Face Inference API """ if not HF_TOKEN: return "❌ Error: HF_TOKEN not found. Please set up your Hugging Face token." if not symptoms.strip(): return "⚠️ Please enter some symptoms to get a medical consultation." # Create the prompt prompt = f"""Medical Consultation Request: Symptoms: {symptoms} Medical History: {medical_history if medical_history else "No medical history provided"} Please provide helpful medical information including: 1. Possible conditions to consider 2. Recommended next steps 3. When to seek immediate medical attention 4. General health advice Note: This is for informational purposes only.""" try: # Use text-generation model that's more reliable API_URL = "https://api-inference.huggingface.co/models/microsoft/DialoGPT-large" headers = { "Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json", } payload = { "inputs": prompt, "parameters": { "max_new_tokens": 400, "temperature": 0.7, "top_p": 0.9, "do_sample": True, "return_full_text": False } } response = requests.post(API_URL, headers=headers, json=payload, timeout=30) if response.status_code == 200: result = response.json() # Handle different response formats if isinstance(result, list) and len(result) > 0: ai_response = result[0].get("generated_text", "") elif isinstance(result, dict) and "generated_text" in result: ai_response = result["generated_text"] else: # Fallback: provide structured medical advice ai_response = generate_medical_advice(symptoms, medical_history) # Add disclaimer disclaimer = "\n\n⚠️ **Medical Disclaimer**: This information is for educational purposes only. Always consult with qualified healthcare professionals for proper medical diagnosis and treatment." return ai_response + disclaimer elif response.status_code == 503: return "❌ Model is currently loading. Please try again in a few minutes." else: # Fallback to structured response return generate_medical_advice(symptoms, medical_history) except requests.exceptions.Timeout: return "❌ Request timed out. Please try again." except requests.exceptions.RequestException as e: return generate_medical_advice(symptoms, medical_history) except Exception as e: return generate_medical_advice(symptoms, medical_history) def generate_medical_advice(symptoms, medical_history): """ Generate structured medical advice as fallback """ response = f"""# Medical Information for Your Symptoms **Symptoms**: {symptoms} **Medical History**: {medical_history if medical_history else "None provided"} ## General Recommendations: ### 1. **Immediate Steps** - Monitor your symptoms closely - Stay hydrated and get adequate rest - Keep a symptom diary noting when symptoms occur and their severity ### 2. **When to Seek Medical Attention** - If symptoms worsen or persist for more than a few days - If you experience severe pain, difficulty breathing, or high fever - If you have concerns about your symptoms given your medical history ### 3. **General Health Advice** - Maintain a healthy diet and regular exercise routine - Get adequate sleep (7-9 hours per night) - Manage stress through relaxation techniques - Stay up to date with preventive care and screenings ### 4. **Next Steps** - **Mild symptoms**: Monitor for 24-48 hours - **Moderate symptoms**: Consider contacting your healthcare provider - **Severe symptoms**: Seek immediate medical attention ## Important Notes: - This is general health information only - Individual cases vary significantly - Your healthcare provider knows your medical history best - Don't delay seeking professional help if you're concerned ⚠️ **Medical Disclaimer**: This information is for educational purposes only. Always consult with qualified healthcare professionals for proper medical diagnosis and treatment.""" return response # Create the Gradio interface with gr.Blocks(title="Medical AI Assistant", theme=gr.themes.Soft()) as demo: gr.Markdown(""" # 🏥 Medical AI Assistant Get AI-powered medical information based on your symptoms. This tool provides general health information and guidance. **⚠️ Important**: This is NOT a substitute for professional medical advice. Always consult healthcare professionals for proper diagnosis and treatment. """) with gr.Row(): with gr.Column(): symptoms_input = gr.Textbox( label="Describe your symptoms", placeholder="E.g., I have a headache, fever, and feel tired...", lines=4, max_lines=8 ) history_input = gr.Textbox( label="Medical history (optional)", placeholder="E.g., diabetes, allergies, medications...", lines=2, max_lines=4 ) submit_btn = gr.Button("Get Medical Information", variant="primary") clear_btn = gr.Button("Clear", variant="secondary") with gr.Column(): output = gr.Textbox( label="Medical AI Response", lines=15, max_lines=20, show_copy_button=True ) # Examples gr.Examples( examples=[ ["I have a persistent cough and shortness of breath", "No significant medical history"], ["Severe headache with nausea and sensitivity to light", "Migraine history"], ["Chest pain and dizziness during exercise", "High blood pressure"], ["Persistent fatigue and joint pain", "Autoimmune conditions in family"], ], inputs=[symptoms_input, history_input], label="Example consultations" ) # Event handlers submit_btn.click( fn=get_medical_response, inputs=[symptoms_input, history_input], outputs=output ) clear_btn.click( lambda: ("", "", ""), outputs=[symptoms_input, history_input, output] ) # Footer gr.Markdown(""" --- **Disclaimer**: This Medical AI Assistant provides general health information for educational purposes only. It should not be used as a substitute for professional medical advice, diagnosis, or treatment. Always seek the advice of your physician or other qualified health provider with any questions you may have regarding a medical condition. """) # Launch the app if __name__ == "__main__": demo.launch()