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()