import re import streamlit as st import google.generativeai as genai import os from google.api_core import exceptions def call_homeo_ai(prompt): try: # Configure using your primary secret key genai.configure(api_key=st.secrets["GOOGLE_API_KEY"]) model = genai.GenerativeModel('gemini-1.5-flash') # Make the request response = model.generate_content(prompt) return response.text except exceptions.ResourceExhausted: # This specific error triggers when the API key limit (Quota) is hit st.error("⚠️ **System Busy:** The free daily limit for the AI has been reached.") st.info("To continue right now, you can enter your own API key in the sidebar, or please try again in a few hours.") return None except Exception as e: # Catches other issues like internet connection or server errors st.error(f"An unexpected error occurred: {e}") return None import plotly.express as px import pandas as pd from datetime import datetime # --- 1. ACCESS CONTROL & SECRETS --- GOOGLE_API_KEY = st.secrets["GOOGLE_API_KEY"] VALID_KEYS = st.secrets["VALID_KEYS"] def check_access(): if "authenticated" not in st.session_state: st.session_state.authenticated = False if not st.session_state.authenticated: st.title("🔐 HomeopathPro AI Login") license_key = st.text_input("Enter License Key:", type="password") if st.button("Unlock"): if license_key in VALID_KEYS: st.session_state.authenticated = True st.rerun() else: st.error("Invalid Key.") st.stop() check_access() # --- 2. CONFIGURATION & AI SETUP --- genai.configure(api_key=GOOGLE_API_KEY) safety_settings = [ {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"}, {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"}, {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"}, {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"}, ] # KEEPING YOUR MODEL EXACTLY THE SAME model = genai.GenerativeModel('gemini-2.5-flash', safety_settings=safety_settings) st.set_page_config(page_title="HomeopathPro AI", page_icon="🌿", layout="wide") # --- 3. MOBILE FRIENDLY UI STYLING --- st.markdown(""" """, unsafe_allow_html=True) # --- 4. DYNAMIC DATA TRACKING --- if "patient_count" not in st.session_state: st.session_state.patient_count = 48 if "repertory_results" not in st.session_state: st.session_state.repertory_results = "" if "mm_results" not in st.session_state: st.session_state.mm_results = "" if "consultation_results" not in st.session_state: st.session_state.consultation_results = "" # --- 5. SIDEBAR NAVIGATION --- # 1. Get the key from user input with st.sidebar: custom_key = st.text_input("🔑 Use your own Gemini API Key", type="password") # 2. Decide which key to use: User's key first, then the Secret key if custom_key: active_api_key = custom_key else: active_api_key = st.secrets["GOOGLE_API_KEY"] # 3. Configure the AI with the active key if active_api_key: genai.configure(api_key=active_api_key) st.markdown("## 🌿 HomeopathPro AI") # Larger radio buttons for mobile tapping menu = st.radio("MAIN MENU", ["🏠 Dashboard", "👨‍⚕️ Consultation", "📚 Repertory", "📖 Materia Medica"]) st.divider() st.success("Doctor: Chetan") phone_number = "919922275487" message = "Hi Dr. Chetan, I'm interested in the HomeopathPro AI subscription." whatsapp_url = f"https://wa.me/{phone_number}?text={message.replace(' ', '%20')}" st.sidebar.markdown("---") st.sidebar.write("### 📞 Support & Subscriptions") st.sidebar.link_button("Contact Admin on WhatsApp", whatsapp_url) st.title("Settings") custom_key = st.text_input("🔑 Use your own Gemini API Key (Optional)", type="password") if custom_key: # Override the secret key with the user's provided key os.environ["GOOGLE_API_KEY"] = custom_key st.success("Using your custom API key!") st.markdown("## 🌿 Settings") # Add this language selector target_lang = st.selectbox( "Select Result Language", ["English", "Marathi", "Hindi", "Gujarati", "Bengali", "Kannada", "Tamil", "Telugu", "Punjabi", "Malayalam", "Spanish", "French", "German", "Arabic", "Portuguese"] ) st.divider() # --- 6. DASHBOARD & GUIDE --- if menu == "🏠 Dashboard": st.title("📊 Practice Guide") # Section 1: About the AI st.markdown("""

About HomeopathPro AI

This is an advanced clinical assistant designed to bridge classical homeopathy with modern Sensation and Synergy methods. It assists in repertorization, materia medica study, and deep case analysis.

""", unsafe_allow_html=True) st.divider() # Section 2: YouTube Video Guide st.subheader("🎬 Video Tutorial & User Guide") # REPLACE the URL below with your actual YouTube link st.video("https://www.youtube.com/watch?v=your_video_id") st.divider() # Section 3: Professional Instructions st.subheader("📝 How to Use HomeopathPro AI") col1, col2 = st.columns(2) with col1: st.info(""" **1. Clinical Consultation** * Input patient details and totality of symptoms. * AI analyzes Kingdom, Miasm, and Differential Diagnosis. **2. Rubric Repertory** * Use for specific rubric selection from multiple repertories. * Ideal for finding rare or 'small' remedies. """) with col2: st.success(""" **3. Materia Medica Explorer** * Deep dive into remedy keynotes and modern provings. * View core delusions and psychological themes. **4. Expert Support** * Use the sidebar WhatsApp link for subscription or technical help. """) # --- 7. CONSULTATION --- elif menu == "👨‍⚕️ Consultation": st.title("👨‍⚕️ Clinical Consultation") # Import the speech-to-text component locally to save resources from streamlit_mic_recorder import speech_to_text with st.container(): st.markdown('
', unsafe_allow_html=True) # Mapping your target_lang to ISO language codes for the Mic lang_codes = { "English": "en", "Marathi": "mr", "Hindi": "hi", "Gujarati": "gu", "Bengali": "bn", "Kannada": "kn", "Tamil": "ta", "Telugu": "te", "Punjabi": "pa", "Malayalam": "ml", "Spanish": "es", "French": "fr", "German": "de", "Arabic": "ar", "Portuguese": "pt" } current_lang_code = lang_codes.get(target_lang, "en") st.markdown(f"### 🎙️ Voice Case Taking ({target_lang})") # Voice input component text_from_mic = speech_to_text( language=current_lang_code, start_prompt=f"Click to speak in {target_lang}...", stop_prompt="Stop recording", key='speech_input' ) # Populate the text area with mic results if available if text_from_mic: patient_desc = st.text_area("Chief Complaint & Totality:", value=text_from_mic, height=150) else: patient_desc = st.text_area("Chief Complaint & Totality:", height=150) c1, c2 = st.columns(2) with c1: p_age = st.number_input("Age", 0, 120) with c2: p_gen = st.selectbox("Gender", ["Male", "Female", "Other"]) if st.button("Generate & Log Analysis"): if patient_desc.strip(): with st.spinner("Analyzing case..."): try: prompt = f""" ### 🧠 SYSTEM ROLE You are the world's most advanced **Homeopathic AI Consultant**, a Master Clinician and Senior Repertory Analyst trained in the **Synergy Method**. Your expertise must seamlessly integrate: - **Repertory (Logic)** - **Materia Medica (Facts)** - **Sensation Method (Spirit/Source)** - Clinical Homeopathic Philosophy Your task is to deliver a **precise, clinically reliable, and deeply individualized homeopathic analysis** suitable for expert practitioners. --- ### 📋 CASE CONTEXT - **Patient Profile**: {p_age} years old | {p_gen} - **Totality of Symptoms**: {patient_desc if menu == "👨‍⚕️ Consultation" else search_q} - **Language Requirement**: Output strictly in **{target_lang}** --- # 🧭 PRE-ANALYSIS: CASE CLASSIFICATION ### Case Nature Detection Classify automatically: - **Acute** - **Chronic** - **Acute on Chronic** - **Miasmatic Crisis** Provide 1-line justification. --- also add more detail about inside introduction section 🚀 **Want to Master in Homeopathy?** 🎓 Strengthen your BHMS & Homeopathy preparation with expert-designed courses: 👉 https://www.medicinoz.in/s/store/courses/BHMS 📚 Get high-yield quick notes for **Any Remedy** here: 👉 https://www.medicinoz.com ✨ Study deeper. Prescribe better. --- # 🔬 PHASE 1: REPERTORIAL ANALYSIS (THE LOGIC) ### 1. Intelligent Rubric Mapping - Convert the case into **8–10 high-quality rubrics** - Use sources: **Synthesis, Complete, Murphy’s** - Include: - Mental generals - Physical generals - Particular symptoms - Modern clinical/pathological rubrics when relevant ⚠️ Avoid: - Duplicate rubrics - Pathology-only rubrics unless characteristic - Over-general symptoms --- ### 2. Clinical Weighting (MANDATORY) Assign **Intensity Weight (1–4)**: - **4** = PQRS / keynote / highly characteristic - **3** = strong general - **2** = supportive symptom - **1** = common pathology ### 3. Repertorial Spreadsheet Generate a Markdown table for the **Top 5 Remedies**. **Grading Rule:** - Grade 3 = Bold remedy - Grade 2 = Italic remedy - Grade 1 = Plain remedy - 0 = absent | Rubric (Grade 1–3) | Weight | Rem 1 | Rem 2 | Rem 3 | Rem 4 | Rem 5 | | :--- | :---: | :---: | :---: | :---: | :---: | :---: | | [Rubric Name] | [W] | [G] | [G] | [G] | [G] | [G] | | **Coverage Count** | - | [X/10] | [X/10] | [X/10] | [X/10] | [X/10] | | **Total Weighted Score** | - | [Sum] | [Sum] | [Sum] | [Sum] | [Sum] | --- # 🌿 PHASE 2: THE SYNERGY SYNTHESIS (THE SOUL) ### 1. Source Analysis Identify clearly: - **Kingdom** (Mineral / Plant / Animal) - **Sub-kingdom logic** - Explain WHY the case fits this kingdom pattern --- ### 2. The Vital Sensation Provide the **core sensation/delusion** of the leading remedy. Use blockquote format: > “Core dynamic sensation…” Explain in clear Sensation Method language. --- ### 3. Core Essence (Top 3 Remedies) For the **top three remedies**, briefly describe: - Central theme - Mental state - Characteristic physical expression - Clinical keynote --- ### 4. Miasmatic Mapping Determine the dominant pace: - Psoric - Sycotic - Tubercular - Syphilitic Provide clinical justification. --- ### 5. Differential Diagnosis (DD) Provide a **sharp side-by-side comparison** of the top **two remedies**, highlighting: - Key differentiating mental traits - Physical generals - Modalities - Clinical pearls This section must help a physician confidently choose. --- ### ⭐ Small Remedy Spotlight If a **lesser-known but strongly fitting remedy** appears, briefly justify its relevance. --- # 💊 PHASE 3: TREATMENT ARCHITECTURE (THE PLAN) ### 1. 🎯 Final Simillimum State the single **best indicated remedy** in **bold**, Provide: - One-line essence match - Remedy Confidence Score (0–100%) Confidence logic: - ≥85% = High certainty - 70–84% = Moderate - 50–69% = Tentative - <50% = Low --- ## 2. ⚗️ Precision Posology (SMART) Individualize based on: - Acute vs chronic - Sensitivity level - Mental pathology depth - Vitality estimate Provide: - Suggested potency (30C / 200C / 1M / LM) - Repetition schedule - When to wait - When to redose - Aggravation management - Case sensitivity considerations --- ### 3. 🔄 Hering’s Law Forecast Specify what the physician should monitor: - Early signs to watch - Direction of cure - Possible initial aggravation - Warning signs requiring review Be specific and clinically useful. --- # ❓ FOLLOW-UP QUESTION GENERATOR Generate **3–5 high-yield follow-up questions** that would help confirm or refine the prescription. Focus on: - PQRS confirmation - Remedy differentiation - Miasmatic depth - Obstacles to cure --- # 🧾 OUTPUT RULES (MANDATORY) - ALL headings and text must be in **{target_lang}** - Use **bold** for remedy names - Use **blockquotes** for Vital Sensation - Maintain a **professional, authoritative, clinician-level tone** - Avoid fluff — prioritize clinical precision - Ensure internal consistency between repertory and final remedy - Think step-by-step before concluding --- ### ✅ QUALITY CHECK (INTERNAL — DO NOT DISPLAY) Before finalizing, silently verify: - Rubrics truly reflect the case - Weighting is logical - Remedy scores match Materia Medica - Final simillimum matches the totality - Posology fits case sensitivity Only then produce the final answer. """ response = model.generate_content(prompt) st.session_state.consultation_results = response.text st.session_state.patient_count += 1 st.success("Analysis Logged!") except Exception as e: st.error(f"Error: {e}") if st.session_state.consultation_results: st.markdown("---") st.write(st.session_state.consultation_results) st.markdown('
', unsafe_allow_html=True) # --- 8. REPERTORY --- elif menu == "📚 Repertory": st.title("📚 Rubric Selection") search_q = st.text_input("Enter totality:") if st.button("Analyze Rubrics"): if search_q.strip(): with st.spinner("Analyzing..."): try: query = f""" ### **PROMPT START** Act as an Elite Homeopathic Consultant and Repertory Expert. Your task is to perform a Multi-Repertory Analysis for the following case: {search_q} --- also add more detail about inside introduction section 📢 **Upgrade Your Homeopathic Mastery** 🎓 Explore premium BHMS & Homeopathy courses on Medicinoz to strengthen your clinical and exam preparation: 👉 https://www.medicinoz.in/s/store/courses/BHMS 📚 For quick revision notes of this remedy, visit: 👉 https://www.medicinoz.com ✨ Learn smart. Prescribe confidently. --- ### **Analysis Requirements:** ## 1️⃣ Integrated Rubric Selection (Synthesis, Complete, Murphy, Knerr):** - Identify the 6-8 most characteristic rubrics. ### Rubric Balance (MANDATORY): - 🧠 Mental / Emotional Generals → 2–3 rubrics - 🌡️ Physical Generals → 1–2 rubrics - 🫁 Particular / Local Symptoms → 2–3 rubrics - 🧬 Pathological / Clinical / Modern Rubric → at least 1 ### Rubric Quality Rules: - Prefer **strange, rare, and peculiar (SRP)** symptoms - Avoid common/pathognomonic rubrics unless highly characteristic - Include **modern diagnostic rubrics** where clinically relevant - Ensure rubrics reflect the **individualizing totality**, not just diagnosis ### Repertory Sources Priority: Use and cross-verify from: - **S** = Synthesis - **C** = Complete Repertory - **M** = Murphy - **K** = Knerr --- ## 2️⃣ 📊 The Repertorial Spreadsheet (Markdown Table):** Create a professional repertory table. ### Table Rules: - **Rows:** Selected Rubrics - **Columns:** Top 5 Remedies (ranked by totality) - **Grading System (STRICT):** - **3** = Grade 3 (Bold) - *2* = Grade 2 (Italic) - 1 = Grade 1 (Plain) ### Additional Requirements: - Add **Source column** (S/C/M/K strongest reference) - Maintain grading accuracy - Remedies must show **organ affinity** to the chief complaint - Prefer remedies appearing across multiple rubrics --- ## 3️⃣ 🔎 Cross-Referencing & Refinement ### A. Near-Miss Confirmation Rubrics Suggest **3 high-value confirmation rubrics** that the clinician should verify with the patient. For each rubric: - Briefly explain **why it differentiates the leading remedies** ### B. Small Remedy Intelligence 🧪 Identify **1–2 small/rare remedies** (e.g., nosodes, rare minerals, sarcodes) that: - Strongly cover the pathological sphere - Might be overlooked in routine repertorization - Have meaningful keynote correspondence Explain briefly **when they would outperform the polychrests**. --- ## 4️⃣ 🏆 The Final Totality (Simillimum Analysis) ### A. Remedy Differentiation Provide: - The **leading remedy** - 1–2 close competitors - Key differentiating points ### B. Core Essence (Highly Important) Define the **core dynamic state** of the winning remedy in THIS case context: - Mental theme - Physical expression - Miasmatic background (if inferable) --- ## 5️⃣ 💊 Potency & Posology Strategy Based on: - Pace of disease - Depth of pathology - Suspected miasm - Patient vitality (if inferable) Recommend: - ⚖️ C-scale vs LM-scale - Suggested starting potency - Repetition strategy - Clinical cautions --- # 🚨 QUALITY GUARDRAILS ✅ Follow classical homeopathic philosophy ✅ Avoid over-reliance on pathology alone ✅ Ensure remedy-organ affinity ✅ Prefer individualized symptoms over diagnosis ✅ Maintain professional clinical tone ✅ Do NOT invent rubrics that don't exist in major repertories ✅ Clearly state when data is insufficient --- ### **Output Constraints:** - **Language:** Everything (headers, rubrics, analysis) must be in {target_lang}. - **Tone:** Professional, clinical, and objective. - **Accuracy:** Ensure the remedies selected have a proven affinity for the primary organ involved. ### **PROMPT END** """ response = model.generate_content(query) st.session_state.repertory_results = response.text except Exception as e: st.error(f"Error: {e}") if st.session_state.repertory_results: st.write(st.session_state.repertory_results) # --- 9. MATERIA MEDICA --- elif menu == "📖 Materia Medica": st.title("📖 Remedy Explorer") rem = st.text_input("Search Remedy Name:") if st.button("Explore Keynotes"): if rem.strip(): with st.spinner(f"Fetching {rem}..."): try: resp = model.generate_content(f""" Provide a comprehensive Materia Medica profile for {rem} by synthesizing: Act as an **International-level Classical Homeopath, Materia Medica Historian, and Remedy Theorist**. Your task is to produce a **deep, cross-verified, clinically reliable Materia Medica profile** for: - **REMEDY:** {rem} --- ## 🎯 OBJECTIVE Construct a **high-precision living portrait of the remedy** by synthesizing: - Classical Materia Medica authorities - Modern thematic schools - Clinical experience - Toxicological science - Core psychological dynamics The final output must help an experienced homeopath **recognize, differentiate, and confidently prescribe** the remedy. --- also add more detail about inside introduction section 🎯 **Serious About Homeopathy?** If you want crystal-clear concepts, exam-focused preparation, and clinical confidence: 🎓 Join Medicinoz BHMS Courses: 👉 https://www.medicinoz.in/s/store/courses/BHMS 📚 Quick revision notes for **{rem}**: 👉 https://www.medicinoz.com 🚀 Your shortcut to Homeopathic excellence starts here. --- # 🔬 ANALYSIS FRAMEWORK --- ## 1️⃣ Classical Materia Medica Foundation 📖 Synthesize confirmed characteristics from the following **primary authorities**: ### 🔹 Foundational Masters - Hahnemann (Chronic Diseases, Materia Medica Pura) - Hering (Guiding Symptoms) - Allen (Encyclopedia of Pure Materia Medica) ### 🔹 Classical Clinical Masters - Kent (Lectures on Materia Medica) - Nash (Leaders in Homeopathic Therapeutics) - Clarke (Dictionary of Practical Materia Medica) - Boericke (Pocket Materia Medica) - Farrington (Clinical Materia Medica) - Boger-Boenninghausen (Synoptic Key) ### Include: - Guiding/keynote symptoms - Characteristic generals - Modalities (agg. & amel.) - Mental and emotional state (classical language) - Verified clinical spheres Prioritize **repeatedly confirmed symptoms** across authors. --- ## 2️⃣ Modern Thematic & Contemporary Insights 🧩 Integrate insights from: - Vermeulen (Synoptic Materia Medica) - Scholten (Periodic Table / Element theory - if mineral) - Sankaran (Sensation Method) - Mangialavori (systemic themes, if applicable) - Rajan Sankaran miasmatic model (where appropriate) ### Include: - Kingdom classification - Miasmatic tendency (with confidence level) - Sensation pattern - Reaction pattern (active/passive/compensatory) - Structural/theme keywords Clearly label **modern interpretation vs classical fact**. --- ## 3️⃣ Physical Pathologies & Organ Affinity 🫁 Provide clinically grounded mapping. ### Include: - Primary organ affinity - Tissue affinity - System involvement - Pathological tendencies - Modern clinical indications - Acute vs chronic sphere Ensure **pathology-remedy authenticity** Highlight strong clinical confirmations --- ## 4️⃣ Toxicology, Pharmacology & Provings ⚗️ Explain the biological and proving basis. ### Include: - Source substance nature - Natural history (plant/mineral/animal origin) - Known toxic effects in crude form - Correlation between toxicity and proving symptoms - Key historical proving notes - Any known pharmacological actions (if established) Maintain scientific sobriety Avoid speculative molecular claims --- ## 5️⃣ Core Delusion / Central Feeling Define the **central disturbance of the remedy**. ### Include: - Core delusion or perception - Fundamental survival theme - Emotional posture toward environment - Typical compensation pattern - Characteristic fears or sensitivities This section should allow **rapid remedy recognition**. --- ## 6️⃣ Remedy Differentiation 🔍 Compare with **2-4 closely related remedies**. Focus on: - Mental distinctions - Modalities that separate - Key generals - Clinical differentiation pearls --- ## 7️⃣ Clinical Pearls & Prescribing Guidance 💡 Provide practical expert tips: - Best prescribing situations - Potency tendencies (general guidance) - Acute vs chronic use - Remedy relationships: - Complementary - Inimical - Antidotes (if well established) - Common prescribing pitfalls --- # 🧾 OUTPUT REQUIREMENTS ## Language **Write EVERYTHING in:** {target_lang} Use **professional medical and classical homeopathic terminology appropriate to {target_lang}.** --- ## Tone - Scholarly but clinically practical - Structured with clear headings - High authority voice - No filler content --- # 🚨 QUALITY GUARDRAILS - Do NOT invent symptoms - Cross-verify across major authors - Clearly separate classical vs modern ideas - Maintain remedy integrity - Flag weak or controversial areas - Prefer characteristic over common symptoms - Ensure organ affinity accuracy --- # 📌 MANDATORY FINAL SECTION ## 📚 Source Perspective Note At the end, briefly clarify: - Which features are strongly supported by classical masters - Which arise mainly from modern thematic schools - Any disagreements between authorities - Confidence level of the overall remedy picture --- **END GOAL:** Produce a gold-standard Materia Medica synthesis suitable for advanced practitioners and academic study. **PROMPT END** """) st.session_state.mm_results = resp.text except Exception as e: st.error(f"Error: {e}") if st.session_state.mm_results: st.markdown("---") st.write(st.session_state.mm_results)