AhmedTamertechno1's picture
Initial upload: PHONEME_TIMINGS_EACH_RECITER dataset (part 7)
c6556f2 verified
Raw History Blame Contribute Delete
7.03 kB
import os
import sys
import glob
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
sys.stdout.reconfigure(encoding='utf-8')
BASE_DIR = r"c:\Users\ahmed\.gemini\antigravity\scratch\Allignments\PHONEME_TIMINGS_EACH_RECITER"
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 main():
print("=" * 60)
print("Updating Phase 3 with Custom Rules for Long Vowels (a:, i:, u:)")
print("=" * 60)
pooled_csv_path = os.path.join(BASE_DIR, "all_reciters_phase3_pooled_tokens.csv")
master_df = pd.read_csv(pooled_csv_path)
unique_phones = sorted(master_df['phone'].dropna().unique())
summary_rows = []
plots_dir = os.path.join(BASE_DIR, "Phase3_Unified_Plots")
os.makedirs(plots_dir, exist_ok=True)
for phone in unique_phones:
phone_str = str(phone)
sub = master_df[master_df['phone'] == phone]
t_ms = sub['duration_norm_ms'].values
n_samples = len(t_ms)
if n_samples == 0:
continue
p1_ms = np.percentile(t_ms, 1.0)
p2_5_ms = np.percentile(t_ms, 2.5)
q1_ms = np.percentile(t_ms, 25.0)
med_ms = np.median(t_ms)
q3_ms = np.percentile(t_ms, 75.0)
p97_5_ms = np.percentile(t_ms, 97.5)
p99_ms = np.percentile(t_ms, 99.0)
mean_ms = np.mean(t_ms)
std_ms = np.std(t_ms)
raw_min_ms = np.min(t_ms)
raw_max_ms = np.max(t_ms)
# APPLY CUSTOM USER RULES (Option A):
# 1. For a: no upper outlier filtering (use raw_max_ms)
if phone_str == 'a:':
p99_ms = raw_max_ms
p97_5_ms = raw_max_ms
# 2. For i: stop at P90 (3726.6 ms)
elif phone_str == 'i:':
p99_ms = np.percentile(t_ms, 90.0)
p97_5_ms = np.percentile(t_ms, 88.0)
# 3. For u: stop at P97 (3828.0 ms)
elif phone_str == 'u:':
p99_ms = np.percentile(t_ms, 97.0)
p97_5_ms = np.percentile(t_ms, 95.0)
p1_sec = p1_ms / 1000.0
p2_5_sec = p2_5_ms / 1000.0
q1_sec = q1_ms / 1000.0
med_sec = med_ms / 1000.0
q3_sec = q3_ms / 1000.0
p97_5_sec = p97_5_ms / 1000.0
p99_sec = p99_ms / 1000.0
mean_sec = mean_ms / 1000.0
std_sec = std_ms / 1000.0
raw_min_sec = raw_min_ms / 1000.0
raw_max_sec = raw_max_ms / 1000.0
summary_rows.append({
'phone': phone_str,
'total_tokens': n_samples,
'min_valid_p1_ms': round(p1_ms, 1),
'min_conservative_p2_5_ms': round(p2_5_ms, 1),
'q1_ms': round(q1_ms, 1),
'median_ms': round(med_ms, 1),
'mean_ms': round(mean_ms, 1),
'std_ms': round(std_ms, 1),
'q3_ms': round(q3_ms, 1),
'max_conservative_p97_5_ms': round(p97_5_ms, 1),
'max_valid_p99_ms': round(p99_ms, 1),
'raw_min_ms': round(raw_min_ms, 1),
'raw_max_ms': round(raw_max_ms, 1),
'min_valid_p1_sec': round(p1_sec, 3),
'min_conservative_p2_5_sec': round(p2_5_sec, 3),
'q1_sec': round(q1_sec, 3),
'median_sec': round(med_sec, 3),
'mean_sec': round(mean_sec, 3),
'std_sec': round(std_sec, 3),
'q3_sec': round(q3_sec, 3),
'max_conservative_p97_5_sec': round(p97_5_sec, 3),
'max_valid_p99_sec': round(p99_sec, 3),
'raw_min_sec': round(raw_min_sec, 3),
'raw_max_sec': round(raw_max_sec, 3)
})
fig, ax = plt.subplots(figsize=(9, 5.5), dpi=120)
plot_upper_limit = p99_ms * 1.2 if p99_ms > 0 else raw_max_ms
t_ms_clipped = t_ms[t_ms <= plot_upper_limit]
counts, bins, patches = ax.hist(
t_ms_clipped,
bins=40,
color='#1d3557',
edgecolor='white',
alpha=0.75,
label=f'Unified Tokens (N={n_samples:,})'
)
ax.axvline(med_ms, color='#e63946', linestyle='-', linewidth=2.2, label=f'Median: {med_ms:.1f} ms')
ax.axvline(mean_ms, color='#9b5de5', linestyle='--', linewidth=1.5, label=f'Mean: {mean_ms:.1f} ms')
ax.axvline(p1_ms, color='#2a9d8f', linestyle='-.', linewidth=1.8, label=f'Min Valid (P1): {p1_ms:.1f} ms')
ax.axvline(p99_ms, color='#e76f51', linestyle='-.', linewidth=1.8, label=f'Max Valid: {p99_ms:.1f} ms')
ax.axvline(q1_ms, color='#457b9d', linestyle=':', linewidth=1.4, label=f'Q1 (P25): {q1_ms:.1f} ms')
ax.axvline(q3_ms, color='#457b9d', linestyle=':', linewidth=1.4, label=f'Q3 (P75): {q3_ms:.1f} ms')
ax.axvspan(q1_ms, q3_ms, color='#a8dadc', alpha=0.25, label='Core Tier [Q1 - Q3]')
ax.set_title(f"Phase 3: Unified Duration Distribution for Phoneme [{phone_str}]\n(Pooled Across All 7 Imams | N = {n_samples:,} samples)",
fontsize=11, fontweight='bold', pad=10)
ax.set_xlabel("Normalized Duration (ms)", fontsize=10, fontweight='bold')
ax.set_ylabel("Token Count", fontsize=10, fontweight='bold')
ax.grid(axis='y', alpha=0.3, linestyle='--')
info_text = (
f"Phoneme: [{phone_str}]\n"
f"Samples: {n_samples:,}\n"
f"Valid Min: {p1_ms:.1f} ms\n"
f"Median: {med_ms:.1f} ms\n"
f"Valid Max: {p99_ms:.1f} ms\n"
f"Mean +/- Std: {mean_ms:.1f} +/- {std_ms:.1f} ms"
)
ax.text(0.97, 0.95, info_text, transform=ax.transAxes, fontsize=8.5,
verticalalignment='top', horizontalalignment='right',
bbox=dict(boxstyle='round,pad=0.5', facecolor='whitesmoke', edgecolor='#adb5bd', alpha=0.9))
ax.legend(loc='upper left', fontsize=8, framealpha=0.9)
fig.tight_layout()
safe_name = sanitize_filename(phone_str)
plot_out = os.path.join(plots_dir, f"{safe_name}_unified_histogram.png")
if os.path.exists(plot_out):
try:
os.remove(plot_out)
except Exception:
pass
try:
fig.savefig(plot_out)
except Exception as e:
import time
time.sleep(0.1)
fig.savefig(plot_out)
plt.close(fig)
summary_df = pd.DataFrame(summary_rows)
master_csv_path = os.path.join(BASE_DIR, "phase3_unified_phoneme_timings.csv")
summary_df.to_csv(master_csv_path, index=False, encoding='utf-8-sig')
print(f"\nPhase 3 Master Timing Table updated: {master_csv_path}")
print("Done!")
if __name__ == '__main__':
main()