#!/usr/bin/env python3 """ CASL Voice Bot - Speech Pathology Assistant Main application file that can be used for both local deployment and Hugging Face Spaces """ import os import asyncio import gradio as gr import logging import tempfile import queue import threading import time from dotenv import load_dotenv from openai import AsyncOpenAI # Load environment variables load_dotenv() # Set up logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Initialize OpenAI client with API key from environment openai_client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY")) # Speech Pathologist Agent Prompt SPEECH_PATHOLOGIST_PROMPT = """ You are a speech pathologist, a healthcare professional who specializes in evaluating, diagnosing, and treating communication disorders, including speech, language, cognitive-communication, voice, and fluency disorders. Your role is to help patients improve their speech and communication skills through various therapeutic techniques and exercises. Your are working with a student with speech impediments typically with ASD You have to be rigid to help them stay on the right track. YOu have to start with some sort of intro activity and can not rely on teh student at all to complete your thoughts. You pick a place to start and assess teh speech from there. Each domain from the CASL-2 framework can be analyzed using the sample: Lexical/Semantic Skills: This category focuses on vocabulary knowledge, word meanings, and the ability to use words contextually. It measures both receptive and expressive language abilities related to word use. Key Subtests: Antonyms: Identifying words with opposite meanings. Synonyms: Identifying words with similar meanings. Idiomatic Language: Understanding and interpreting idioms and figurative language. Evaluate vocabulary diversity (type-token ratio). Note word-finding difficulties, incorrect word choices, or over-reliance on fillers (e.g., "like," "stuff"). Assess use of specific vs. vague language (e.g., "car" vs. "sedan"). Syntactic Skills: This category evaluates understanding and use of grammar and sentence structure. It focuses on the ability to comprehend and produce grammatically correct sentences. Key Subtests: Sentence Expression: Producing grammatically correct sentences based on prompts. Grammaticality Judgment: Identifying whether a sentence is grammatically correct. Examine sentence structure for grammatical accuracy. Identify errors in verb tense, subject-verb agreement, or sentence complexity. Note the use of clauses, conjunctions, and varied sentence types. Supralinguistic Skills: This subcategory assesses higher-level language skills that go beyond literal meanings, such as understanding implied meanings, sarcasm, and complex verbal reasoning. Key Subtests: Inferences: Understanding information that is not explicitly stated. Meaning from Context: Deriving meaning from surrounding text or dialogue. Nonliteral Language: Interpreting figurative language, such as metaphors or irony Look for use or understanding of figurative language, idioms, or humor. Assess ability to handle ambiguous or implied meanings in context. Identify advanced language use for abstract or hypothetical ideas. Pragmatic Skills(focus less on this as it is not typically necessary for the age range you will be dealing with): This category measures the ability to use language effectively in social contexts. It evaluates understanding of conversational rules, turn-taking, and adapting communication to different social situations. Key Subtests: Pragmatic Language Test: Assessing appropriateness of responses in social scenarios. Begin by introducing yourself as a speech pathologist and start with a simple vocabulary assessment activity. Be encouraging but structured in your approach. """ # Custom audio processing for Gradio interface class AudioProcessor: def __init__(self): self.transcript = [] self.is_active = False self.voice_model = "shimmer" # Default voice self.notes = [] self.current_assessment = { "lexical_semantic": 0, "syntactic": 0, "supralinguistic": 0, "pragmatic": 0 } async def process_speech(self, audio_data, openai_client): """Process speech using OpenAI's API""" if not self.is_active or audio_data is None: return None, "\n".join(self.transcript), self.get_assessment_html() # Prepare audio file for OpenAI temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav") temp_file.close() try: # Save audio data to temporary file sample_rate, audio_array = audio_data import scipy.io.wavfile scipy.io.wavfile.write(temp_file.name, sample_rate, audio_array) # Transcribe audio using OpenAI with open(temp_file.name, "rb") as audio_file: transcript_response = await openai_client.audio.transcriptions.create( file=audio_file, model="whisper-1" ) user_text = transcript_response.text if user_text.strip(): self.transcript.append(f"Student: {user_text}") # Analyze speech for CASL-2 categories self.analyze_speech(user_text) # Generate assistant response chat_response = await openai_client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": SPEECH_PATHOLOGIST_PROMPT}, {"role": "user", "content": user_text} ] ) assistant_text = chat_response.choices[0].message.content self.transcript.append(f"Speech Pathologist: {assistant_text}") # Generate speech from text speech_response = await openai_client.audio.speech.create( model="tts-1", voice=self.voice_model, input=assistant_text ) # Save speech to temporary file response_temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") response_temp_file.close() speech_response.stream_to_file(response_temp_file.name) # Load audio data for Gradio import soundfile as sf audio_data, sample_rate = sf.read(response_temp_file.name) # Clean up os.unlink(response_temp_file.name) return (sample_rate, audio_data), "\n".join(self.transcript), self.get_assessment_html() except Exception as e: logger.error(f"Error processing speech: {e}") self.transcript.append(f"Error: {str(e)}") finally: # Clean up temp file os.unlink(temp_file.name) return None, "\n".join(self.transcript), self.get_assessment_html() def analyze_speech(self, text): """Analyze speech for CASL-2 categories""" # Simple heuristic analysis - in a real app, this would use more sophisticated NLP # Lexical/Semantic: check vocabulary diversity words = text.lower().split() unique_words = set(words) if len(unique_words) / max(1, len(words)) > 0.7: self.current_assessment["lexical_semantic"] += 1 self.notes.append("Lexical/Semantic: Good vocabulary diversity") # Syntactic: check for sentence complexity sentences = [s.strip() for s in text.replace("!", ".").replace("?", ".").split(".") if s.strip()] avg_words = sum(len(s.split()) for s in sentences) / max(1, len(sentences)) if avg_words > 7: self.current_assessment["syntactic"] += 1 self.notes.append("Syntactic: Complex sentence structures used") # Supralinguistic: check for figurative language (very basic check) figurative_markers = ["like", "as", "than", "seems", "appears", "metaphor", "imagine"] if any(marker in text.lower() for marker in figurative_markers): self.current_assessment["supralinguistic"] += 1 self.notes.append("Supralinguistic: Potential figurative language detected") # Pragmatic: basic check for conversational elements pragmatic_markers = ["hello", "hi", "thanks", "thank you", "please", "excuse me", "sorry"] if any(marker in text.lower() for marker in pragmatic_markers): self.current_assessment["pragmatic"] += 1 self.notes.append("Pragmatic: Appropriate social language detected") def get_assessment_html(self): """Get HTML representation of the current assessment""" html = """