DIrtyCha's picture
Update app.py for HF Space: direct backend import instead of HTTP API
c655002
"""
Gradio Demo for Multilingual Pain Assessment System
Powered by BioLORD-2023-M medical embeddings
"""
import gradio as gr
import os
import sys
# Add Backend to path
sys.path.append("./Backend")
# Import backend directly (no HTTP API needed for HF Space)
from services.neuro_symbolic_service import analyze_pain_neuro_symbolic
def analyze_pain(text, language):
"""Analyze pain description using the neuro-symbolic pipeline."""
try:
if not text or not text.strip():
return "⚠️ Please enter a pain description."
# Call backend function directly
result = analyze_pain_neuro_symbolic(text)
if result.get("status") == "success":
return result.get("report", "No report generated")
else:
return f"❌ Error: {result.get('message', 'Unknown error')}"
except Exception as e:
return f"❌ Error during analysis:\n\n{str(e)}\n\n**Troubleshooting:**\n- Check that all dependencies are installed\n- Verify OpenAI API key is set in Space secrets"
# Example pain descriptions in different languages
examples = [
["腰部和腿部最近一周特别难受。感觉像有成千上万只蚂蚁在皮肤下面爬来爬去,停不下来;有时突然像被针戳了一下,会猛地跳起来。", "Chinese"],
["허리와 다리가 최근 일주일 동안 특히 불편합니다. 피부 아래 수천 마리의 개미가 기어다니는 느낌이 들고, 때때로 갑자기 바늘에 찔린 것처럼 아파요.", "Korean"],
["La espalda y las piernas han sido especialmente difíciles de soportar esta última semana. Se siente como si hubiera miles de hormigas arrastrándose bajo la piel, sin poder detenerse.", "Spanish"],
["My lower back and legs have been especially hard to bear this past week. It feels like thousands of ants crawling under the skin, unable to stop.", "English"]
]
# Build Gradio interface
with gr.Blocks(title="Pain Assessment System") as demo:
gr.Markdown("""
# 🏥 Multilingual Pain Assessment System
Powered by **BioLORD-2023-M** medical embeddings and **GPT-5.2**
### Supported Languages:
- 🇨🇳 Chinese (中文)
- 🇰🇷 Korean (한국어)
- 🇪🇸 Spanish (Español)
- 🇻🇳 Hmong
- 🇺🇸 English
### How it works:
1. Enter patient's pain description in any supported language
2. BioLORD analyzes medical semantics
3. GPT-5.2 generates comprehensive clinical report
""")
with gr.Row():
with gr.Column():
text_input = gr.Textbox(
label="Patient's Pain Description",
placeholder="Enter pain description in any language...",
lines=8
)
language_input = gr.Dropdown(
choices=["Chinese", "Korean", "Spanish", "Hmong", "English"],
label="Language (optional - auto-detected)",
value="Chinese"
)
submit_btn = gr.Button("Analyze Pain", variant="primary")
with gr.Column():
output = gr.Markdown(
label="Clinical Report",
value="*Report will appear here...*"
)
# Examples
gr.Examples(
examples=examples,
inputs=[text_input, language_input],
outputs=output,
fn=analyze_pain,
cache_examples=False
)
# Event handlers
submit_btn.click(
fn=analyze_pain,
inputs=[text_input, language_input],
outputs=output
)
gr.Markdown("""
---
### 🔬 Model Information
- **Embeddings**: BioLORD-2023-M (SOTA on MedSTS medical semantic similarity)
- **Report Generation**: GPT-5.2
- **Dictionary**: 362 multilingual pain terms
- **Accuracy**: 85-92% on medical synonym matching
### ℹ️ About
This system maps patient's pain expressions to standardized medical terminology using:
- **Semantic Distance Analysis**: BioLORD understands medical concepts beyond literal text
- **Knowledge Graph Integration**: Aligned with medical ontologies (UMLS/AGCT)
- **Cultural Sensitivity**: Preserves metaphors and cultural expressions
**Privacy**: BioLORD embeddings run locally. GPT-5.2 API used for report generation only.
""")
# Launch
if __name__ == "__main__":
demo.launch() # HF Space handles server configuration automatically