Update app.py
Browse files
app.py
CHANGED
|
@@ -6,49 +6,109 @@ import logging
|
|
| 6 |
import traceback
|
| 7 |
from pathlib import Path
|
| 8 |
|
| 9 |
-
# Import your pipeline modules
|
| 10 |
-
try:
|
| 11 |
-
from utils_audio import convert_to_wav
|
| 12 |
-
from to_cha import to_cha_from_wav
|
| 13 |
-
from cha_json import cha_to_json_file
|
| 14 |
-
from output import predict_from_chajson
|
| 15 |
-
except ImportError as e:
|
| 16 |
-
logging.error(f"Import error: {e}")
|
| 17 |
-
# Fallback imports or error handling
|
| 18 |
-
|
| 19 |
# Set up logging
|
| 20 |
logging.basicConfig(level=logging.INFO)
|
| 21 |
logger = logging.getLogger(__name__)
|
| 22 |
|
| 23 |
-
# Configuration
|
| 24 |
-
MODEL_DIR = ".
|
| 25 |
SUPPORTED_AUDIO_FORMATS = [".mp3", ".mp4", ".wav", ".m4a", ".flac", ".ogg"]
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
def run_complete_pipeline(audio_file_path: str) -> dict:
|
| 28 |
-
"""
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
try:
|
| 32 |
logger.info(f"Starting pipeline for: {audio_file_path}")
|
| 33 |
|
| 34 |
# Step 1: Convert to WAV
|
| 35 |
logger.info("Step 1: Converting audio to WAV...")
|
| 36 |
-
wav_path = convert_to_wav(audio_file_path, sr=16000, mono=True)
|
| 37 |
logger.info(f"WAV conversion completed: {wav_path}")
|
| 38 |
|
| 39 |
# Step 2: Generate CHA file using Batchalign
|
| 40 |
logger.info("Step 2: Generating CHA file...")
|
| 41 |
-
cha_path = to_cha_from_wav(wav_path, lang="eng")
|
| 42 |
logger.info(f"CHA generation completed: {cha_path}")
|
| 43 |
|
| 44 |
# Step 3: Convert CHA to JSON
|
| 45 |
logger.info("Step 3: Converting CHA to JSON...")
|
| 46 |
-
chajson_path, json_data = cha_to_json_file(cha_path)
|
| 47 |
logger.info(f"JSON conversion completed: {chajson_path}")
|
| 48 |
|
| 49 |
# Step 4: Run aphasia classification
|
| 50 |
logger.info("Step 4: Running aphasia classification...")
|
| 51 |
-
results = predict_from_chajson(MODEL_DIR, chajson_path, output_file=None)
|
| 52 |
logger.info("Classification completed")
|
| 53 |
|
| 54 |
# Cleanup temporary files
|
|
@@ -75,82 +135,44 @@ def run_complete_pipeline(audio_file_path: str) -> dict:
|
|
| 75 |
}
|
| 76 |
|
| 77 |
def process_audio_input(audio_file):
|
| 78 |
-
"""
|
| 79 |
-
Process audio file and return formatted results
|
| 80 |
-
"""
|
| 81 |
try:
|
| 82 |
if audio_file is None:
|
| 83 |
-
return
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
""
|
| 89 |
-
)
|
| 90 |
|
| 91 |
# Check file format
|
| 92 |
file_path = audio_file
|
| 93 |
-
if
|
| 94 |
-
file_path = audio_file
|
| 95 |
-
else:
|
| 96 |
-
# Handle Gradio file object
|
| 97 |
-
file_path = audio_file.name if hasattr(audio_file, 'name') else str(audio_file)
|
| 98 |
|
| 99 |
file_ext = Path(file_path).suffix.lower()
|
| 100 |
if file_ext not in SUPPORTED_AUDIO_FORMATS:
|
| 101 |
-
return (
|
| 102 |
-
f"❌ Error: Unsupported file format {file_ext}",
|
| 103 |
-
f"Supported formats: {', '.join(SUPPORTED_AUDIO_FORMATS)}",
|
| 104 |
-
"",
|
| 105 |
-
"",
|
| 106 |
-
""
|
| 107 |
-
)
|
| 108 |
|
| 109 |
# Run the complete pipeline
|
| 110 |
pipeline_result = run_complete_pipeline(file_path)
|
| 111 |
|
| 112 |
if not pipeline_result["success"]:
|
| 113 |
-
return (
|
| 114 |
-
f"❌ Pipeline Error: {pipeline_result['message']}",
|
| 115 |
-
pipeline_result.get('error', ''),
|
| 116 |
-
"",
|
| 117 |
-
"",
|
| 118 |
-
""
|
| 119 |
-
)
|
| 120 |
|
| 121 |
-
#
|
| 122 |
results = pipeline_result["results"]
|
| 123 |
|
| 124 |
-
# Format main prediction
|
| 125 |
if "predictions" in results and len(results["predictions"]) > 0:
|
| 126 |
first_pred = results["predictions"][0]
|
| 127 |
|
| 128 |
if "error" in first_pred:
|
| 129 |
-
return
|
| 130 |
-
f"❌ Classification Error: {first_pred['error']}",
|
| 131 |
-
"",
|
| 132 |
-
"",
|
| 133 |
-
"",
|
| 134 |
-
""
|
| 135 |
-
)
|
| 136 |
|
| 137 |
-
#
|
| 138 |
predicted_class = first_pred["prediction"]["predicted_class"]
|
| 139 |
confidence = first_pred["prediction"]["confidence_percentage"]
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
main_result = f"🧠 **Predicted Aphasia Type:** {predicted_class}\n"
|
| 143 |
-
main_result += f"📊 **Confidence:** {confidence}\n"
|
| 144 |
-
main_result += f"📋 **Description:** {class_description}"
|
| 145 |
-
|
| 146 |
-
# Detailed analysis
|
| 147 |
-
features = first_pred["class_description"].get("features", [])
|
| 148 |
-
detailed_analysis = f"**Key Features:**\n"
|
| 149 |
-
for feature in features:
|
| 150 |
-
detailed_analysis += f"• {feature}\n"
|
| 151 |
-
|
| 152 |
-
detailed_analysis += f"\n**Clinical Description:**\n"
|
| 153 |
-
detailed_analysis += first_pred["class_description"].get("description", "No description available")
|
| 154 |
|
| 155 |
# Additional metrics
|
| 156 |
additional_info = first_pred["additional_predictions"]
|
|
@@ -158,65 +180,55 @@ def process_audio_input(audio_file):
|
|
| 158 |
fluency_score = additional_info["fluency_score"]
|
| 159 |
fluency_rating = additional_info["fluency_rating"]
|
| 160 |
|
| 161 |
-
|
| 162 |
-
additional_metrics += f"**Fluency Score:** {fluency_score:.3f} ({fluency_rating})\n"
|
| 163 |
-
|
| 164 |
-
# Probability distribution (top 3)
|
| 165 |
prob_dist = first_pred["probability_distribution"]
|
| 166 |
top_3 = list(prob_dist.items())[:3]
|
| 167 |
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
for i, (aphasia_type, info) in enumerate(top_3, 1):
|
| 170 |
-
|
| 171 |
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
-
return
|
| 180 |
-
main_result,
|
| 181 |
-
detailed_analysis,
|
| 182 |
-
additional_metrics,
|
| 183 |
-
probability_breakdown,
|
| 184 |
-
summary_text
|
| 185 |
-
)
|
| 186 |
|
| 187 |
else:
|
| 188 |
-
return
|
| 189 |
-
"❌ No predictions generated",
|
| 190 |
-
"The audio file may not contain analyzable speech",
|
| 191 |
-
"",
|
| 192 |
-
"",
|
| 193 |
-
""
|
| 194 |
-
)
|
| 195 |
|
| 196 |
except Exception as e:
|
| 197 |
logger.error(f"Processing error: {str(e)}")
|
| 198 |
logger.error(traceback.format_exc())
|
| 199 |
-
return (
|
| 200 |
-
f"❌ Processing Error: {str(e)}",
|
| 201 |
-
"Please check the logs for more details",
|
| 202 |
-
"",
|
| 203 |
-
"",
|
| 204 |
-
""
|
| 205 |
-
)
|
| 206 |
|
| 207 |
def process_text_input(text_input):
|
| 208 |
-
"""
|
| 209 |
-
Process text input directly (fallback option)
|
| 210 |
-
"""
|
| 211 |
try:
|
| 212 |
if not text_input or not text_input.strip():
|
| 213 |
-
return
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
""
|
| 219 |
-
)
|
| 220 |
|
| 221 |
# Create a simple JSON structure for text-only input
|
| 222 |
temp_json = {
|
|
@@ -243,7 +255,7 @@ def process_text_input(text_input):
|
|
| 243 |
temp_json_path = f.name
|
| 244 |
|
| 245 |
# Run prediction
|
| 246 |
-
results = predict_from_chajson(MODEL_DIR, temp_json_path, output_file=None)
|
| 247 |
|
| 248 |
# Cleanup
|
| 249 |
try:
|
|
@@ -251,227 +263,134 @@ def process_text_input(text_input):
|
|
| 251 |
except:
|
| 252 |
pass
|
| 253 |
|
| 254 |
-
# Format results
|
| 255 |
if "predictions" in results and len(results["predictions"]) > 0:
|
| 256 |
first_pred = results["predictions"][0]
|
| 257 |
|
| 258 |
predicted_class = first_pred["prediction"]["predicted_class"]
|
| 259 |
confidence = first_pred["prediction"]["confidence_percentage"]
|
|
|
|
|
|
|
|
|
|
| 260 |
|
| 261 |
-
return
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
else:
|
| 269 |
-
return
|
| 270 |
-
"❌ No predictions generated",
|
| 271 |
-
"",
|
| 272 |
-
"",
|
| 273 |
-
"",
|
| 274 |
-
""
|
| 275 |
-
)
|
| 276 |
|
| 277 |
except Exception as e:
|
| 278 |
logger.error(f"Text processing error: {str(e)}")
|
| 279 |
-
return (
|
| 280 |
-
f"❌ Error: {str(e)}",
|
| 281 |
-
"",
|
| 282 |
-
"",
|
| 283 |
-
"",
|
| 284 |
-
""
|
| 285 |
-
)
|
| 286 |
|
| 287 |
-
# Create Gradio interface
|
| 288 |
def create_interface():
|
| 289 |
-
"""Create
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
.
|
| 298 |
-
""
|
| 299 |
-
|
|
|
|
|
|
|
| 300 |
|
| 301 |
-
# Header
|
| 302 |
gr.HTML("""
|
| 303 |
-
<div
|
| 304 |
<h1>🧠 Advanced Aphasia Classification System</h1>
|
| 305 |
-
<p>Upload audio files
|
| 306 |
</div>
|
| 307 |
""")
|
| 308 |
|
|
|
|
|
|
|
| 309 |
with gr.Tabs():
|
| 310 |
-
# Audio
|
| 311 |
-
with gr.
|
| 312 |
gr.Markdown("### Upload Audio File")
|
| 313 |
-
gr.Markdown("Supported formats: MP3, MP4, WAV, M4A, FLAC, OGG")
|
| 314 |
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
)
|
| 328 |
-
|
| 329 |
-
gr.Markdown("**Note:** Processing may take 1-3 minutes depending on audio length")
|
| 330 |
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
label="🎯 Primary Classification",
|
| 337 |
-
lines=3,
|
| 338 |
-
interactive=False
|
| 339 |
-
)
|
| 340 |
-
|
| 341 |
-
with gr.Row():
|
| 342 |
-
audio_detailed = gr.Textbox(
|
| 343 |
-
label="📋 Detailed Analysis",
|
| 344 |
-
lines=6,
|
| 345 |
-
interactive=False
|
| 346 |
-
)
|
| 347 |
-
|
| 348 |
-
audio_metrics = gr.Textbox(
|
| 349 |
-
label="📈 Additional Metrics",
|
| 350 |
-
lines=6,
|
| 351 |
-
interactive=False
|
| 352 |
-
)
|
| 353 |
-
|
| 354 |
-
with gr.Row():
|
| 355 |
-
audio_probabilities = gr.Textbox(
|
| 356 |
-
label="📊 Probability Breakdown",
|
| 357 |
-
lines=4,
|
| 358 |
-
interactive=False
|
| 359 |
-
)
|
| 360 |
-
|
| 361 |
-
audio_summary = gr.Textbox(
|
| 362 |
-
label="📝 Processing Summary",
|
| 363 |
-
lines=4,
|
| 364 |
-
interactive=False
|
| 365 |
-
)
|
| 366 |
|
| 367 |
-
# Text
|
| 368 |
-
with gr.
|
| 369 |
gr.Markdown("### Direct Text Input")
|
| 370 |
-
gr.Markdown("
|
| 371 |
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
lines=5
|
| 378 |
-
)
|
| 379 |
-
|
| 380 |
-
process_text_btn = gr.Button(
|
| 381 |
-
"🔍 Analyze Text",
|
| 382 |
-
variant="secondary",
|
| 383 |
-
size="lg"
|
| 384 |
-
)
|
| 385 |
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
lines=4,
|
| 400 |
-
interactive=False
|
| 401 |
-
)
|
| 402 |
-
|
| 403 |
-
text_metrics = gr.Textbox(
|
| 404 |
-
label="📈 Metrics",
|
| 405 |
-
lines=4,
|
| 406 |
-
interactive=False
|
| 407 |
-
)
|
| 408 |
-
|
| 409 |
-
with gr.Row():
|
| 410 |
-
text_probabilities = gr.Textbox(
|
| 411 |
-
label="📊 Assessment",
|
| 412 |
-
lines=2,
|
| 413 |
-
interactive=False
|
| 414 |
-
)
|
| 415 |
-
|
| 416 |
-
text_summary = gr.Textbox(
|
| 417 |
-
label="📝 Status",
|
| 418 |
-
lines=2,
|
| 419 |
-
interactive=False
|
| 420 |
-
)
|
| 421 |
-
|
| 422 |
-
# Event handlers
|
| 423 |
-
process_audio_btn.click(
|
| 424 |
-
fn=process_audio_input,
|
| 425 |
-
inputs=[audio_input],
|
| 426 |
-
outputs=[
|
| 427 |
-
audio_main_result,
|
| 428 |
-
audio_detailed,
|
| 429 |
-
audio_metrics,
|
| 430 |
-
audio_probabilities,
|
| 431 |
-
audio_summary
|
| 432 |
-
]
|
| 433 |
-
)
|
| 434 |
-
|
| 435 |
-
process_text_btn.click(
|
| 436 |
-
fn=process_text_input,
|
| 437 |
-
inputs=[text_input],
|
| 438 |
-
outputs=[
|
| 439 |
-
text_main_result,
|
| 440 |
-
text_detailed,
|
| 441 |
-
text_metrics,
|
| 442 |
-
text_probabilities,
|
| 443 |
-
text_summary
|
| 444 |
-
]
|
| 445 |
-
)
|
| 446 |
|
| 447 |
-
# Footer
|
| 448 |
gr.HTML("""
|
| 449 |
<div style="text-align: center; margin-top: 2rem; padding: 1rem; border-top: 1px solid #eee;">
|
| 450 |
-
<p><strong>About:</strong> This system uses advanced NLP and acoustic analysis to classify different types of aphasia
|
| 451 |
<p><em>For research and clinical assessment purposes.</em></p>
|
| 452 |
</div>
|
| 453 |
""")
|
| 454 |
|
| 455 |
return demo
|
| 456 |
|
| 457 |
-
# Launch the application
|
| 458 |
if __name__ == "__main__":
|
| 459 |
try:
|
| 460 |
logger.info("Starting Aphasia Classification System...")
|
| 461 |
|
| 462 |
-
# Check if model directory exists
|
| 463 |
-
if not os.path.exists(MODEL_DIR):
|
| 464 |
-
logger.error(f"Model directory not found: {MODEL_DIR}")
|
| 465 |
-
print(f"❌ Error: Model directory not found: {MODEL_DIR}")
|
| 466 |
-
print("Please ensure your trained model is in the correct directory.")
|
| 467 |
-
|
| 468 |
# Create and launch interface
|
| 469 |
demo = create_interface()
|
| 470 |
demo.launch(
|
| 471 |
server_name="0.0.0.0",
|
| 472 |
server_port=7860,
|
| 473 |
-
|
| 474 |
-
|
| 475 |
)
|
| 476 |
|
| 477 |
except Exception as e:
|
|
|
|
| 6 |
import traceback
|
| 7 |
from pathlib import Path
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
# Set up logging
|
| 10 |
logging.basicConfig(level=logging.INFO)
|
| 11 |
logger = logging.getLogger(__name__)
|
| 12 |
|
| 13 |
+
# Configuration - Use current directory for model files
|
| 14 |
+
MODEL_DIR = "." # Changed from "./adaptive_aphasia_model"
|
| 15 |
SUPPORTED_AUDIO_FORMATS = [".mp3", ".mp4", ".wav", ".m4a", ".flac", ".ogg"]
|
| 16 |
|
| 17 |
+
def safe_import_modules():
|
| 18 |
+
"""Safely import pipeline modules with error handling"""
|
| 19 |
+
modules = {}
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
from utils_audio import convert_to_wav
|
| 23 |
+
modules['convert_to_wav'] = convert_to_wav
|
| 24 |
+
logger.info("✓ utils_audio imported successfully")
|
| 25 |
+
except Exception as e:
|
| 26 |
+
logger.error(f"✗ Failed to import utils_audio: {e}")
|
| 27 |
+
modules['convert_to_wav'] = None
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
from to_cha import to_cha_from_wav
|
| 31 |
+
modules['to_cha_from_wav'] = to_cha_from_wav
|
| 32 |
+
logger.info("✓ to_cha imported successfully")
|
| 33 |
+
except Exception as e:
|
| 34 |
+
logger.error(f"✗ Failed to import to_cha: {e}")
|
| 35 |
+
modules['to_cha_from_wav'] = None
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
from cha_json import cha_to_json_file
|
| 39 |
+
modules['cha_to_json_file'] = cha_to_json_file
|
| 40 |
+
logger.info("✓ cha_json imported successfully")
|
| 41 |
+
except Exception as e:
|
| 42 |
+
logger.error(f"✗ Failed to import cha_json: {e}")
|
| 43 |
+
modules['cha_to_json_file'] = None
|
| 44 |
+
|
| 45 |
+
try:
|
| 46 |
+
from output import predict_from_chajson
|
| 47 |
+
modules['predict_from_chajson'] = predict_from_chajson
|
| 48 |
+
logger.info("✓ output imported successfully")
|
| 49 |
+
except Exception as e:
|
| 50 |
+
logger.error(f"✗ Failed to import output: {e}")
|
| 51 |
+
modules['predict_from_chajson'] = None
|
| 52 |
+
|
| 53 |
+
return modules
|
| 54 |
+
|
| 55 |
+
# Import modules
|
| 56 |
+
MODULES = safe_import_modules()
|
| 57 |
+
|
| 58 |
+
def check_model_files():
|
| 59 |
+
"""Check if required model files exist"""
|
| 60 |
+
required_files = [
|
| 61 |
+
"pytorch_model.bin",
|
| 62 |
+
"config.json",
|
| 63 |
+
"tokenizer.json",
|
| 64 |
+
"tokenizer_config.json"
|
| 65 |
+
]
|
| 66 |
+
|
| 67 |
+
missing_files = []
|
| 68 |
+
for file in required_files:
|
| 69 |
+
if not os.path.exists(os.path.join(MODEL_DIR, file)):
|
| 70 |
+
missing_files.append(file)
|
| 71 |
+
|
| 72 |
+
if missing_files:
|
| 73 |
+
logger.error(f"Missing model files: {missing_files}")
|
| 74 |
+
return False, missing_files
|
| 75 |
+
|
| 76 |
+
logger.info("✓ All required model files found")
|
| 77 |
+
return True, []
|
| 78 |
+
|
| 79 |
def run_complete_pipeline(audio_file_path: str) -> dict:
|
| 80 |
+
"""Complete pipeline: Audio → WAV → CHA → JSON → Model Prediction"""
|
| 81 |
+
|
| 82 |
+
# Check if all modules are available
|
| 83 |
+
if not all(MODULES.values()):
|
| 84 |
+
missing = [k for k, v in MODULES.items() if v is None]
|
| 85 |
+
return {
|
| 86 |
+
"success": False,
|
| 87 |
+
"error": f"Missing required modules: {missing}",
|
| 88 |
+
"message": "Pipeline modules not available"
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
try:
|
| 92 |
logger.info(f"Starting pipeline for: {audio_file_path}")
|
| 93 |
|
| 94 |
# Step 1: Convert to WAV
|
| 95 |
logger.info("Step 1: Converting audio to WAV...")
|
| 96 |
+
wav_path = MODULES['convert_to_wav'](audio_file_path, sr=16000, mono=True)
|
| 97 |
logger.info(f"WAV conversion completed: {wav_path}")
|
| 98 |
|
| 99 |
# Step 2: Generate CHA file using Batchalign
|
| 100 |
logger.info("Step 2: Generating CHA file...")
|
| 101 |
+
cha_path = MODULES['to_cha_from_wav'](wav_path, lang="eng")
|
| 102 |
logger.info(f"CHA generation completed: {cha_path}")
|
| 103 |
|
| 104 |
# Step 3: Convert CHA to JSON
|
| 105 |
logger.info("Step 3: Converting CHA to JSON...")
|
| 106 |
+
chajson_path, json_data = MODULES['cha_to_json_file'](cha_path)
|
| 107 |
logger.info(f"JSON conversion completed: {chajson_path}")
|
| 108 |
|
| 109 |
# Step 4: Run aphasia classification
|
| 110 |
logger.info("Step 4: Running aphasia classification...")
|
| 111 |
+
results = MODULES['predict_from_chajson'](MODEL_DIR, chajson_path, output_file=None)
|
| 112 |
logger.info("Classification completed")
|
| 113 |
|
| 114 |
# Cleanup temporary files
|
|
|
|
| 135 |
}
|
| 136 |
|
| 137 |
def process_audio_input(audio_file):
|
| 138 |
+
"""Process audio file and return formatted results"""
|
|
|
|
|
|
|
| 139 |
try:
|
| 140 |
if audio_file is None:
|
| 141 |
+
return "❌ Error: No audio file uploaded"
|
| 142 |
+
|
| 143 |
+
# Check if pipeline is available
|
| 144 |
+
if not all(MODULES.values()):
|
| 145 |
+
return "❌ Error: Audio processing pipeline not available. Missing required modules."
|
|
|
|
|
|
|
| 146 |
|
| 147 |
# Check file format
|
| 148 |
file_path = audio_file
|
| 149 |
+
if hasattr(audio_file, 'name'):
|
| 150 |
+
file_path = audio_file.name
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
file_ext = Path(file_path).suffix.lower()
|
| 153 |
if file_ext not in SUPPORTED_AUDIO_FORMATS:
|
| 154 |
+
return f"❌ Error: Unsupported file format {file_ext}. Supported: {', '.join(SUPPORTED_AUDIO_FORMATS)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
# Run the complete pipeline
|
| 157 |
pipeline_result = run_complete_pipeline(file_path)
|
| 158 |
|
| 159 |
if not pipeline_result["success"]:
|
| 160 |
+
return f"❌ Pipeline Error: {pipeline_result['message']}\n\nDetails: {pipeline_result.get('error', '')}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
+
# Format results
|
| 163 |
results = pipeline_result["results"]
|
| 164 |
|
|
|
|
| 165 |
if "predictions" in results and len(results["predictions"]) > 0:
|
| 166 |
first_pred = results["predictions"][0]
|
| 167 |
|
| 168 |
if "error" in first_pred:
|
| 169 |
+
return f"❌ Classification Error: {first_pred['error']}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
+
# Format main result
|
| 172 |
predicted_class = first_pred["prediction"]["predicted_class"]
|
| 173 |
confidence = first_pred["prediction"]["confidence_percentage"]
|
| 174 |
+
class_name = first_pred["class_description"]["name"]
|
| 175 |
+
description = first_pred["class_description"]["description"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
|
| 177 |
# Additional metrics
|
| 178 |
additional_info = first_pred["additional_predictions"]
|
|
|
|
| 180 |
fluency_score = additional_info["fluency_score"]
|
| 181 |
fluency_rating = additional_info["fluency_rating"]
|
| 182 |
|
| 183 |
+
# Format probability distribution (top 3)
|
|
|
|
|
|
|
|
|
|
| 184 |
prob_dist = first_pred["probability_distribution"]
|
| 185 |
top_3 = list(prob_dist.items())[:3]
|
| 186 |
|
| 187 |
+
result_text = f"""
|
| 188 |
+
🧠 **APHASIA CLASSIFICATION RESULTS**
|
| 189 |
+
|
| 190 |
+
🎯 **Primary Classification:** {predicted_class}
|
| 191 |
+
📊 **Confidence:** {confidence}
|
| 192 |
+
📋 **Type:** {class_name}
|
| 193 |
+
|
| 194 |
+
📈 **Additional Metrics:**
|
| 195 |
+
• Severity Level: {severity_level}/3
|
| 196 |
+
• Fluency Score: {fluency_score:.3f} ({fluency_rating})
|
| 197 |
+
|
| 198 |
+
📊 **Top 3 Probability Rankings:**
|
| 199 |
+
"""
|
| 200 |
for i, (aphasia_type, info) in enumerate(top_3, 1):
|
| 201 |
+
result_text += f"{i}. {aphasia_type}: {info['percentage']}\n"
|
| 202 |
|
| 203 |
+
result_text += f"""
|
| 204 |
+
📝 **Clinical Description:**
|
| 205 |
+
{description}
|
| 206 |
+
|
| 207 |
+
📊 **Processing Summary:**
|
| 208 |
+
• Total sentences analyzed: {results.get('total_sentences', 'N/A')}
|
| 209 |
+
• Average confidence: {results.get('summary', {}).get('average_confidence', 'N/A')}
|
| 210 |
+
• Average fluency: {results.get('summary', {}).get('average_fluency_score', 'N/A')}
|
| 211 |
+
"""
|
| 212 |
|
| 213 |
+
return result_text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
|
| 215 |
else:
|
| 216 |
+
return "❌ No predictions generated. The audio file may not contain analyzable speech."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
|
| 218 |
except Exception as e:
|
| 219 |
logger.error(f"Processing error: {str(e)}")
|
| 220 |
logger.error(traceback.format_exc())
|
| 221 |
+
return f"❌ Processing Error: {str(e)}\n\nPlease check the logs for more details."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
|
| 223 |
def process_text_input(text_input):
|
| 224 |
+
"""Process text input directly (fallback option)"""
|
|
|
|
|
|
|
| 225 |
try:
|
| 226 |
if not text_input or not text_input.strip():
|
| 227 |
+
return "❌ Error: Please enter some text for analysis"
|
| 228 |
+
|
| 229 |
+
# Check if prediction module is available
|
| 230 |
+
if MODULES['predict_from_chajson'] is None:
|
| 231 |
+
return "❌ Error: Text analysis not available. Missing prediction module."
|
|
|
|
|
|
|
| 232 |
|
| 233 |
# Create a simple JSON structure for text-only input
|
| 234 |
temp_json = {
|
|
|
|
| 255 |
temp_json_path = f.name
|
| 256 |
|
| 257 |
# Run prediction
|
| 258 |
+
results = MODULES['predict_from_chajson'](MODEL_DIR, temp_json_path, output_file=None)
|
| 259 |
|
| 260 |
# Cleanup
|
| 261 |
try:
|
|
|
|
| 263 |
except:
|
| 264 |
pass
|
| 265 |
|
| 266 |
+
# Format results
|
| 267 |
if "predictions" in results and len(results["predictions"]) > 0:
|
| 268 |
first_pred = results["predictions"][0]
|
| 269 |
|
| 270 |
predicted_class = first_pred["prediction"]["predicted_class"]
|
| 271 |
confidence = first_pred["prediction"]["confidence_percentage"]
|
| 272 |
+
description = first_pred["class_description"]["description"]
|
| 273 |
+
severity = first_pred["additional_predictions"]["predicted_severity_level"]
|
| 274 |
+
fluency = first_pred["additional_predictions"]["fluency_rating"]
|
| 275 |
|
| 276 |
+
return f"""
|
| 277 |
+
🧠 **TEXT ANALYSIS RESULTS**
|
| 278 |
+
|
| 279 |
+
🎯 **Predicted:** {predicted_class}
|
| 280 |
+
📊 **Confidence:** {confidence}
|
| 281 |
+
📈 **Severity:** {severity}/3
|
| 282 |
+
🗣️ **Fluency:** {fluency}
|
| 283 |
+
|
| 284 |
+
📝 **Description:**
|
| 285 |
+
{description}
|
| 286 |
+
|
| 287 |
+
ℹ️ **Note:** Text-based analysis provides limited accuracy compared to audio analysis.
|
| 288 |
+
"""
|
| 289 |
else:
|
| 290 |
+
return "❌ No predictions generated from text input"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 291 |
|
| 292 |
except Exception as e:
|
| 293 |
logger.error(f"Text processing error: {str(e)}")
|
| 294 |
+
return f"❌ Error: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
|
|
|
|
| 296 |
def create_interface():
|
| 297 |
+
"""Create simplified Gradio interface"""
|
| 298 |
+
|
| 299 |
+
# Check system status
|
| 300 |
+
model_available, missing_files = check_model_files()
|
| 301 |
+
pipeline_available = all(MODULES.values())
|
| 302 |
|
| 303 |
+
status_message = "🟢 **System Status: Ready**" if model_available and pipeline_available else "🔴 **System Status: Issues Detected**"
|
| 304 |
+
|
| 305 |
+
if not model_available:
|
| 306 |
+
status_message += f"\n❌ Missing model files: {', '.join(missing_files)}"
|
| 307 |
+
|
| 308 |
+
if not pipeline_available:
|
| 309 |
+
missing_modules = [k for k, v in MODULES.items() if v is None]
|
| 310 |
+
status_message += f"\n❌ Missing modules: {', '.join(missing_modules)}"
|
| 311 |
+
|
| 312 |
+
# Create interface
|
| 313 |
+
with gr.Blocks(title="Aphasia Classification System") as demo:
|
| 314 |
|
|
|
|
| 315 |
gr.HTML("""
|
| 316 |
+
<div style="text-align: center; margin-bottom: 2rem;">
|
| 317 |
<h1>🧠 Advanced Aphasia Classification System</h1>
|
| 318 |
+
<p>Upload audio files or enter text to analyze speech patterns and classify aphasia types</p>
|
| 319 |
</div>
|
| 320 |
""")
|
| 321 |
|
| 322 |
+
gr.Markdown(status_message)
|
| 323 |
+
|
| 324 |
with gr.Tabs():
|
| 325 |
+
# Audio Tab
|
| 326 |
+
with gr.Tab("🎵 Audio Analysis"):
|
| 327 |
gr.Markdown("### Upload Audio File")
|
| 328 |
+
gr.Markdown("**Supported formats:** MP3, MP4, WAV, M4A, FLAC, OGG")
|
| 329 |
|
| 330 |
+
audio_input = gr.File(
|
| 331 |
+
label="Upload Audio File",
|
| 332 |
+
file_types=["audio"]
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
audio_btn = gr.Button("🔍 Analyze Audio", variant="primary")
|
| 336 |
+
|
| 337 |
+
audio_output = gr.Textbox(
|
| 338 |
+
label="Analysis Results",
|
| 339 |
+
lines=20,
|
| 340 |
+
max_lines=30
|
| 341 |
+
)
|
|
|
|
|
|
|
|
|
|
| 342 |
|
| 343 |
+
audio_btn.click(
|
| 344 |
+
fn=process_audio_input,
|
| 345 |
+
inputs=audio_input,
|
| 346 |
+
outputs=audio_output
|
| 347 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
|
| 349 |
+
# Text Tab
|
| 350 |
+
with gr.Tab("📝 Text Analysis"):
|
| 351 |
gr.Markdown("### Direct Text Input")
|
| 352 |
+
gr.Markdown("**Note:** Audio analysis provides more accurate results")
|
| 353 |
|
| 354 |
+
text_input = gr.Textbox(
|
| 355 |
+
label="Enter Text",
|
| 356 |
+
placeholder="Enter speech transcription or text for analysis...",
|
| 357 |
+
lines=5
|
| 358 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 359 |
|
| 360 |
+
text_btn = gr.Button("🔍 Analyze Text", variant="secondary")
|
| 361 |
+
|
| 362 |
+
text_output = gr.Textbox(
|
| 363 |
+
label="Analysis Results",
|
| 364 |
+
lines=15,
|
| 365 |
+
max_lines=20
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
text_btn.click(
|
| 369 |
+
fn=process_text_input,
|
| 370 |
+
inputs=text_input,
|
| 371 |
+
outputs=text_output
|
| 372 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 373 |
|
|
|
|
| 374 |
gr.HTML("""
|
| 375 |
<div style="text-align: center; margin-top: 2rem; padding: 1rem; border-top: 1px solid #eee;">
|
| 376 |
+
<p><strong>About:</strong> This system uses advanced NLP and acoustic analysis to classify different types of aphasia.</p>
|
| 377 |
<p><em>For research and clinical assessment purposes.</em></p>
|
| 378 |
</div>
|
| 379 |
""")
|
| 380 |
|
| 381 |
return demo
|
| 382 |
|
|
|
|
| 383 |
if __name__ == "__main__":
|
| 384 |
try:
|
| 385 |
logger.info("Starting Aphasia Classification System...")
|
| 386 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 387 |
# Create and launch interface
|
| 388 |
demo = create_interface()
|
| 389 |
demo.launch(
|
| 390 |
server_name="0.0.0.0",
|
| 391 |
server_port=7860,
|
| 392 |
+
share=True, # This fixes the localhost error
|
| 393 |
+
show_error=True
|
| 394 |
)
|
| 395 |
|
| 396 |
except Exception as e:
|