File size: 5,909 Bytes
add8e69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#!/usr/bin/env python3
"""
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]
            
            # Granule position in Opus is ALWAYS at 48000 Hz
            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
    
    # Match verse files: e.g. 001001.opus (length > 3 before extension)
    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"
    
    # 1. Compute JSON and write concat file
    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)
                # Shift timings
                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
            
    # Write combined JSON
    with open(target_json, 'w') as jf:
        # Format like a compact 2D array
        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('[]')
        
    # 2. Concat Opus Losslessly using ffmpeg
    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()
            
    # 3. Clean up verse-level files if successful
    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 = []
    
    # Identify valid reciter directories
    for entry in base_dir.iterdir():
        if entry.is_dir() and not entry.name.startswith('.') and entry.name not in ('audio', 'wbw_tester', '__pycache__'):
            # Only include if it has surah directories like '001'
            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()