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
environmental-sounds
RSK World
environmental-sounds
Environmental Sound Dataset - Audio Classification + Sound Event Detection + Deep Learning + Machine Learning
environmental-sounds
  • environmental-sounds
  • examples
  • .gitignore844 B
  • ADVANCED_FEATURES.md8.3 KB
  • CONTRIBUTING.md1.7 KB
  • CREATE_RELEASE.md5.1 KB
  • DATASET_STRUCTURE.md3.5 KB
  • LICENSE1.5 KB
  • PROJECT_SUMMARY.md5 KB
  • README.md5.9 KB
  • RELEASE_NOTES.md4.8 KB
  • analyze.py6.9 KB
  • api_server.py8.1 KB
  • audio_quality.py10.2 KB
  • audio_similarity.py10.4 KB
  • augment_audio.py10.9 KB
  • batch_processing.py11.3 KB
  • create_dataset_structure.py4.8 KB
  • create_sample_data.py4.3 KB
  • create_zip.py3.8 KB
  • deep_learning_models.py13.2 KB
  • environmental-sounds.zip50.1 KB
  • example_usage.py5 KB
  • index.html26.9 KB
  • load_data.py4.9 KB
  • model_interpretability.py10.3 KB
  • realtime_classification.py9.6 KB
  • requirements.txt475 B
  • setup.py1.7 KB
  • train_model.py7.8 KB
  • verify_project.py5.3 KB
example_usage.pycreate_sample_data.py
example_usage.py
Raw Download
Find: Go to:
"""
Environmental Sound Dataset - Example Usage Script

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

This script demonstrates basic usage of the Environmental Sound Dataset.
"""

import os
import sys

# Add current directory to path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from load_data import load_environmental_sounds, get_class_distribution, prepare_features
from analyze import analyze_audio_file, get_dataset_statistics
from train_model import train_classifier, evaluate_model, save_model


def main():
    """Main example function demonstrating dataset usage."""
    
    print("=" * 60)
    print("Environmental Sound Dataset - Example Usage")
    print("=" * 60)
    print()
    
    # Check if dataset exists
    data_dir = './environmental-sounds'
    if not os.path.exists(data_dir):
        print(f"Error: Dataset directory '{data_dir}' not found.")
        print("Please ensure the dataset is extracted in the current directory.")
        return
    
    # 1. Load dataset statistics
    print("1. Getting dataset statistics...")
    print("-" * 60)
    try:
        stats = get_dataset_statistics(data_dir)
        print(f"   Total files: {stats['total_files']}")
        print(f"   Total duration: {stats['total_duration']:.2f} seconds")
        print(f"   Average duration: {stats['avg_duration']:.2f} seconds")
        print(f"   Classes: {list(stats['classes'].keys())}")
        print()
    except Exception as e:
        print(f"   Error: {e}")
        print()
    
    # 2. Load training data
    print("2. Loading training data...")
    print("-" * 60)
    try:
        train_data, train_labels = load_environmental_sounds('train', data_dir=data_dir)
        print(f"   Loaded {len(train_data)} training samples")
        print(f"   Number of classes: {len(set(train_labels))}")
        print(f"   Classes: {sorted(set(train_labels))}")
        
        # Show class distribution
        class_dist = get_class_distribution(train_labels)
        print(f"   Class distribution:")
        for cls, count in sorted(class_dist.items()):
            print(f"     - {cls}: {count} samples")
        print()
    except Exception as e:
        print(f"   Error: {e}")
        print("   Please ensure the dataset structure is correct.")
        print("   See DATASET_STRUCTURE.md for details.")
        return
    
    # 3. Load test data
    print("3. Loading test data...")
    print("-" * 60)
    try:
        test_data, test_labels = load_environmental_sounds('test', data_dir=data_dir)
        print(f"   Loaded {len(test_data)} test samples")
        print()
    except Exception as e:
        print(f"   Error: {e}")
        print("   Test set not found or empty.")
        print()
    
    # 4. Extract features (sample)
    print("4. Extracting features from sample data...")
    print("-" * 60)
    try:
        if len(train_data) > 0:
            sample_data = train_data[:10]  # Use first 10 samples
            features = prepare_features(sample_data, feature_type='mfcc', n_mfcc=13)
            print(f"   Extracted features from {len(sample_data)} samples")
            print(f"   Feature shape: {features.shape}")
            print(f"   Features per sample: {features.shape[1]}")
            print()
    except Exception as e:
        print(f"   Error: {e}")
        print()
    
    # 5. Train a simple classifier (if enough data)
    print("5. Training classifier...")
    print("-" * 60)
    try:
        if len(train_data) >= 20:  # Need minimum samples
            print("   Training Random Forest classifier...")
            model, scaler, label_encoder, accuracy = train_classifier(
                train_data, train_labels, model_type='random_forest'
            )
            print(f"   Training completed with validation accuracy: {accuracy:.4f}")
            
            # Evaluate on test set if available
            if len(test_data) > 0:
                print("   Evaluating on test set...")
                results = evaluate_model(model, scaler, label_encoder, test_data, test_labels)
                print(f"   Test accuracy: {results['accuracy']:.4f}")
            
            # Save model
            print("   Saving model...")
            save_model(model, scaler, label_encoder)
            print()
        else:
            print("   Not enough training samples (need at least 20)")
            print()
    except Exception as e:
        print(f"   Error: {e}")
        print()
    
    print("=" * 60)
    print("Example usage completed!")
    print("=" * 60)
    print()
    print("For more examples, see:")
    print("  - examples/data_exploration.ipynb")
    print("  - README.md")
    print()
    print("Contact:")
    print("  Website: https://rskworld.in")
    print("  Email: help@rskworld.in")
    print("  Phone: +91 93305 39277")


if __name__ == '__main__':
    main()

147 lines•5 KB
python
create_sample_data.py
Raw Download
Find: Go to:
"""
Create Sample Dataset Structure and Metadata

Project: Environmental Sound Dataset
Website: https://rskworld.in
Founded by: Molla Samser
Designer & Tester: Rima Khatun
Email: help@rskworld.in
Phone: +91 93305 39277
"""

import os
import numpy as np
import soundfile as sf
import librosa
from pathlib import Path


def create_sample_audio(filename: str, duration: float = 2.0, sample_rate: int = 22050, 
                        frequency: float = 440.0, noise_level: float = 0.1):
    """
    Create a sample audio file with a simple tone.
    
    Args:
        filename: Output filename
        duration: Duration in seconds
        sample_rate: Sample rate
        frequency: Tone frequency in Hz
        noise_level: Noise level (0-1)
    """
    t = np.linspace(0, duration, int(sample_rate * duration))
    
    # Generate tone
    audio = np.sin(2 * np.pi * frequency * t)
    
    # Add some harmonics for more realistic sound
    audio += 0.3 * np.sin(2 * np.pi * frequency * 2 * t)
    audio += 0.1 * np.sin(2 * np.pi * frequency * 3 * t)
    
    # Add noise
    noise = np.random.randn(len(audio)) * noise_level
    audio = audio + noise
    
    # Normalize
    audio = audio / np.max(np.abs(audio)) * 0.8
    
    # Save
    sf.write(filename, audio, sample_rate)
    return audio


def generate_dataset_structure():
    """Generate the complete dataset structure with sample files."""
    
    base_dir = 'environmental-sounds'
    
    # Define classes and their characteristics
    classes = {
        'bird': {'freq': 2000, 'noise': 0.05},
        'car': {'freq': 200, 'noise': 0.2},
        'dog': {'freq': 500, 'noise': 0.1},
        'rain': {'freq': 100, 'noise': 0.3},
        'wind': {'freq': 50, 'noise': 0.4}
    }
    
    # Create directories
    for split in ['train', 'test']:
        for class_name in classes.keys():
            dir_path = os.path.join(base_dir, split, class_name)
            os.makedirs(dir_path, exist_ok=True)
    
    print("Created dataset directory structure")
    
    # Generate sample audio files
    metadata = []
    
    for split in ['train', 'test']:
        n_samples = 10 if split == 'train' else 3  # More training samples
        
        for class_name, params in classes.items():
            for i in range(n_samples):
                filename = f"{class_name}_{i+1:03d}.wav"
                filepath = os.path.join(base_dir, split, class_name, filename)
                
                # Vary duration slightly
                duration = np.random.uniform(1.5, 3.0)
                
                # Create sample audio
                audio = create_sample_audio(
                    filepath,
                    duration=duration,
                    frequency=params['freq'] * np.random.uniform(0.8, 1.2),
                    noise_level=params['noise']
                )
                
                # Add to metadata
                metadata.append({
                    'filename': filename,
                    'filepath': filepath,
                    'class': class_name,
                    'split': split,
                    'duration': duration,
                    'sample_rate': 22050,
                    'n_samples': len(audio)
                })
                
                print(f"Created: {filepath}")
    
    # Save metadata
    import pandas as pd
    df = pd.DataFrame(metadata)
    metadata_path = os.path.join(base_dir, 'metadata.csv')
    df.to_csv(metadata_path, index=False)
    print(f"\nMetadata saved to: {metadata_path}")
    print(f"Total files created: {len(metadata)}")
    print(f"  - Training: {len(df[df['split'] == 'train'])}")
    print(f"  - Test: {len(df[df['split'] == 'test'])}")
    
    return metadata


if __name__ == '__main__':
    print("Generating sample dataset...")
    print("=" * 50)
    
    try:
        metadata = generate_dataset_structure()
        print("\n" + "=" * 50)
        print("Sample dataset generation completed!")
        print("\nNote: These are simple synthetic audio files for demonstration.")
        print("For real audio classification, replace with actual environmental sound recordings.")
    except Exception as e:
        print(f"Error: {e}")
        import traceback
        traceback.print_exc()

137 lines•4.3 KB
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