""" Script to prepare and upload Surah Al-Ikhlas Error Detection Dataset to Hugging Face. Dataset: Audio recordings of Quran recitations with error labels - 1506 WAV files - Labels encoded in filename: ID{participant}V{verse}{T/F} - T = True (correct recitation) - F = False (contains error) """ import os import re import pandas as pd from pathlib import Path from datasets import Dataset, Audio, Features, Value, ClassLabel import json # Paths DATASET_PATH = "/Users/muaz/Downloads/Surah Al-Ikhlas of the Holy Quran Error Detection Dataset/Dataset and Sounds" EXCEL_PATH = os.path.join(DATASET_PATH, "Dataset.xlsx") AUDIO_PATH = os.path.join(DATASET_PATH, "Sound recordings") OUTPUT_PATH = "/Users/muaz/cursor/IkhlasDataset" # Verse texts for Surah Al-Ikhlas VERSE_TEXTS = { 1: "قُلْ هُوَ اللَّهُ أَحَدٌ", 2: "اللَّهُ الصَّمَدُ", 3: "لَمْ يَلِدْ وَلَمْ يُولَدْ", 4: "وَلَمْ يَكُن لَّهُ كُفُوًا أَحَدٌ" } def parse_filename(filename): """Parse filename like 'ID100V1F.wav' to extract components.""" match = re.match(r'ID(\d+)V(\d)([TF])\.wav', filename) if match: return { 'participant_id': int(match.group(1)), 'verse': int(match.group(2)), 'is_correct': match.group(3) == 'T', 'label': 1 if match.group(3) == 'T' else 0, 'label_text': 'correct' if match.group(3) == 'T' else 'error' } return None def load_and_prepare_data(): """Load audio files and Excel metadata.""" print("=" * 60) print("Loading and preparing dataset...") print("=" * 60) # Get all audio files audio_files = list(Path(AUDIO_PATH).glob("*.wav")) print(f"\nFound {len(audio_files)} audio files") # Parse all filenames to extract labels data = [] for audio_file in audio_files: parsed = parse_filename(audio_file.name) if parsed: parsed['filename'] = audio_file.name parsed['audio_path'] = str(audio_file) data.append(parsed) df = pd.DataFrame(data) print(f"Parsed {len(df)} files successfully") # Load Excel for additional metadata print("\nLoading Excel metadata...") excel_df = pd.read_excel(EXCEL_PATH, sheet_name='Sheet1') excel_df.columns = [col.strip() for col in excel_df.columns] # Sort both dataframes to align df = df.sort_values(['participant_id', 'verse']).reset_index(drop=True) # Add verse text df['verse_text'] = df['verse'].map(VERSE_TEXTS) # Since the Excel has 1506 rows and we have 1506 files, try direct assignment if len(df) == len(excel_df): excel_df = excel_df.reset_index(drop=True) # Add error information from Excel df['error_type'] = excel_df['Error type'].apply(lambda x: '' if x == 0 or pd.isna(x) else str(x)) df['error_location'] = excel_df['Error location'].apply(lambda x: '' if x == 0 or pd.isna(x) else str(x)) df['error_explanation'] = excel_df['Error explanation'].apply(lambda x: '' if x == 0 or pd.isna(x) else str(x)) df['error_count'] = excel_df['Error number'].fillna(0).astype(int) print("Merged Excel metadata successfully!") else: df['error_type'] = '' df['error_location'] = '' df['error_explanation'] = '' df['error_count'] = 0 print(f"Warning: Excel rows ({len(excel_df)}) don't match audio files ({len(df)})") print(f"\nLabel distribution:") print(df['label_text'].value_counts()) print(f"\nVerse distribution:") print(df['verse'].value_counts().sort_index()) print(f"\nUnique participants: {df['participant_id'].nunique()}") return df def create_hf_dataset(df): """Create Hugging Face dataset from DataFrame.""" print("\n" + "=" * 60) print("Creating Hugging Face dataset...") print("=" * 60) # Prepare data for dataset - audio column will contain file paths data = { 'audio': df['audio_path'].tolist(), 'label': df['label'].tolist(), 'participant_id': df['participant_id'].tolist(), 'verse_number': df['verse'].tolist(), 'verse_text': df['verse_text'].tolist(), 'error_type': df['error_type'].tolist(), 'error_location': df['error_location'].tolist(), 'error_explanation': df['error_explanation'].tolist(), 'error_count': df['error_count'].tolist(), } # Create dataset without audio feature first dataset = Dataset.from_dict(data) # Cast label to ClassLabel dataset = dataset.cast_column('label', ClassLabel(names=['error', 'correct'])) # Cast audio column (this will load audio lazily) dataset = dataset.cast_column('audio', Audio(sampling_rate=16000)) # Create train/test split (80/20) stratified by label dataset = dataset.train_test_split(test_size=0.2, seed=42, stratify_by_column='label') print(f"\nDataset created:") print(f" Train: {len(dataset['train'])} samples") print(f" Test: {len(dataset['test'])} samples") # Show label distribution in splits train_labels = dataset['train']['label'] test_labels = dataset['test']['label'] print(f"\n Train label distribution: error={train_labels.count(0)}, correct={train_labels.count(1)}") print(f" Test label distribution: error={test_labels.count(0)}, correct={test_labels.count(1)}") return dataset def create_dataset_card(): """Create README.md for the dataset.""" readme_content = """--- license: cc-by-4.0 task_categories: - audio-classification language: - ar tags: - quran - tajweed - recitation - error-detection - arabic - audio - speech - islam pretty_name: Surah Al-Ikhlas Quran Recitation Error Detection Dataset size_categories: - 1K