File size: 5,538 Bytes
acaf471
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Simple API Test Script - Multilingual Pain Assessment System Demo
"""
import requests
import json

BASE_URL = "http://localhost:8000"


def test_health():
    """Check server health status"""
    try:
        response = requests.get(f"{BASE_URL}/health", timeout=5)
        print("βœ… Server is running")
        print(f"   Version: {response.json()['version']}")
        return True
    except requests.exceptions.ConnectionError:
        print("❌ Server not running")
        print("   Please start server: python Backend/main.py")
        return False
    except Exception as e:
        print(f"❌ Connection error: {e}")
        return False


def test_system_info():
    """Get system information"""
    print("\n" + "="*70)
    print("πŸ“Š System Information")
    print("="*70)
    
    try:
        response = requests.get(f"{BASE_URL}/api/system-info")
        data = response.json()
        
        if data["status"] == "success":
            info = data["system_info"]["pipeline_info"]
            print(f"Version: {info['pipeline_version']}")
            print(f"Architecture: {info['architecture']}")
            print(f"Supported Languages: {', '.join(info['supported_languages'])}")
            print(f"\nOntology Coverage:")
            print(f"  - Total: {info['ontology_coverage']['total_descriptors']} terms")
            print(f"  - Chinese: {info['ontology_coverage']['chinese_terms']}")
            print(f"  - Korean: {info['ontology_coverage']['korean_terms']}")
            print(f"  - Spanish: {info['ontology_coverage']['spanish_terms']}")
            print(f"  - Hmong: {info['ontology_coverage']['hmong_terms']}")
    except Exception as e:
        print(f"❌ Failed to get system info: {e}")


def test_analysis(language_name, text):
    """Test pain analysis"""
    print("\n" + "="*70)
    print(f"🌐 Testing {language_name}")
    print("="*70)
    print(f"Input: {text}")
    
    try:
        response = requests.post(
            f"{BASE_URL}/api/analyze-text-neuro-symbolic",
            json={"text": text},
            timeout=30
        )
        
        result = response.json()
        
        if result["status"] == "success":
            print("\nβœ… Analysis succeeded!")
            
            # Display structured data
            data = result["structured_data"]
            print(f"\nπŸ“‹ Structured Data:")
            print(f"  Pain Type: {data['pain_type']}")
            print(f"  Location: {data['location']}")
            print(f"  Temporal Pattern: {data['temporal_pattern']}")
            print(f"  Intensity: {data['intensity']}")
            if data['emotion']:
                print(f"  Emotion: {data['emotion']}")
            
            # Display ontology mappings
            if result["ontology_mapping_trace"]:
                print(f"\nπŸ”„ Ontology Mappings ({len(result['ontology_mapping_trace'])} items):")
                for mapping in result["ontology_mapping_trace"]:
                    lang_code = mapping.get('detected_language', '?')
                    print(f"  - [{lang_code}] {mapping['original_term']} β†’ "
                          f"{mapping['mapped_english']} ({mapping.get('pain_type', 'N/A')})")
            
            # Display clinical recommendations
            if result["clinical_recommendations"]:
                print(f"\nπŸ’Š Clinical Recommendations ({len(result['clinical_recommendations'])} items):")
                for i, rec in enumerate(result["clinical_recommendations"], 1):
                    print(f"\n  {i}. {rec['recommendation'][:100]}...")
                    print(f"     Rule: {rec['triggered_by_rule']}")
                    print(f"     Evidence: {rec['evidence']}")
            else:
                print("\nπŸ’Š Clinical Recommendations: Standard assessment recommended")
            
            return True
        else:
            print(f"\n❌ Analysis failed: {result.get('message')}")
            return False
            
    except requests.exceptions.Timeout:
        print("\n❌ Request timeout (OpenAI API might be slow)")
        return False
    except Exception as e:
        print(f"\n❌ Error: {e}")
        import traceback
        traceback.print_exc()
        return False


def main():
    """Main test function"""
    print("="*70)
    print("πŸš€ Multilingual Pain Assessment System - API Test")
    print("="*70)
    
    # 1. Check server
    if not test_health():
        return
    
    # 2. Get system info
    test_system_info()
    
    # 3. Test different languages
    test_cases = [
        {
            "name": "Chinese πŸ‡¨πŸ‡³",
            "text": "ζˆ‘ζœ‰η«θΎ£θΎ£ηš„η–Όη—›οΌŒε·²η»ε₯½ε‡ δΈͺζœˆδΊ†οΌŒθ…°ιƒ¨εΎˆιšΎε—"
        },
        {
            "name": "Korean πŸ‡°πŸ‡·",
            "text": "ν—ˆλ¦¬κ°€ 따끔거리듯이 μ•„ν”„λ‹€"
        },
        {
            "name": "Spanish πŸ‡ͺπŸ‡Έ",
            "text": "Tengo un dolor agudo y punzante en la espalda"
        },
        {
            "name": "Hmong",
            "text": "Kuv mob Kub Heev heev"
        }
    ]
    
    passed = 0
    total = len(test_cases)
    
    for test_case in test_cases:
        if test_analysis(test_case["name"], test_case["text"]):
            passed += 1
    
    # Summary
    print("\n" + "="*70)
    print("πŸ“Š Test Summary")
    print("="*70)
    print(f"Passed: {passed}/{total}")
    
    if passed == total:
        print("βœ… All tests passed!")
    else:
        print(f"⚠️  {total - passed} test(s) failed")


if __name__ == "__main__":
    main()