Spaces:
Sleeping
Sleeping
File size: 12,460 Bytes
3e9e3df | 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 | """
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.
""") |