Spaces:
Running
Running
File size: 5,612 Bytes
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 |
import gradio as gr
import boto3
import json
import os
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# AWS credentials
AWS_ACCESS_KEY = os.getenv("AWS_ACCESS_KEY", "")
AWS_SECRET_KEY = os.getenv("AWS_SECRET_KEY", "")
AWS_REGION = os.getenv("AWS_REGION", "us-east-1")
# Initialize Bedrock client
bedrock_client = None
if AWS_ACCESS_KEY and AWS_SECRET_KEY:
try:
bedrock_client = boto3.client(
'bedrock-runtime',
aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_SECRET_KEY,
region_name=AWS_REGION
)
logger.info("Bedrock client initialized successfully")
except Exception as e:
logger.error(f"Failed to initialize AWS Bedrock client: {str(e)}")
def call_bedrock(prompt):
"""Call AWS Bedrock API with correct format"""
if not bedrock_client:
return "β AWS Bedrock not configured. Please set AWS credentials."
try:
body = json.dumps({
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 4096,
"top_k": 250,
"stop_sequences": [],
"temperature": 0.3,
"top_p": 0.9,
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": prompt
}
]
}
]
})
response = bedrock_client.invoke_model(
body=body,
modelId='anthropic.claude-3-5-sonnet-20240620-v1:0',
accept='application/json',
contentType='application/json'
)
response_body = json.loads(response.get('body').read())
return response_body['content'][0]['text']
except Exception as e:
logger.error(f"Error calling Bedrock: {str(e)}")
return f"β Error calling Bedrock: {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):
"""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
# Simple analysis prompt
prompt = f"""
You are a speech-language pathologist analyzing a transcript for CASL assessment.
Patient: {age}-year-old {gender}
TRANSCRIPT:
{transcript}
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).
"""
# Get analysis from Bedrock
result = call_bedrock(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"
)
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],
outputs=[output]
)
if __name__ == "__main__":
print("π Starting Simple CASL Analysis Tool...")
if not bedrock_client:
print("β οΈ AWS credentials not configured - analysis will show error message")
app.launch(show_api=False) |