Homoeopathy-Bot / components /ui_elements.py
yekkala's picture
Create components/ui_elements.py
3e9e3df verified
"""
Custom UI components for the homeopathic analyzer
"""
import streamlit as st
from typing import Dict, List, Callable
def render_header():
"""Render application header"""
st.set_page_config(
page_title="Homeopathic Symptom Analyzer",
page_icon="🌿",
layout="wide"
)
col1, col2 = st.columns([1, 4])
with col1:
st.image("🌿", width=80)
with col2:
st.title("Homeopathic Symptom Analyzer AI")
st.markdown("### Advanced Symptom Analysis & Remedy Matching")
st.markdown("---")
def render_sidebar() -> Dict:
"""Render sidebar with configuration options"""
with st.sidebar:
st.header("βš™οΈ Analysis Settings")
# Search options
st.subheader("Search Options")
search_web = st.checkbox("Search Web Resources", value=False,
help="Include web-based homeopathic resources")
search_docs = st.checkbox("Search Internal Documents", value=True,
help="Search in uploaded documents")
# Analysis depth
st.subheader("Analysis Depth")
analysis_level = st.select_slider(
"Analysis Detail",
options=["Basic", "Standard", "Comprehensive", "Deep"],
value="Comprehensive"
)
# Upload documents
st.subheader("πŸ“ Document Upload")
uploaded_files = st.file_uploader(
"Upload medical documents (PDF, DOCX, TXT)",
type=['pdf', 'docx', 'txt'],
accept_multiple_files=True
)
# Agent intelligence settings
st.subheader("πŸ€– AI Agent Settings")
agent_intelligence = st.select_slider(
"Agent Intelligence Level",
options=["Basic", "Intelligent", "Advanced", "Expert"],
value="Intelligent",
help="Higher levels provide more detailed reasoning"
)
return {
'search_web': search_web,
'search_docs': search_docs,
'analysis_level': analysis_level,
'uploaded_files': uploaded_files,
'agent_intelligence': agent_intelligence
}
def render_case_sheet_form() -> Dict:
"""Render comprehensive case sheet form"""
st.markdown("## πŸ“‹ Patient Case Sheet")
with st.form("case_sheet_form"):
# Patient information
col1, col2 = st.columns(2)
with col1:
age = st.number_input("Age", min_value=0, max_value=120, value=30)
gender = st.selectbox("Gender", ["Male", "Female", "Other"])
with col2:
occupation = st.text_input("Occupation")
constitution = st.selectbox("Constitution Type",
["Lean", "Stout", "Average", "Not Sure"])
# Main complaint
st.subheader("Chief Complaint")
main_complaint = st.text_area(
"Describe your main health issue in detail",
height=100,
placeholder="Example: Severe headache on right side with throbbing pain..."
)
# Symptom details
st.subheader("Symptom Details")
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("**Location**")
location = st.multiselect(
"Where are symptoms located?",
["Head", "Stomach", "Chest", "Back", "Limbs", "Joints", "General"]
)
with col2:
st.markdown("**Sensation**")
sensation = st.multiselect(
"What does it feel like?",
["Burning", "Throbbing", "Stabbing", "Aching", "Pressing", "Numbness"]
)
with col3:
st.markdown("**Intensity**")
intensity = st.slider("Pain/Symptom Intensity", 1, 10, 5)
# Modalities
st.subheader("Modalities")
col1, col2 = st.columns(2)
with col1:
aggravations = st.text_area(
"What makes it worse?",
placeholder="Example: Motion, heat, noise, after eating..."
)
with col2:
ameliorations = st.text_area(
"What makes it better?",
placeholder="Example: Rest, pressure, cold applications..."
)
# Time factors
st.subheader("Timing")
timing = st.text_area(
"When do symptoms occur or change?",
placeholder="Example: Worse in morning, better in evening, periodic every week..."
)
# Emotional state
st.subheader("Emotional & Mental State")
emotional_state = st.text_area(
"Describe emotional state, fears, anxieties",
placeholder="Example: Anxious about health, irritable, fear of crowds..."
)
# Generalities
st.subheader("General Symptoms")
generalities = st.text_area(
"Other symptoms, food desires/aversions, thermal preferences",
placeholder="Example: Thirst for cold water, aversion to fat, chilly..."
)
# Submit button
submit_button = st.form_submit_button("πŸš€ Analyze Symptoms")
if submit_button:
return {
'age': age,
'gender': gender,
'occupation': occupation,
'constitution': constitution,
'main_complaint': main_complaint,
'location': location,
'sensation': sensation,
'intensity': intensity,
'aggravations': aggravations,
'ameliorations': ameliorations,
'timing': timing,
'emotional_state': emotional_state,
'generalities': generalities
}
return None
def render_remedy_results(results: List[Dict], analysis: Dict):
"""Render remedy matching results with detailed analysis"""
st.markdown("## πŸ” Analysis Results")
# Summary card
with st.expander("πŸ“Š Analysis Summary", expanded=True):
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Key Symptoms Identified", len(analysis.get('key_symptoms', [])))
with col2:
st.metric("SRP Symptoms", len(analysis.get('strange_rare_peculiar', [])))
with col3:
st.metric("Top Match Score", f"{results[0]['score']:.1f}%" if results else "N/A")
# Display each remedy result
for i, result in enumerate(results[:5], 1):
with st.expander(f"πŸ† #{i}: {result['remedy']} ({result['score']:.1f}% Match)", expanded=i==1):
# Header with match score
col1, col2 = st.columns([3, 1])
with col1:
st.subheader(result['remedy'])
st.caption(result['data']['description'])
with col2:
st.metric("Match Score", f"{result['score']:.1f}%")
# Tabs for different analyses
tab1, tab2, tab3, tab4 = st.tabs(["Physical", "Modalities", "Constitutional", "Analysis"])
with tab1:
st.markdown("### Physical Symptoms")
for keynote in result['data']['keynotes']:
st.markdown(f"β€’ {keynote}")
with tab2:
st.markdown("### Modalities")
col1, col2 = st.columns(2)
with col1:
st.markdown("**Aggravations:**")
for agg in result['data']['modalities']['aggravations']:
st.markdown(f"β€’ {agg}")
with col2:
st.markdown("**Ameliorations:**")
for amel in result['data']['modalities']['ameliorations']:
st.markdown(f"β€’ {amel}")
# Modality match analysis
if result['modality_match']['reasoning']:
st.markdown("**Modality Match Analysis:**")
for reason in result['modality_match']['reasoning']:
st.success(f"βœ“ {reason}")
with tab3:
st.markdown("### Constitutional Profile")
st.info(result['data']['constitutional'])
st.markdown("### Emotional Profile")
st.info(result['data']['emotional'])
with tab4:
st.markdown("### Detailed Analysis")
st.markdown(result['detailed_analysis'])
# Reasoning section
st.markdown("#### Reasoning for Selection")
st.markdown("""
1. **Symptom Correspondence**: Key symptoms match remedy picture
2. **Modality Alignment**: Aggravations/ameliorations correspond
3. **Constitutional Fit**: Patient profile matches remedy type
4. **Emotional Match**: Mental/emotional state aligns
""")
st.divider()
def render_agent_intelligence(analysis: Dict, settings: Dict):
"""Render AI agent's intelligent analysis"""
st.markdown("## πŸ€– AI Agent Analysis")
with st.chat_message("assistant", avatar="πŸ€–"):
st.markdown("### Intelligent Symptom Analysis")
# Generate intelligent analysis based on settings
intelligence_level = settings.get('agent_intelligence', 'Intelligent')
analysis_text = f"""
Based on my analysis ({intelligence_level} mode), here's my assessment:
**Primary Analysis:**
- **Chief Complaint**: {analysis.get('physical_symptoms', [{}])[0].get('description', 'Not specified') if analysis.get('physical_symptoms') else 'Not specified'}
- **Key Modalities**: {', '.join(analysis.get('modalities', {}).get('aggravations', [])[:3]) if analysis.get('modalities', {}).get('aggravations') else 'Not specified'}
- **Emotional State**: {', '.join(analysis.get('emotional_state', {}).get('primary_emotions', [])) if analysis.get('emotional_state', {}).get('primary_emotions') else 'Not specified'}
**Pattern Recognition:**
"""
if intelligence_level in ["Advanced", "Expert"]:
analysis_text += """
- Detected potential miasmatic influence based on symptom patterns
- Noticed characteristic symptom combinations suggesting specific remedy families
- Identified paradoxical symptoms that are highly characteristic
"""
else:
analysis_text += """
- Symptoms suggest acute inflammatory process
- Modalities indicate thermal preferences
- Emotional state aligns with common remedy pictures
"""
analysis_text += f"""
**Recommendation Approach:**
Based on the {intelligence_level} analysis, I'm considering:
1. Matching physical symptoms with modalities
2. Aligning constitutional factors
3. Considering emotional/mental state
4. Evaluating time factors and periodicity
**Next Steps:**
Consider consultation with a qualified homeopath for:
- Potency selection
- Repetition schedule
- Constitutional follow-up
"""
st.markdown(analysis_text)
def render_document_search_results(search_results: List[Dict]):
"""Render document search results"""
if search_results:
st.markdown("## πŸ“š Document Search Results")
for result in search_results:
with st.expander(f"πŸ“„ {result['document']}"):
st.markdown(f"**Match**: `{result['match']}`")
st.markdown(f"**Context**: {result['context']}")
st.caption(f"Relevance: {result['relevance']:.2f}")
else:
st.info("No matches found in uploaded documents.")
def render_disclaimer():
"""Render medical disclaimer"""
st.markdown("---")
st.warning("""
**IMPORTANT DISCLAIMER**: This application is for educational and informational purposes only.
It is not a substitute for professional medical advice, diagnosis, or treatment.
Always consult a qualified homeopath or medical professional for health concerns.
""")