Advanced AI-Powered Raga Detection and Music Therapy System
|
πΌ Advanced Audio Processing
π€ Multi-Model LLM Integration
|
π§ Advanced Audio-Text Mapping
π Clinical-Grade Pipeline
|
System Requirements:
- Python 3.7+ with CUDA support (optional but recommended)
- 8GB+ RAM for model inference (16GB recommended for Yi-34B)
- Audio processing libraries for feature extraction
- 4GB+ storage for models and datasets
π§ Complete Setup Guide
# 1. Clone the repository
git clone https://github.com/yourusername/sursoothe.git
cd sursoothe
# 2. Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# 3. Install core dependencies
pip install torch torchvision torchaudio
pip install transformers datasets
pip install peft bitsandbytes # For LoRA fine-tuning
# 4. Install audio processing libraries
pip install librosa scipy
pip install parselmouth speechpy
pip install scikit-learn pandas numpy
# 5. Install report generation (optional)
pip install reportlab # For PDF generation
# 6. Create required directories
mkdir -p data results/json_values mapping_output
mkdir -p llm_engine finetuned_models training_data
# 7. Initialize the system
python raga_detection.py # Run detection first
python therapy_mapping.py # Then therapy mappingπ³ Docker Installation
# Quick start with Docker
docker build -t sursoothe .
docker run -p 8000:8000 -v $(pwd)/data:/app/data sursoothe
# Or with docker-compose for full stack
docker-compose up -dgraph TD
A[π΅ Audio Input] --> B[π§ Feature Extraction]
B --> C[π€ Raga Detection]
C --> D[π Therapy Mapping]
D --> E[π§ LLM Processing]
E --> F[π‘οΈ Safety Verification]
F --> G[π Report Generation]
G --> H[πΎ Multi-format Output]
B --> B1[librosa]
B --> B2[speechpy]
B --> B3[Parselmouth]
C --> C1[Custom CNN]
C --> C2[MFCC Features]
C --> C3[Spectral Analysis]
D --> D1[Wav2CLIP]
D --> D2[Patient Profiling]
E --> E1[Yi-34B]
E --> E2[OpenOrca]
E --> E3[BioLLMs]
G --> G1[PDF Reports]
G --> G2[JSON Data]
G --> G3[Text Reports]
The primary audio processing module that handles raga classification using advanced signal processing and machine learning techniques. It combines traditional audio features (MFCC, ZCR, Chroma) with modern deep learning approaches to achieve high accuracy in raga recognition across 10+ classical Indian ragas.
Implements a custom Wav2CLIP-inspired system that creates joint embeddings for audio and text in a shared semantic space. This module maps detected ragas to therapeutic descriptions and generates personalized therapy recommendations based on patient profiles and detected musical characteristics.
Advanced language model integration featuring dual-model architecture with Yi-34B as the primary therapy reasoning engine and OpenOrca-Platypus2-7B for safety verification. Includes LoRA fine-tuning capabilities and parameter-efficient training methods.
Professional medical reporting system using specialized biomedical language models including BioGPT, BioBERT, and SciBERT. Generates clinical-grade PDF reports with proper medical formatting and comprehensive biological analysis integration.
π Classical Ragas Database (10+ Primary Ragas)
| Raga Name | Time Period | Therapeutic Properties | Clinical Applications |
|---|---|---|---|
| Yaman | Evening | Relaxation, Peace | Anxiety, Stress Relief |
| Bhairav | Morning | Alertness, Focus | Depression, Energy Enhancement |
| Malkauns | Night | Deep Relaxation | Insomnia, Sleep Disorders |
| Kafi | Late Morning | Emotional Balance | Mood Disorders, PTSD |
| Todi | Morning | Contemplation | Meditation, Mindfulness |
| Bilawal | Morning | Uplifting, Joy | Depression, Seasonal Affective |
| Bhimpalasi | Afternoon | Devotional, Calm | Spiritual Healing, Grief |
| Darbari | Night | Solemnity, Depth | Chronic Pain Management |
| Bageshri | Night | Serenity, Romance | Relationship Therapy |
| Puriya | Evening | Mystical, Introspective | Trauma Recovery |
|
π― Audio Model Setup Architecture: Custom CNN + Traditional ML
Input Features: MFCC, ZCR, Chroma, Spectral
Dataset: Combined Dataset.csv + Final_dataset_s.csv
Optimizer: AdamW / Random Forest
Training: Enhanced feature extraction
Validation: Cross-validation with stratification |
π Performance Metrics
|
# Yi-34B Configuration
MODEL_CONFIGS = {
"yi-34b": {
"model_name": "01-ai/Yi-34B-Chat",
"purpose": "Primary Therapy Reasoning Engine",
"max_length": 2048,
"batch_size": 1,
"gradient_accumulation_steps": 16,
"learning_rate": 2e-4,
"lora_r": 16,
"lora_alpha": 32
}
}π Therapy Recommendation Templates
@dataclass
class PatientProfile:
age: int
gender: str
mental_condition: str
severity: str
improvement_score: float
listening_time: floatThe system generates comprehensive therapy recommendations including:
- Raga-specific benefits based on classical music theory
- Duration recommendations tailored to patient condition
- Time-of-day optimization for maximum therapeutic effect
- Contraindication warnings for safe therapy delivery
- Progress tracking metrics for session monitoring
from raga_detection import main as detect_raga
from therapy_mapping import RagaTherapyMapper
# Step 1: Run raga detection
print("π΅ Running raga detection...")
detection_results = detect_raga()
# Step 2: Initialize therapy mapper
mapper = RagaTherapyMapper()
# Step 3: Process therapy mapping
print("π₯ Processing therapy recommendations...")
therapy_results = mapper.process_therapy_mapping()
# Step 4: View results
if therapy_results["status"] == "success":
print(f"β
Generated {therapy_results['total_mappings']} therapy recommendations")
print(f"π Reports saved in: mapping_output/")from llm_engine.prompter import CompleteRagaTherapySystem
# Initialize complete system
complete_system = CompleteRagaTherapySystem()
# Patient data
patient_data = {
'age': 28,
'gender': 'Female',
'condition': 'Anxiety',
'severity': 'Moderate',
'history': 'Work-related stress'
}
# Generate comprehensive recommendation
recommendation = complete_system.generate_complete_recommendation(
patient_data=patient_data,
detected_raga='Yaman',
confidence=0.85
)
# Save in all formats (JSON, TXT, PDF)
saved_files = complete_system.output_generator.save_all_formats(
recommendation, patient_id="P001"
)| Safety Feature | Implementation | Clinical Validation |
|---|---|---|
| Contraindication Checking | Multi-layer validation | Medical expert reviewed |
| Age Appropriateness | Automatic age-based modifications | Pediatric specialist approved |
| Severity Assessment | Risk-level categorization | Clinical psychologist validated |
| Professional Supervision | Requirement flagging system | Healthcare provider integrated |
| Progress Monitoring | Session tracking metrics | Patient outcome verified |
Signal Processing Stack:
- librosa: Core audio analysis and MFCC extraction
- scipy: Signal filtering and frequency domain analysis
- parselmouth: Prosodic feature extraction for pitch analysis
- speechpy: Advanced audio feature computation
- numpy: Numerical computations and array operations
Feature Set:
- MFCC Coefficients: 0-18 (mel-frequency cepstral coefficients)
- Zero Crossing Rate: Temporal feature for rhythm analysis
- Chroma Features: Harmonic content representation
- Spectral Features: Centroid, bandwidth, rolloff characteristics
class Wav2CLIPEmbedder:
"""Custom audio-text embedding system"""
def __init__(self, model_name="distilbert-base-uncased"):
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.text_encoder = AutoModel.from_pretrained(model_name)
self.audio_encoder = self._build_audio_encoder()
self.audio_projection = nn.Linear(512, 256)
self.text_projection = nn.Linear(768, 256)The system generates comprehensive reports in multiple formats to serve different stakeholders:
π PDF Reports: Clinical-grade documents with medical formatting, patient information, raga analysis, therapeutic recommendations, and safety guidelines. Includes professional styling with proper headers, sections, and medical terminology.
πΎ JSON Data: Machine-readable structured data containing all analysis parameters, recommendation details, confidence scores, and metadata for integration with electronic health record systems.
π Text Reports: Plain text format for universal compatibility, containing the same comprehensive information as PDF reports but in a simplified format for systems without advanced document processing capabilities.
mapping_output/
βββ therapy_mapping_results.json # Main analysis results
βββ detailed_therapy_mappings.json # Individual patient mappings
βββ therapy_session_templates.json # Practitioner session guides
βββ therapy_mapping_report.pdf # Professional clinical report
βββ patient_reports/ # Individual patient files
βββ P001_therapy_recommendation.pdf
βββ P001_session_data.json
βββ P001_progress_tracking.txt
π§ Model Configuration Options
# Advanced system configuration
SYSTEM_CONFIG = {
"audio_processing": {
"sample_rate": 22050,
"n_mfcc": 19,
"hop_length": 512,
"n_fft": 2048
},
"model_settings": {
"use_gpu": True,
"quantization": "4bit", # For memory optimization
"max_length": 2048,
"temperature": 0.7
},
"safety_settings": {
"enable_contraindication_check": True,
"require_professional_oversight": True,
"age_based_modifications": True
}
}SurSoothe has been developed with rigorous attention to clinical and therapeutic standards. The system incorporates evidence-based music therapy principles, validated safety protocols, and professional medical reporting standards. All therapeutic recommendations are generated based on established research in music therapy and Indian classical music's documented effects on various psychological and physiological conditions.
The integration of traditional signal processing with modern transformer-based language models represents a novel approach to music therapy systems. The custom Wav2CLIP implementation bridges the gap between audio analysis and textual therapeutic descriptions, while the multi-model LLM architecture ensures both therapeutic relevance and safety validation.
We welcome contributions from researchers, developers, music therapists, and healthcare professionals. SurSoothe is designed to be an open platform for advancing the intersection of artificial intelligence and music therapy.
π οΈ Development Setup
# Install development dependencies
pip install -r requirements-dev.txt
# Run system tests
python -m pytest tests/
# Code formatting
black *.py llm_engine/
isort *.py llm_engine/
# Type checking
mypy --ignore-missing-imports *.py
# Test individual components
python raga_detection.py test_system
python therapy_mapping.py- π΅ Raga Database Expansion: Additional regional variations and rare ragas
- π Multilingual Support: Therapy recommendations in regional languages
- π± Mobile Integration: Smartphone app for real-time therapy sessions
- π¬ Clinical Studies: Validation studies with healthcare institutions
- π Evaluation Metrics: Enhanced clinical outcome measurements
- π€ Model Improvements: Advanced architectures and training techniques
This project is licensed under the BSD 2-Clause License - see the LICENSE file for details.
Important Note: While SurSoothe provides evidence-based music therapy recommendations, it should be used as a complementary tool alongside professional healthcare guidance, not as a replacement for clinical treatment.
π΅ Harmonizing ancient musical wisdom with modern AI technology for therapeutic healing π΅
Developed with dedication to advancing accessible, evidence-based music therapy
SurSoothe - Where technology meets traditional healing through the power of Indian classical music