| |
| """ |
| Quranic Recitation Surah Concatenator |
| ===================================== |
| Converts verse-level Opus and JSON files into single Surah-level files |
| for all 22 reciters. |
| |
| Output format: {reciter_slug}/{surah_id}/{surah_id}.opus |
| """ |
|
|
| import os |
| import glob |
| import json |
| import struct |
| import subprocess |
| from pathlib import Path |
| from concurrent.futures import ProcessPoolExecutor, as_completed |
| import time |
|
|
| def get_ogg_opus_duration(filepath): |
| """Fast extraction of Ogg Opus duration in milliseconds.""" |
| try: |
| with open(filepath, 'rb') as f: |
| f.seek(0, 2) |
| file_size = f.tell() |
| |
| chunk_size = min(65536, file_size) |
| f.seek(file_size - chunk_size) |
| data = f.read(chunk_size) |
| |
| last_oggs_idx = data.rfind(b'OggS') |
| if last_oggs_idx == -1: |
| return 0 |
| |
| granule_bytes = data[last_oggs_idx+6 : last_oggs_idx+14] |
| granule_position = struct.unpack('<q', granule_bytes)[0] |
| |
| |
| return int((granule_position / 48000.0) * 1000) |
| except Exception: |
| return 0 |
|
|
| def process_surah(args): |
| reciter_dir, surah_str = args |
| surah_path = Path(reciter_dir) / surah_str |
| |
| |
| all_opus = sorted(list(surah_path.glob(f"{surah_str}*.opus"))) |
| verse_opus_files = [f for f in all_opus if len(f.stem) > 3] |
| |
| if not verse_opus_files: |
| return True |
| |
| target_opus = surah_path / f"{surah_str}.opus" |
| target_json = surah_path / f"{surah_str}.json" |
| concat_txt_path = surah_path / f"concat_{surah_str}.txt" |
| |
| |
| combined_json = [] |
| cumulative_offset = 0 |
| verse_json_files = [] |
| |
| with open(concat_txt_path, 'w') as f_out: |
| for opus_f in verse_opus_files: |
| f_out.write(f"file '{opus_f.name}'\n") |
| |
| json_f = opus_f.with_suffix('.json') |
| if json_f.exists(): |
| verse_json_files.append(json_f) |
| with open(json_f, 'r') as jf: |
| data = json.load(jf) |
| |
| if isinstance(data, list): |
| for seg in data: |
| new_seg = [ |
| seg[0], |
| seg[1], |
| int(seg[2]) + cumulative_offset, |
| int(seg[3]) + cumulative_offset |
| ] |
| combined_json.append(new_seg) |
| |
| duration = get_ogg_opus_duration(opus_f) |
| cumulative_offset += duration |
| |
| |
| with open(target_json, 'w') as jf: |
| |
| if combined_json: |
| inner_strs = [json.dumps(seg) for seg in combined_json] |
| json_str = '[\n ' + ',\n '.join(inner_strs) + '\n]' |
| jf.write(json_str) |
| else: |
| jf.write('[]') |
| |
| |
| success = False |
| try: |
| subprocess.run([ |
| "ffmpeg", "-y", "-hide_banner", "-loglevel", "error", |
| "-f", "concat", "-safe", "0", |
| "-i", str(concat_txt_path), |
| "-c", "copy", |
| str(target_opus) |
| ], check=True) |
| success = True |
| except subprocess.CalledProcessError: |
| return False |
| finally: |
| if concat_txt_path.exists(): |
| concat_txt_path.unlink() |
| |
| |
| if success and target_opus.exists(): |
| for opus_f in verse_opus_files: |
| try: opus_f.unlink() |
| except: pass |
| for json_f in verse_json_files: |
| try: json_f.unlink() |
| except: pass |
| |
| return success |
|
|
| def main(): |
| print("ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ") |
| print("β Surah Concatenator β") |
| print("β Verse Opus/JSON -> Surah Opus/JSON β") |
| print("ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ") |
| |
| base_dir = Path(".") |
| reciters = [] |
| |
| |
| for entry in base_dir.iterdir(): |
| if entry.is_dir() and not entry.name.startswith('.') and entry.name not in ('audio', 'wbw_tester', '__pycache__'): |
| |
| if (entry / '001').exists(): |
| reciters.append(entry.name) |
| |
| reciters = sorted(reciters) |
| print(f"β Found {len(reciters)} reciters to process.") |
| |
| tasks = [] |
| for r in reciters: |
| for s in range(1, 115): |
| tasks.append((r, f"{s:03d}")) |
| |
| print(f"Total tasks (surahs): {len(tasks)}") |
| print(f"Starting parallel processing...") |
| |
| completed = 0 |
| errors = 0 |
| start = time.time() |
| |
| with ProcessPoolExecutor(max_workers=min(os.cpu_count() or 4, 16)) as executor: |
| futures = [executor.submit(process_surah, t) for t in tasks] |
| for f in as_completed(futures): |
| if not f.result(): |
| errors += 1 |
| completed += 1 |
| if completed % 114 == 0 or completed == len(tasks): |
| print(f" Processed {completed}/{len(tasks)} surahs... ({errors} errors)") |
| |
| elapsed = time.time() - start |
| print(f"\nβ Done! Converted {len(reciters)} reciters in {elapsed:.1f}s.") |
|
|
| if __name__ == '__main__': |
| main() |
|
|