Surah_Ikhlas-Labeled_Dataset / prepare_dataset.py
Setya54's picture
Duplicate from MuazAhmad7/Surah_Ikhlas-Labeled_Dataset
ae5d352 verified
"""
Prepare Surah Al-Ikhlas Error Detection Dataset for Hugging Face CLI upload.
Matches each audio file with its Excel metadata and creates the proper folder structure.
"""
import os
import shutil
import pandas as pd
from pathlib import Path
# Paths
SOURCE_PATH = "/Users/muaz/Downloads/Surah Al-Ikhlas of the Holy Quran Error Detection Dataset/Dataset and Sounds"
EXCEL_PATH = os.path.join(SOURCE_PATH, "Dataset.xlsx")
AUDIO_SOURCE = os.path.join(SOURCE_PATH, "Sound recordings")
OUTPUT_PATH = "/Users/muaz/cursor/IkhlasDataset"
# Verse texts for Surah Al-Ikhlas
VERSE_TEXTS = {
1: "قُلْ هُوَ اللَّهُ أَحَدٌ",
2: "اللَّهُ الصَّمَدُ",
3: "لَمْ يَلِدْ وَلَمْ يُولَدْ",
4: "وَلَمْ يَكُن لَّهُ كُفُوًا أَحَدٌ"
}
def main():
print("=" * 60)
print("Preparing dataset for Hugging Face upload")
print("=" * 60)
# Read Excel file
print("\n1. Reading Excel file...")
df = pd.read_excel(EXCEL_PATH, sheet_name='Sheet1')
df.columns = [col.strip() for col in df.columns]
print(f" Found {len(df)} entries in Excel")
# The filename is in 'Verse location' column
df['filename'] = df['Verse location'].astype(str).str.strip()
# Create label column (0 = error, 1 = correct)
# Excel: True or False = 1 means HAS ERROR, 0 means CORRECT
df['label'] = df['True or False'].apply(lambda x: 0 if x == 1 else 1)
df['label_name'] = df['label'].apply(lambda x: 'correct' if x == 1 else 'error')
# Add verse text
df['verse_text'] = df['Verse number'].map(VERSE_TEXTS)
# Clean error columns
df['error_type'] = df['Error type'].apply(lambda x: '' if pd.isna(x) or x == 0 else str(x))
df['error_location'] = df['Error location'].apply(lambda x: '' if pd.isna(x) or x == 0 else str(x))
df['error_explanation'] = df['Error explanation'].apply(lambda x: '' if pd.isna(x) or x == 0 else str(x))
df['error_count'] = df['Error number'].fillna(0).astype(int)
# Verify files exist
print("\n2. Verifying audio files...")
audio_files_on_disk = set(os.listdir(AUDIO_SOURCE))
df['file_exists'] = df['filename'].isin(audio_files_on_disk)
missing = df[~df['file_exists']]
if len(missing) > 0:
print(f" WARNING: {len(missing)} files in Excel not found on disk:")
for f in missing['filename'].head(5):
print(f" - {f}")
matched = df[df['file_exists']]
print(f" Matched {len(matched)} files")
# Check for audio files not in Excel
excel_files = set(df['filename'])
extra_files = audio_files_on_disk - excel_files
if extra_files:
print(f" Note: {len(extra_files)} audio files on disk not in Excel")
# Create output directory structure
print("\n3. Creating output directory structure...")
data_dir = os.path.join(OUTPUT_PATH, "data")
os.makedirs(data_dir, exist_ok=True)
# Copy audio files to data directory
print("\n4. Copying audio files...")
for i, row in matched.iterrows():
src = os.path.join(AUDIO_SOURCE, row['filename'])
dst = os.path.join(data_dir, row['filename'])
if not os.path.exists(dst):
shutil.copy2(src, dst)
print(f" Copied {len(matched)} audio files to {data_dir}")
# Create metadata CSV (HuggingFace convention)
print("\n5. Creating metadata.csv...")
metadata = matched[['filename', 'label', 'label_name', 'Verse number', 'verse_text',
'error_type', 'error_location', 'error_explanation', 'error_count']].copy()
metadata.columns = ['file_name', 'label', 'label_name', 'verse_number', 'verse_text',
'error_type', 'error_location', 'error_explanation', 'error_count']
# Add file path relative to data folder
metadata['file_name'] = 'data/' + metadata['file_name']
metadata_path = os.path.join(OUTPUT_PATH, "metadata.csv")
metadata.to_csv(metadata_path, index=False, encoding='utf-8')
print(f" Saved metadata to {metadata_path}")
# Print statistics
print("\n" + "=" * 60)
print("Dataset Statistics")
print("=" * 60)
print(f"\nTotal samples: {len(matched)}")
print(f"\nLabel distribution:")
print(f" Error: {len(matched[matched['label'] == 0])} samples")
print(f" Correct: {len(matched[matched['label'] == 1])} samples")
print(f"\nVerse distribution:")
for v in sorted(matched['Verse number'].unique()):
count = len(matched[matched['Verse number'] == v])
print(f" Verse {v}: {count} samples")
# Create README
print("\n6. Creating README.md...")
create_readme(OUTPUT_PATH, len(matched), matched)
print("\n" + "=" * 60)
print("DONE! Dataset is ready for upload.")
print("=" * 60)
print(f"""
Files created in {OUTPUT_PATH}:
- data/ (folder with {len(matched)} audio files)
- metadata.csv (labels and metadata for each audio)
- README.md (dataset card)
Next steps to upload to Hugging Face:
1. Install Hugging Face CLI:
brew install huggingface-cli
2. Login to Hugging Face:
huggingface-cli login
3. Upload the dataset:
cd {OUTPUT_PATH}
huggingface-cli upload MuazAhmad7/Surah_Ikhlas-Labeled_Dataset . --repo-type=dataset
""")
def create_readme(output_path, total_samples, df):
"""Create README.md dataset card."""
error_count = len(df[df['label'] == 0])
correct_count = len(df[df['label'] == 1])
readme = f"""---
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<n<10K
---
# Surah Al-Ikhlas Quran Recitation Error Detection Dataset
## Dataset Description
This dataset contains audio recordings of Quran recitations of **Surah Al-Ikhlas** (Chapter 112 - The Sincerity) with labels indicating whether each recitation contains errors in Tajweed (Quran recitation rules).
### Dataset Summary
| Statistic | Value |
|-----------|-------|
| **Total Samples** | {total_samples:,} |
| **Error Recitations** | {error_count} ({100*error_count/total_samples:.1f}%) |
| **Correct Recitations** | {correct_count} ({100*correct_count/total_samples:.1f}%) |
| **Verses** | 4 |
| **Audio Format** | WAV |
| **Language** | Arabic |
### Surah Al-Ikhlas Text
| Verse | Arabic | Transliteration | Translation |
|-------|--------|-----------------|-------------|
| 1 | قُلْ هُوَ اللَّهُ أَحَدٌ | Qul huwa Allahu ahad | Say, "He is Allah, [who is] One" |
| 2 | اللَّهُ الصَّمَدُ | Allahu assamad | "Allah, the Eternal Refuge" |
| 3 | لَمْ يَلِدْ وَلَمْ يُولَدْ | Lam yalid walam yulad | "He neither begets nor is born" |
| 4 | وَلَمْ يَكُن لَّهُ كُفُوًا أَحَدٌ | Walam yakun lahu kufuwan ahad | "Nor is there to Him any equivalent" |
## Dataset Structure
### Files
- `data/` - Folder containing all WAV audio files
- `metadata.csv` - CSV file with labels and metadata for each audio file
### Metadata Fields
| Field | Type | Description |
|-------|------|-------------|
| `file_name` | string | Path to audio file (e.g., `data/ID1V1F.wav`) |
| `label` | int | Binary label: 0 = error, 1 = correct |
| `label_name` | string | Label as text: "error" or "correct" |
| `verse_number` | int | Verse number (1-4) |
| `verse_text` | string | Arabic text of the verse |
| `error_type` | string | Type of Tajweed error (Arabic, if applicable) |
| `error_location` | string | Location of error in the verse |
| `error_explanation` | string | Explanation of the error (Arabic) |
| `error_count` | int | Error category number |
### File Naming Convention
Audio files follow the pattern: `ID{{participant}}V{{verse}}{{T/F}}.wav`
- `ID` prefix followed by participant number
- `V` followed by verse number (1-4)
- `T` = True (correct recitation) / `F` = False (contains error)
## Usage
```python
from datasets import load_dataset
# Load the dataset
dataset = load_dataset("MuazAhmad7/Surah_Ikhlas-Labeled_Dataset")
# Access the data
for sample in dataset['train']:
print(f"File: {{sample['file_name']}}")
print(f"Label: {{sample['label_name']}}")
print(f"Verse: {{sample['verse_number']}}")
break
```
### Loading Audio
```python
import pandas as pd
from datasets import Dataset, Audio
# Load metadata
df = pd.read_csv("metadata.csv")
# Create dataset with audio
dataset = Dataset.from_pandas(df)
dataset = dataset.cast_column("file_name", Audio(sampling_rate=16000))
```
## Applications
This dataset can be used for:
- 🎯 Training audio classification models for Tajweed error detection
- 📱 Building Quran recitation assessment applications
- 🔬 Research in Arabic speech processing
- 📚 Educational tools for learning proper Quran recitation
- 🤖 Developing AI-assisted Quran tutoring systems
## Error Types
The dataset includes various Tajweed errors including:
- Errors in Qalqalah (قلقلة) - echoing/bouncing sounds
- Errors in letter pronunciation
- Errors in elongation (Madd)
- And other Tajweed rule violations
## License
This dataset is released under the [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) license.
"""
readme_path = os.path.join(output_path, "README.md")
with open(readme_path, 'w', encoding='utf-8') as f:
f.write(readme)
print(f" Saved README to {readme_path}")
if __name__ == "__main__":
main()