File size: 6,135 Bytes
a9de5f0
 
 
 
29b30f3
a9de5f0
 
 
 
 
29b30f3
 
a9de5f0
29b30f3
 
 
 
 
a9de5f0
29b30f3
 
 
 
a9de5f0
 
29b30f3
 
 
 
 
 
 
 
a9de5f0
 
 
 
29b30f3
a9de5f0
 
29b30f3
a9de5f0
29b30f3
 
 
 
 
a9de5f0
 
29b30f3
 
 
 
 
 
 
a9de5f0
29b30f3
 
a9de5f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0f2f4f
a9de5f0
 
 
 
 
 
 
 
 
d0f2f4f
 
 
 
e0eefc3
d0f2f4f
 
e0eefc3
 
d0f2f4f
 
 
e0eefc3
d0f2f4f
e0eefc3
d0f2f4f
 
a9de5f0
 
 
 
 
 
 
 
 
 
 
d0f2f4f
 
a9de5f0
d0f2f4f
 
e0eefc3
d0f2f4f
 
e0eefc3
d0f2f4f
 
 
 
e0eefc3
29b30f3
 
a9de5f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0f2f4f
 
 
 
 
 
a9de5f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0f2f4f
a9de5f0
 
 
 
 
29b30f3
 
 
 
 
 
a9de5f0
 
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
import gradio as gr
import json
import os
import logging
import requests

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Anthropic API key - can be set as HuggingFace secret or environment variable
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY", "")

# Check if API key is available
if ANTHROPIC_API_KEY:
    logger.info("Claude API key found")
else:
    logger.warning("Claude API key not found - using demo mode")

def call_claude_api(prompt):
    """Call Claude API directly"""
    if not ANTHROPIC_API_KEY:
        return "❌ Claude API key not configured. Please set ANTHROPIC_API_KEY environment variable."
    
    try:
        headers = {
            "Content-Type": "application/json",
            "x-api-key": ANTHROPIC_API_KEY,
            "anthropic-version": "2023-06-01"
        }
        
        data = {
            "model": "claude-3-5-sonnet-20241022",
            "max_tokens": 4096,
            "messages": [
                {
                    "role": "user",
                    "content": prompt
                }
            ]
        }
        
        response = requests.post(
            "https://api.anthropic.com/v1/messages",
            headers=headers,
            json=data,
            timeout=60
        )
        
        if response.status_code == 200:
            response_json = response.json()
            return response_json['content'][0]['text']
        else:
            logger.error(f"Claude API error: {response.status_code} - {response.text}")
            return f"❌ Claude API Error: {response.status_code}"
            
    except Exception as e:
        logger.error(f"Error calling Claude API: {str(e)}")
        return f"❌ Error: {str(e)}"

def process_file(file):
    """Process uploaded file"""
    if file is None:
        return "Please upload a file first."
    
    try:
        # Read file content
        with open(file.name, 'r', encoding='utf-8', errors='ignore') as f:
            content = f.read()
        
        if not content.strip():
            return "File appears to be empty."
            
        return content
    except Exception as e:
        return f"Error reading file: {str(e)}"

def analyze_transcript(file, age, gender, slp_notes):
    """Simple CASL analysis"""
    if file is None:
        return "Please upload a transcript file first."
    
    # Get transcript content
    transcript = process_file(file)
    if transcript.startswith("Error") or transcript.startswith("Please"):
        return transcript
    
    # Add SLP notes to the prompt if provided
    notes_section = ""
    if slp_notes and slp_notes.strip():
        notes_section = f"""
    
    SLP CLINICAL NOTES:
    {slp_notes.strip()}
    """
    
    # Simple analysis prompt
    prompt = f"""
    You are a speech-language pathologist analyzing a transcript for CASL assessment.
    
    Patient: {age}-year-old {gender}
    
    TRANSCRIPT:
    {transcript}{notes_section}
    
    Please provide a CASL analysis including:
    
    1. SPEECH FACTORS (with counts and severity):
    - Difficulty producing fluent speech
    - Word retrieval issues  
    - Grammatical errors
    - Repetitions and revisions
    
    2. CASL SKILLS ASSESSMENT:
    - Lexical/Semantic Skills (Standard Score, Percentile, Level)
    - Syntactic Skills (Standard Score, Percentile, Level)
    - Supralinguistic Skills (Standard Score, Percentile, Level)
    
    3. TREATMENT RECOMMENDATIONS:
    - List 3-5 specific intervention strategies
    
    4. CLINICAL SUMMARY:
    - Brief explanation of findings and prognosis
    
    Use exact quotes from the transcript as evidence.
    Provide realistic standard scores (70-130 range, mean=100).
    {f"Consider the SLP clinical notes in your analysis." if slp_notes and slp_notes.strip() else ""}
    """
    
    # Get analysis from Claude API
    result = call_claude_api(prompt)
    return result

# Create simple interface
with gr.Blocks(title="Simple CASL Analysis", theme=gr.themes.Soft()) as app:
    
    gr.Markdown("# πŸ—£οΈ Simple CASL Analysis Tool")
    gr.Markdown("Upload a speech transcript and get instant CASL assessment results.")
    
    with gr.Row():
        with gr.Column():
            gr.Markdown("### Upload & Settings")
            
            file_upload = gr.File(
                label="Upload Transcript File",
                file_types=[".txt", ".cha"]
            )
            
            age = gr.Number(
                label="Patient Age", 
                value=8, 
                minimum=1, 
                maximum=120
            )
            
            gender = gr.Radio(
                ["male", "female", "other"], 
                label="Gender", 
                value="male"
            )
            
            slp_notes = gr.Textbox(
                label="SLP Clinical Notes (Optional)",
                placeholder="Enter any additional clinical observations, context, or notes...",
                lines=3
            )
            
            analyze_btn = gr.Button(
                "πŸ” Analyze Transcript", 
                variant="primary"
            )
        
        with gr.Column():
            gr.Markdown("### Analysis Results")
            
            output = gr.Textbox(
                label="CASL Analysis Report",
                placeholder="Analysis results will appear here...",
                lines=25,
                max_lines=30
            )
    
    # Connect the analyze button
    analyze_btn.click(
        analyze_transcript,
        inputs=[file_upload, age, gender, slp_notes],
        outputs=[output]
    )

if __name__ == "__main__":
    print("πŸš€ Starting Simple CASL Analysis Tool...")
    if not ANTHROPIC_API_KEY:
        print("⚠️  ANTHROPIC_API_KEY not configured - analysis will show error message")
        print("   For HuggingFace Spaces: Add ANTHROPIC_API_KEY as a secret in your space settings")
        print("   For local use: export ANTHROPIC_API_KEY='your-key-here'")
    else:
        print("βœ… Claude API configured")
    
    app.launch(show_api=False)