File size: 9,890 Bytes
c6556f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import os
import sys
import glob
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

# Ensure UTF-8 output
sys.stdout.reconfigure(encoding='utf-8')

BASE_DIR = r"c:\Users\ahmed\.gemini\antigravity\scratch\Allignments\PHONEME_TIMINGS_EACH_RECITER"

# Safe filename conversion for Windows filesystem
def sanitize_filename(name):
    replacements = {
        ':': '_colon_',
        '/': '_slash_',
        '\\': '_bslash_',
        '*': '_star_',
        '?': '_qmark_',
        '"': '_quote_',
        '<': '_lt_',
        '>': '_gt_',
        '|': '_pipe_'
    }
    s = str(name)
    for char, rep in replacements.items():
        s = s.replace(char, rep)
    return s

def get_filtered_tokens(csv_path):
    df = pd.read_csv(csv_path)
    df = df[df['duration'] > 0].copy()
    filtered_records = []
    
    unique_phones = sorted(df['phone'].dropna().unique())
    for phone in unique_phones:
        sub_df = df[df['phone'] == phone].copy()
        t_raw = sub_df['duration'].values
        if len(t_raw) == 0:
            continue
            
        y_log = np.log(t_raw)
        q25 = np.percentile(y_log, 25)
        q75 = np.percentile(y_log, 75)
        iqr = q75 - q25
        lower_log = q25 - 1.5 * iqr
        upper_log = q75 + 1.5 * iqr
        
        valid_mask = (y_log >= lower_log) & (y_log <= upper_log)
        sub_df_filtered = sub_df[valid_mask].copy()
        filtered_records.append(sub_df_filtered)
        
    return pd.concat(filtered_records, ignore_index=True)

def main():
    print("==================================================")
    print("Starting Phase 2: Tempo Normalization against Husary (and Ayman Sowaid for 3 rare tokens)")
    print("==================================================")
    
    csv_files = glob.glob(os.path.join(BASE_DIR, "*_phoneme_timestamps.csv"))
    reciter_data = {}
    
    for f in csv_files:
        reciter_name = os.path.basename(f).replace('_phoneme_timestamps.csv', '')
        print(f"Loading & filtering Phase 1 data for: {reciter_name}")
        reciter_data[reciter_name] = get_filtered_tokens(f)
        
    # Get all unique phonemes across all datasets
    all_phones = sorted(list(set().union(*[df['phone'].unique() for df in reciter_data.values()])))
    print(f"\nTotal Unique Phonemes across all datasets: {len(all_phones)}")
    
    # 3 missing tokens in Husary
    rare_tokens = {'dˤdˤ', 'xx', 'ħħ'}
    print(f"Special reference tokens (using Ayman Sowaid): {rare_tokens}")
    
    # 1. Compute Reference Medians
    reference_medians = {}
    reference_reciter_map = {}
    
    for p in all_phones:
        if p in rare_tokens or p not in reciter_data['Husary']['phone'].values:
            ref_reciter = 'Ayman_Sowaid'
        else:
            ref_reciter = 'Husary'
            
        ref_df = reciter_data[ref_reciter]
        sub = ref_df[ref_df['phone'] == p]
        ref_med = sub['duration'].median()
        reference_medians[p] = ref_med
        reference_reciter_map[p] = ref_reciter
        
    # 2. Compute Scaling Factor Matrix S(R, p)
    scaling_rows = []
    normalized_reciter_data = {}
    
    for reciter, df in reciter_data.items():
        df_norm = df.copy()
        df_norm['scale_factor'] = 1.0
        df_norm['duration_norm'] = df_norm['duration']
        
        for p in df['phone'].unique():
            ref_reciter = reference_reciter_map[p]
            ref_med = reference_medians[p]
            
            sub_mask = (df['phone'] == p)
            reciter_med = df.loc[sub_mask, 'duration'].median()
            
            if reciter == ref_reciter or reciter_med == 0 or np.isnan(reciter_med):
                scale = 1.0
            else:
                scale = ref_med / reciter_med
                
            df_norm.loc[sub_mask, 'scale_factor'] = scale
            df_norm.loc[sub_mask, 'duration_norm'] = df.loc[sub_mask, 'duration'] * scale
            
            scaling_rows.append({
                'reciter': reciter,
                'phone': p,
                'reference_reciter': ref_reciter,
                'reference_median_ms': round(ref_med * 1000, 2),
                'original_median_ms': round(reciter_med * 1000, 2),
                'scale_factor': round(scale, 4)
            })
            
        normalized_reciter_data[reciter] = df_norm
        
        # Save normalized dataset for this reciter
        reciter_dir = os.path.join(BASE_DIR, reciter)
        out_csv = os.path.join(reciter_dir, f"{reciter}_phase2_normalized.csv")
        df_norm.to_csv(out_csv, index=False, encoding='utf-8-sig')
        print(f"Saved normalized tokens for {reciter} -> {out_csv}")
        
    scaling_df = pd.DataFrame(scaling_rows)
    scaling_csv_path = os.path.join(BASE_DIR, "phase2_scaling_factors.csv")
    scaling_df.to_csv(scaling_csv_path, index=False, encoding='utf-8-sig')
    print(f"\nScaling factor matrix saved to: {scaling_csv_path}")
    
    # 3. Compute Phase 2 Post-Normalization Summary Statistics
    summary_rows = []
    for reciter, df in normalized_reciter_data.items():
        for p in sorted(df['phone'].unique()):
            sub = df[df['phone'] == p]
            t_raw = sub['duration'].values * 1000
            t_norm = sub['duration_norm'].values * 1000
            
            summary_rows.append({
                'reciter': reciter,
                'phone': p,
                'reference_used': reference_reciter_map[p],
                'scale_factor': round(sub['scale_factor'].iloc[0], 4),
                'count': len(sub),
                'raw_median_ms': round(np.median(t_raw), 1),
                'norm_median_ms': round(np.median(t_norm), 1),
                'raw_mean_ms': round(np.mean(t_raw), 1),
                'norm_mean_ms': round(np.mean(t_norm), 1),
                'norm_min_ms': round(np.min(t_norm), 1),
                'norm_max_ms': round(np.max(t_norm), 1),
                'norm_std_ms': round(np.std(t_norm), 1),
                'norm_min_sec': round(np.min(t_norm) / 1000.0, 4),
                'norm_max_sec': round(np.max(t_norm) / 1000.0, 4),
                'norm_mean_sec': round(np.mean(t_norm) / 1000.0, 4),
                'norm_median_sec': round(np.median(t_norm) / 1000.0, 4)
            })
            
    summary_df = pd.DataFrame(summary_rows)
    summary_csv_path = os.path.join(BASE_DIR, "all_reciters_phase2_summary.csv")
    summary_df.to_csv(summary_csv_path, index=False, encoding='utf-8-sig')
    print(f"Master Phase 2 summary saved to: {summary_csv_path}")
    
    # 4. Generate Comparative Multi-Reciter Plots (Before vs. After Normalization)
    plots_dir = os.path.join(BASE_DIR, "Phase2_Comparative_Plots")
    os.makedirs(plots_dir, exist_ok=True)
    
    color_palette = {
        'Husary': '#d90429',             # Bold Red (Primary Ref)
        'Ayman_Sowaid': '#7209b7',       # Purple (Secondary Ref)
        'Abdullah_Basfar': '#2b5c8f',    # Deep Blue
        'Abu_Bakr_Ash-Shaatree': '#0077b6',# Blue
        'Alafasy': '#0096c7',            # Cyan-Blue
        'Ghamadi': '#48cae4',            # Light Blue
        'Maher_AlMuaiqly': '#f77f00'     # Orange
    }
    
    print(f"\nGenerating 70 Phase 2 Comparative Visualizations in {plots_dir}...")
    
    for phone in all_phones:
        phone_str = str(phone)
        safe_phone = sanitize_filename(phone_str)
        ref_reciter = reference_reciter_map[phone]
        ref_med_ms = reference_medians[phone] * 1000.0
        
        fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8), dpi=100)
        
        # Upper Subplot: Raw Filtered Durations (Before Tempo Normalization)
        for reciter, df in reciter_data.items():
            sub = df[df['phone'] == phone]
            if len(sub) > 0:
                t_ms = sub['duration'].values * 1000.0
                ax1.hist(t_ms, bins=30, density=True, alpha=0.35, 
                         color=color_palette.get(reciter, 'gray'),
                         label=f"{reciter} (Med: {np.median(t_ms):.0f} ms)")
                
        ax1.set_title(f"Phase 2: Before Tempo Normalization | Phoneme [{phone_str}]\n(Different Imams Reciting at Varying Speeds)", fontsize=11, fontweight='bold')
        ax1.set_xlabel("Raw Filtered Duration (ms)")
        ax1.set_ylabel("Probability Density (PDF)")
        ax1.grid(axis='y', alpha=0.3)
        ax1.legend(loc='upper right', fontsize=8, framealpha=0.85)
        
        # Lower Subplot: Normalized Durations (Aligned to Reference Timeline)
        for reciter, df in normalized_reciter_data.items():
            sub = df[df['phone'] == phone]
            if len(sub) > 0:
                t_norm_ms = sub['duration_norm'].values * 1000.0
                lw = 2.0 if reciter == ref_reciter else 1.0
                ax2.hist(t_norm_ms, bins=30, density=True, alpha=0.35,
                         color=color_palette.get(reciter, 'gray'),
                         label=f"{reciter} (Norm Med: {np.median(t_norm_ms):.0f} ms)")
                
        ax2.axvline(ref_med_ms, color='black', linestyle='--', linewidth=1.8, label=f"Ref Baseline [{ref_reciter}]: {ref_med_ms:.0f} ms")
        ax2.set_title(f"Phase 2: After Median-Ratio Normalization to [{ref_reciter}] | Phoneme [{phone_str}]\n(All 7 Imams Perfectly Tempo-Aligned)", fontsize=11, fontweight='bold')
        ax2.set_xlabel("Normalized Duration (ms)")
        ax2.set_ylabel("Probability Density (PDF)")
        ax2.grid(axis='y', alpha=0.3)
        ax2.legend(loc='upper right', fontsize=8, framealpha=0.85)
        
        fig.tight_layout()
        plot_path = os.path.join(plots_dir, f"{safe_phone}_normalization_comparison.png")
        fig.savefig(plot_path)
        plt.close(fig)
        
    print(f"All 70 comparative plots generated successfully!")
    print("Phase 2 complete.")

if __name__ == '__main__':
    main()