help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
speech-recognition
/
scripts
RSK World
speech-recognition
Speech Recognition Dataset - Audio AI + Speech-to-Text + Voice Recognition
scripts
  • __init__.py848 B
  • augmentation.py13.9 KB
  • evaluate_model.py13.9 KB
  • example_usage.py5.3 KB
  • generate_sample_audio.py10.2 KB
  • load_dataset.py9 KB
  • preprocess.py8.5 KB
  • train_model.py9.5 KB
  • transformer_model.py14.9 KB
augmentation.pyevaluate_model.pyvisualize_ner.pytranscripts.json.gitkeep__init__.py
scripts/augmentation.py
Raw Download
Find: Go to:
"""
============================================================================
Speech Recognition Dataset - Data Augmentation Script
============================================================================

Project: Speech Recognition Dataset
Description: Audio speech recognition dataset with labeled speech samples 
             for training speech-to-text and voice recognition models.

============================================================================
DEVELOPER INFORMATION
============================================================================
Website: https://rskworld.in
Founded by: Molla Samser
Designer & Tester: Rima Khatun
Email: help@rskworld.in
Support: support@rskworld.in
Phone: +91 93305 39277
Address: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147

============================================================================
COPYRIGHT NOTICE
============================================================================
© 2026 RSK World. All rights reserved.
This dataset is provided for educational and research purposes.

============================================================================

This script provides various audio augmentation techniques to expand
the training dataset and improve model robustness.
"""

import numpy as np
import librosa
import soundfile as sf
from pathlib import Path
import pandas as pd
from tqdm import tqdm
import random


class AudioAugmentation:
    """
    Audio augmentation class for speech recognition datasets.
    
    Provides various augmentation techniques:
    - Time stretching
    - Pitch shifting
    - Adding noise
    - Time shifting
    - Volume variation
    - Speed perturbation
    - SpecAugment (frequency/time masking)
    """
    
    def __init__(self, sr=16000):
        """
        Initialize the augmentation class.
        
        Args:
            sr: Sample rate for audio processing
        """
        self.sr = sr
    
    def time_stretch(self, audio, rate=None):
        """
        Apply time stretching to audio.
        
        Args:
            audio: Audio signal
            rate: Stretch rate (default: random between 0.8 and 1.2)
            
        Returns:
            Time-stretched audio
        """
        if rate is None:
            rate = np.random.uniform(0.8, 1.2)
        return librosa.effects.time_stretch(audio, rate=rate)
    
    def pitch_shift(self, audio, n_steps=None):
        """
        Apply pitch shifting to audio.
        
        Args:
            audio: Audio signal
            n_steps: Number of semitones to shift (default: random between -4 and 4)
            
        Returns:
            Pitch-shifted audio
        """
        if n_steps is None:
            n_steps = np.random.uniform(-4, 4)
        return librosa.effects.pitch_shift(audio, sr=self.sr, n_steps=n_steps)
    
    def add_noise(self, audio, noise_level=None):
        """
        Add Gaussian noise to audio.
        
        Args:
            audio: Audio signal
            noise_level: Noise amplitude (default: random between 0.001 and 0.01)
            
        Returns:
            Noisy audio
        """
        if noise_level is None:
            noise_level = np.random.uniform(0.001, 0.01)
        noise = np.random.randn(len(audio)) * noise_level
        return audio + noise
    
    def time_shift(self, audio, shift_max=None):
        """
        Apply random time shift to audio.
        
        Args:
            audio: Audio signal
            shift_max: Maximum shift in samples (default: 10% of audio length)
            
        Returns:
            Time-shifted audio
        """
        if shift_max is None:
            shift_max = int(len(audio) * 0.1)
        shift = np.random.randint(-shift_max, shift_max)
        return np.roll(audio, shift)
    
    def change_volume(self, audio, gain=None):
        """
        Change audio volume.
        
        Args:
            audio: Audio signal
            gain: Volume multiplier (default: random between 0.5 and 1.5)
            
        Returns:
            Volume-adjusted audio
        """
        if gain is None:
            gain = np.random.uniform(0.5, 1.5)
        return audio * gain
    
    def speed_perturbation(self, audio, speed_factor=None):
        """
        Apply speed perturbation (changes both speed and pitch).
        
        Args:
            audio: Audio signal
            speed_factor: Speed multiplier (default: random between 0.9 and 1.1)
            
        Returns:
            Speed-perturbed audio
        """
        if speed_factor is None:
            speed_factor = np.random.uniform(0.9, 1.1)
        
        # Resample to change speed
        indices = np.round(np.arange(0, len(audio), speed_factor))
        indices = indices[indices < len(audio)].astype(int)
        return audio[indices]
    
    def add_background_noise(self, audio, noise_audio, snr_db=None):
        """
        Add background noise from another audio file.
        
        Args:
            audio: Original audio signal
            noise_audio: Background noise audio
            snr_db: Signal-to-noise ratio in dB (default: random between 5 and 20)
            
        Returns:
            Audio with background noise
        """
        if snr_db is None:
            snr_db = np.random.uniform(5, 20)
        
        # Adjust noise length
        if len(noise_audio) < len(audio):
            noise_audio = np.tile(noise_audio, int(np.ceil(len(audio) / len(noise_audio))))
        noise_audio = noise_audio[:len(audio)]
        
        # Calculate scaling factor for desired SNR
        signal_power = np.mean(audio ** 2)
        noise_power = np.mean(noise_audio ** 2)
        
        if noise_power > 0:
            scale = np.sqrt(signal_power / (noise_power * 10 ** (snr_db / 10)))
            return audio + scale * noise_audio
        return audio
    
    def frequency_mask(self, spectrogram, num_masks=1, mask_factor=27):
        """
        Apply frequency masking (SpecAugment).
        
        Args:
            spectrogram: Mel spectrogram
            num_masks: Number of frequency masks
            mask_factor: Maximum mask width
            
        Returns:
            Masked spectrogram
        """
        spec = spectrogram.copy()
        num_freqs = spec.shape[0]
        
        for _ in range(num_masks):
            f = np.random.randint(0, mask_factor)
            f0 = np.random.randint(0, num_freqs - f)
            spec[f0:f0 + f, :] = 0
        
        return spec
    
    def time_mask(self, spectrogram, num_masks=1, mask_factor=100):
        """
        Apply time masking (SpecAugment).
        
        Args:
            spectrogram: Mel spectrogram
            num_masks: Number of time masks
            mask_factor: Maximum mask width
            
        Returns:
            Masked spectrogram
        """
        spec = spectrogram.copy()
        num_frames = spec.shape[1]
        
        for _ in range(num_masks):
            t = np.random.randint(0, min(mask_factor, num_frames))
            t0 = np.random.randint(0, num_frames - t)
            spec[:, t0:t0 + t] = 0
        
        return spec
    
    def spec_augment(self, spectrogram, num_freq_masks=2, num_time_masks=2):
        """
        Apply SpecAugment (combined frequency and time masking).
        
        Args:
            spectrogram: Mel spectrogram
            num_freq_masks: Number of frequency masks
            num_time_masks: Number of time masks
            
        Returns:
            Augmented spectrogram
        """
        spec = self.frequency_mask(spectrogram, num_freq_masks)
        spec = self.time_mask(spec, num_time_masks)
        return spec
    
    def random_augment(self, audio, augmentations=None):
        """
        Apply random augmentations to audio.
        
        Args:
            audio: Audio signal
            augmentations: List of augmentation names to apply
                          (default: random selection)
            
        Returns:
            Augmented audio
        """
        if augmentations is None:
            augmentations = random.sample([
                'time_stretch', 'pitch_shift', 'add_noise',
                'time_shift', 'change_volume', 'speed_perturbation'
            ], k=random.randint(1, 3))
        
        augmented = audio.copy()
        
        for aug in augmentations:
            if aug == 'time_stretch':
                augmented = self.time_stretch(augmented)
            elif aug == 'pitch_shift':
                augmented = self.pitch_shift(augmented)
            elif aug == 'add_noise':
                augmented = self.add_noise(augmented)
            elif aug == 'time_shift':
                augmented = self.time_shift(augmented)
            elif aug == 'change_volume':
                augmented = self.change_volume(augmented)
            elif aug == 'speed_perturbation':
                augmented = self.speed_perturbation(augmented)
        
        return augmented


class DatasetAugmenter:
    """
    Augment entire dataset with various audio transformations.
    """
    
    def __init__(self, audio_dir, output_dir, sr=16000):
        """
        Initialize the dataset augmenter.
        
        Args:
            audio_dir: Directory containing original audio files
            output_dir: Directory to save augmented files
            sr: Sample rate
        """
        self.audio_dir = Path(audio_dir)
        self.output_dir = Path(output_dir)
        self.sr = sr
        self.augmenter = AudioAugmentation(sr)
        
        self.output_dir.mkdir(parents=True, exist_ok=True)
    
    def augment_file(self, audio_path, num_augmentations=3):
        """
        Generate multiple augmented versions of a single audio file.
        
        Args:
            audio_path: Path to audio file
            num_augmentations: Number of augmented versions to create
            
        Returns:
            List of (augmented_audio, augmentation_info) tuples
        """
        # Load audio
        audio, _ = librosa.load(str(audio_path), sr=self.sr)
        
        augmented_versions = []
        augmentation_types = [
            ['time_stretch'],
            ['pitch_shift'],
            ['add_noise'],
            ['time_stretch', 'add_noise'],
            ['pitch_shift', 'change_volume'],
            ['speed_perturbation', 'add_noise']
        ]
        
        for i in range(num_augmentations):
            augs = augmentation_types[i % len(augmentation_types)]
            augmented = self.augmenter.random_augment(audio, augs)
            augmented_versions.append((augmented, '_'.join(augs)))
        
        return augmented_versions
    
    def augment_dataset(self, metadata_path, num_augmentations=2):
        """
        Augment entire dataset.
        
        Args:
            metadata_path: Path to metadata CSV
            num_augmentations: Number of augmented versions per file
            
        Returns:
            Updated metadata DataFrame
        """
        # Load metadata
        metadata = pd.read_csv(metadata_path)
        new_rows = []
        
        print(f"Augmenting dataset with {num_augmentations} versions per file...")
        
        for idx, row in tqdm(metadata.iterrows(), total=len(metadata)):
            audio_path = self.audio_dir / row['file_name']
            
            if not audio_path.exists():
                continue
            
            try:
                # Generate augmented versions
                augmented_versions = self.augment_file(
                    audio_path, 
                    num_augmentations
                )
                
                # Save augmented files
                for i, (aug_audio, aug_type) in enumerate(augmented_versions):
                    # Generate new filename
                    stem = audio_path.stem
                    new_filename = f"{stem}_aug{i}_{aug_type}.wav"
                    output_path = self.output_dir / new_filename
                    
                    # Save audio
                    sf.write(str(output_path), aug_audio, self.sr)
                    
                    # Create new metadata row
                    new_row = row.copy()
                    new_row['id'] = f"{row['id']}_aug{i}"
                    new_row['file_name'] = new_filename
                    new_row['augmentation'] = aug_type
                    new_rows.append(new_row)
                    
            except Exception as e:
                print(f"Error augmenting {audio_path}: {str(e)}")
                continue
        
        # Create augmented metadata
        if new_rows:
            augmented_df = pd.DataFrame(new_rows)
            
            # Save augmented metadata
            augmented_df.to_csv(
                self.output_dir / 'augmented_metadata.csv',
                index=False
            )
            
            print(f"\nAugmentation complete!")
            print(f"Original files: {len(metadata)}")
            print(f"Augmented files: {len(new_rows)}")
            print(f"Total files: {len(metadata) + len(new_rows)}")
            
            return augmented_df
        
        return pd.DataFrame()


def main():
    """Main function to run data augmentation"""
    # Initialize augmenter
    augmenter = DatasetAugmenter(
        audio_dir='data/audio',
        output_dir='data/augmented',
        sr=16000
    )
    
    # Augment dataset
    augmented_metadata = augmenter.augment_dataset(
        metadata_path='data/metadata.csv',
        num_augmentations=2
    )
    
    print("\nData augmentation completed successfully!")
    print("Augmented files saved to: data/augmented/")


if __name__ == '__main__':
    main()

432 lines•13.9 KB
python
scripts/evaluate_model.py
Raw Download
Find: Go to:
"""
============================================================================
Speech Recognition Dataset - Model Evaluation Script
============================================================================

Project: Speech Recognition Dataset
Description: Audio speech recognition dataset with labeled speech samples 
             for training speech-to-text and voice recognition models.

============================================================================
DEVELOPER INFORMATION
============================================================================
Website: https://rskworld.in
Founded by: Molla Samser
Designer & Tester: Rima Khatun
Email: help@rskworld.in
Support: support@rskworld.in
Phone: +91 93305 39277
Address: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147

============================================================================
COPYRIGHT NOTICE
============================================================================
© 2026 RSK World. All rights reserved.
This dataset is provided for educational and research purposes.

============================================================================

This script provides comprehensive model evaluation including:
- Confusion matrix
- Classification report
- ROC curves
- Precision-Recall curves
- Error analysis
"""

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from pathlib import Path
from sklearn.metrics import (
    confusion_matrix, classification_report, accuracy_score,
    precision_recall_fscore_support, roc_curve, auc,
    precision_recall_curve, average_precision_score
)
from sklearn.preprocessing import LabelEncoder, label_binarize
import tensorflow as tf
import pickle
import json


class ModelEvaluator:
    """
    Comprehensive model evaluation for speech recognition.
    """
    
    def __init__(self, model_path, label_encoder_path, output_dir='evaluation'):
        """
        Initialize the evaluator.
        
        Args:
            model_path: Path to trained model
            label_encoder_path: Path to label encoder
            output_dir: Directory to save evaluation results
        """
        self.model_path = Path(model_path)
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        
        # Load model
        print(f"Loading model from {model_path}...")
        self.model = tf.keras.models.load_model(str(model_path))
        
        # Load label encoder
        with open(label_encoder_path, 'rb') as f:
            self.label_encoder = pickle.load(f)
        
        self.classes = self.label_encoder.classes_
        self.num_classes = len(self.classes)
    
    def evaluate(self, X_test, y_test):
        """
        Perform comprehensive evaluation.
        
        Args:
            X_test: Test features
            y_test: Test labels (not encoded)
            
        Returns:
            Dictionary with evaluation metrics
        """
        # Encode labels
        y_true = self.label_encoder.transform(y_test)
        y_true_onehot = label_binarize(y_true, classes=range(self.num_classes))
        
        # Get predictions
        print("Making predictions...")
        y_pred_proba = self.model.predict(X_test)
        y_pred = np.argmax(y_pred_proba, axis=1)
        
        # Calculate metrics
        metrics = {}
        
        # Basic accuracy
        metrics['accuracy'] = accuracy_score(y_true, y_pred)
        print(f"\nAccuracy: {metrics['accuracy']:.4f}")
        
        # Precision, Recall, F1
        precision, recall, f1, support = precision_recall_fscore_support(
            y_true, y_pred, average='weighted'
        )
        metrics['precision'] = precision
        metrics['recall'] = recall
        metrics['f1_score'] = f1
        
        print(f"Precision: {precision:.4f}")
        print(f"Recall: {recall:.4f}")
        print(f"F1 Score: {f1:.4f}")
        
        # Per-class metrics
        metrics['per_class'] = precision_recall_fscore_support(
            y_true, y_pred, average=None
        )
        
        # Generate visualizations
        self._plot_confusion_matrix(y_true, y_pred)
        self._plot_roc_curves(y_true_onehot, y_pred_proba)
        self._plot_precision_recall_curves(y_true_onehot, y_pred_proba)
        self._generate_classification_report(y_true, y_pred)
        self._analyze_errors(X_test, y_test, y_true, y_pred, y_pred_proba)
        
        # Save metrics
        self._save_metrics(metrics)
        
        return metrics
    
    def _plot_confusion_matrix(self, y_true, y_pred):
        """Plot and save confusion matrix."""
        cm = confusion_matrix(y_true, y_pred)
        
        plt.figure(figsize=(12, 10))
        sns.heatmap(
            cm, annot=True, fmt='d', cmap='Blues',
            xticklabels=self.classes,
            yticklabels=self.classes
        )
        plt.title('Confusion Matrix', fontsize=16, fontweight='bold')
        plt.xlabel('Predicted', fontsize=12)
        plt.ylabel('Actual', fontsize=12)
        plt.tight_layout()
        plt.savefig(self.output_dir / 'confusion_matrix.png', dpi=300)
        plt.close()
        
        print(f"Confusion matrix saved to {self.output_dir / 'confusion_matrix.png'}")
        
        # Normalized confusion matrix
        cm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        
        plt.figure(figsize=(12, 10))
        sns.heatmap(
            cm_normalized, annot=True, fmt='.2f', cmap='Blues',
            xticklabels=self.classes,
            yticklabels=self.classes
        )
        plt.title('Normalized Confusion Matrix', fontsize=16, fontweight='bold')
        plt.xlabel('Predicted', fontsize=12)
        plt.ylabel('Actual', fontsize=12)
        plt.tight_layout()
        plt.savefig(self.output_dir / 'confusion_matrix_normalized.png', dpi=300)
        plt.close()
    
    def _plot_roc_curves(self, y_true_onehot, y_pred_proba):
        """Plot ROC curves for each class."""
        plt.figure(figsize=(12, 8))
        
        colors = plt.cm.rainbow(np.linspace(0, 1, self.num_classes))
        
        # Calculate ROC for each class
        all_fpr = []
        all_tpr = []
        all_auc = []
        
        for i, (class_name, color) in enumerate(zip(self.classes, colors)):
            if self.num_classes > 2:
                fpr, tpr, _ = roc_curve(y_true_onehot[:, i], y_pred_proba[:, i])
                roc_auc = auc(fpr, tpr)
            else:
                fpr, tpr, _ = roc_curve(y_true_onehot.ravel(), y_pred_proba[:, 1])
                roc_auc = auc(fpr, tpr)
            
            all_fpr.append(fpr)
            all_tpr.append(tpr)
            all_auc.append(roc_auc)
            
            plt.plot(fpr, tpr, color=color, lw=2,
                    label=f'{class_name} (AUC = {roc_auc:.3f})')
        
        plt.plot([0, 1], [0, 1], 'k--', lw=2, label='Random')
        plt.xlim([0.0, 1.0])
        plt.ylim([0.0, 1.05])
        plt.xlabel('False Positive Rate', fontsize=12)
        plt.ylabel('True Positive Rate', fontsize=12)
        plt.title('ROC Curves', fontsize=16, fontweight='bold')
        plt.legend(loc='lower right', fontsize=10)
        plt.grid(True, alpha=0.3)
        plt.tight_layout()
        plt.savefig(self.output_dir / 'roc_curves.png', dpi=300)
        plt.close()
        
        print(f"ROC curves saved to {self.output_dir / 'roc_curves.png'}")
        print(f"Average AUC: {np.mean(all_auc):.4f}")
    
    def _plot_precision_recall_curves(self, y_true_onehot, y_pred_proba):
        """Plot Precision-Recall curves."""
        plt.figure(figsize=(12, 8))
        
        colors = plt.cm.rainbow(np.linspace(0, 1, self.num_classes))
        
        for i, (class_name, color) in enumerate(zip(self.classes, colors)):
            if self.num_classes > 2:
                precision, recall, _ = precision_recall_curve(
                    y_true_onehot[:, i], y_pred_proba[:, i]
                )
                ap = average_precision_score(y_true_onehot[:, i], y_pred_proba[:, i])
            else:
                precision, recall, _ = precision_recall_curve(
                    y_true_onehot.ravel(), y_pred_proba[:, 1]
                )
                ap = average_precision_score(y_true_onehot.ravel(), y_pred_proba[:, 1])
            
            plt.plot(recall, precision, color=color, lw=2,
                    label=f'{class_name} (AP = {ap:.3f})')
        
        plt.xlabel('Recall', fontsize=12)
        plt.ylabel('Precision', fontsize=12)
        plt.title('Precision-Recall Curves', fontsize=16, fontweight='bold')
        plt.legend(loc='lower left', fontsize=10)
        plt.grid(True, alpha=0.3)
        plt.tight_layout()
        plt.savefig(self.output_dir / 'precision_recall_curves.png', dpi=300)
        plt.close()
        
        print(f"Precision-Recall curves saved to {self.output_dir / 'precision_recall_curves.png'}")
    
    def _generate_classification_report(self, y_true, y_pred):
        """Generate and save classification report."""
        report = classification_report(
            y_true, y_pred,
            target_names=self.classes,
            output_dict=True
        )
        
        # Save as CSV
        report_df = pd.DataFrame(report).transpose()
        report_df.to_csv(self.output_dir / 'classification_report.csv')
        
        # Print report
        print("\nClassification Report:")
        print(classification_report(y_true, y_pred, target_names=self.classes))
        
        # Plot per-class metrics
        plt.figure(figsize=(14, 6))
        
        metrics_df = report_df.iloc[:-3]  # Exclude avg rows
        x = range(len(metrics_df))
        width = 0.25
        
        plt.bar([i - width for i in x], metrics_df['precision'], width, label='Precision', alpha=0.8)
        plt.bar(x, metrics_df['recall'], width, label='Recall', alpha=0.8)
        plt.bar([i + width for i in x], metrics_df['f1-score'], width, label='F1-Score', alpha=0.8)
        
        plt.xlabel('Class', fontsize=12)
        plt.ylabel('Score', fontsize=12)
        plt.title('Per-Class Performance Metrics', fontsize=16, fontweight='bold')
        plt.xticks(x, metrics_df.index, rotation=45, ha='right')
        plt.legend()
        plt.grid(True, alpha=0.3, axis='y')
        plt.tight_layout()
        plt.savefig(self.output_dir / 'per_class_metrics.png', dpi=300)
        plt.close()
    
    def _analyze_errors(self, X_test, y_test, y_true, y_pred, y_pred_proba):
        """Analyze prediction errors."""
        # Find misclassified samples
        errors = y_true != y_pred
        error_indices = np.where(errors)[0]
        
        error_analysis = []
        for idx in error_indices:
            error_analysis.append({
                'index': int(idx),
                'true_label': self.classes[y_true[idx]],
                'predicted_label': self.classes[y_pred[idx]],
                'confidence': float(np.max(y_pred_proba[idx])),
                'true_label_prob': float(y_pred_proba[idx][y_true[idx]])
            })
        
        # Save error analysis
        error_df = pd.DataFrame(error_analysis)
        error_df.to_csv(self.output_dir / 'error_analysis.csv', index=False)
        
        print(f"\nTotal errors: {len(error_indices)} ({len(error_indices)/len(y_true)*100:.2f}%)")
        
        # Plot confidence distribution of errors
        if len(error_analysis) > 0:
            confidences = [e['confidence'] for e in error_analysis]
            
            plt.figure(figsize=(10, 6))
            plt.hist(confidences, bins=20, edgecolor='white', alpha=0.7)
            plt.xlabel('Prediction Confidence', fontsize=12)
            plt.ylabel('Count', fontsize=12)
            plt.title('Confidence Distribution of Misclassified Samples', fontsize=16, fontweight='bold')
            plt.grid(True, alpha=0.3)
            plt.tight_layout()
            plt.savefig(self.output_dir / 'error_confidence_distribution.png', dpi=300)
            plt.close()
        
        # Most common error pairs
        if len(error_df) > 0:
            error_pairs = error_df.groupby(['true_label', 'predicted_label']).size()
            error_pairs = error_pairs.sort_values(ascending=False)
            
            print("\nMost Common Error Pairs:")
            print(error_pairs.head(10))
    
    def _save_metrics(self, metrics):
        """Save metrics to JSON file."""
        # Convert numpy types to Python types
        def convert_to_native(obj):
            if isinstance(obj, np.ndarray):
                return obj.tolist()
            elif isinstance(obj, np.integer):
                return int(obj)
            elif isinstance(obj, np.floating):
                return float(obj)
            elif isinstance(obj, tuple):
                return [convert_to_native(item) for item in obj]
            return obj
        
        metrics_native = {k: convert_to_native(v) for k, v in metrics.items()}
        
        with open(self.output_dir / 'metrics.json', 'w') as f:
            json.dump(metrics_native, f, indent=2)
        
        print(f"\nMetrics saved to {self.output_dir / 'metrics.json'}")


def main():
    """Main function to evaluate a trained model."""
    # Load test data
    from load_dataset import SpeechRecognitionDataset
    
    # Initialize evaluator
    evaluator = ModelEvaluator(
        model_path='models/best_model.h5',
        label_encoder_path='models/label_encoder.pkl',
        output_dir='evaluation'
    )
    
    # Load test features (you would need to prepare these)
    print("Please prepare your test data (X_test, y_test) and run evaluation.")
    print("Example:")
    print("  evaluator.evaluate(X_test, y_test)")
    
    print("\nEvaluation script ready!")


if __name__ == '__main__':
    main()

372 lines•13.9 KB
python
data/transcripts.json
Raw Download
Find: Go to:
{
  "1": "Hello, how are you today?",
  "2": "Good morning",
  "3": "Please turn on the lights",
  "4": "What's the weather like outside?",
  "5": "Set a timer for five minutes",
  "6": "Thank you very much",
  "7": "Can you play some music?",
  "8": "How much does it cost?",
  "9": "Goodbye",
  "10": "What time is it now?",
  "11": "Turn off the television",
  "12": "Where is the nearest hospital?",
  "13": "Yes please",
  "14": "Call my mother",
  "15": "What is the capital of France?",
  "16": "Send a message to John",
  "17": "No thank you",
  "18": "Play the next song",
  "19": "How do I get there?",
  "20": "Set an alarm for seven AM",
  "21": "Nice to meet you",
  "22": "What movies are playing tonight?",
  "23": "Stop the music",
  "24": "Can you repeat that please?",
  "25": "Open the door",
  "26": "What is your name?",
  "27": "Volume up",
  "28": "Have a nice day",
  "29": "Search for Italian restaurants",
  "30": "Read my emails",
  "31": "What is the temperature today?",
  "32": "Lock the front door",
  "33": "See you later",
  "34": "Navigate to the airport",
  "35": "Pause the video",
  "36": "How far is the beach?",
  "37": "Dim the lights to fifty percent",
  "38": "Good evening",
  "39": "Find me a recipe for pasta",
  "40": "Skip this track",
  "41": "What are my appointments today?",
  "42": "Close the window",
  "43": "Thanks a lot",
  "44": "How do you spell that?",
  "45": "Increase the brightness",
  "46": "What is the stock price of Apple?",
  "47": "Add milk to my shopping list",
  "48": "Good night",
  "49": "Show me photos from last week",
  "50": "Translate hello to Spanish"
}
53 lines•1.6 KB
json
models/.gitkeep
Raw Download
Find: Go to:
# This file ensures the models directory is tracked by Git
# Trained model files (.h5, .pkl, .pb) are ignored but directory structure is preserved

4 lines•151 B
text
scripts/__init__.py
Raw Download
Find: Go to:
"""
============================================================================
Speech Recognition Dataset - Scripts Package
============================================================================

Project: Speech Recognition Dataset
Website: https://rskworld.in
Founded by: Molla Samser
Designer & Tester: Rima Khatun
Email: help@rskworld.in
Support: support@rskworld.in
Phone: +91 93305 39277

============================================================================
COPYRIGHT NOTICE
============================================================================
© 2026 RSK World. All rights reserved.
This dataset is provided for educational and research purposes.

============================================================================
"""

__version__ = '1.0.0'
__author__ = 'Molla Samser - RSK World'

26 lines•848 B
python
🚀 Support RSK World

Subscribe to our YouTube channel for latest tutorials & updates!



Click subscribe & support our work ❤️

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer