Download Scripts/run_phase1.py from AhmedTamertechno1/Phone_Timings_Database: direct link, hf CLI and curl.
- Browser
- Download file 11.6 kB
-
https://huggingface.co/datasets/AhmedTamertechno1/Phone_Timings_Database/resolve/main/Scripts/run_phase1.py
- Command line
-
hf download hf://datasets/AhmedTamertechno1/Phone_Timings_Database/Scripts/run_phase1.py
-
curl -L -o run_phase1.py https://huggingface.co/datasets/AhmedTamertechno1/Phone_Timings_Database/resolve/main/Scripts/run_phase1.py
11.6 kB
| import os | |
| import re | |
| 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): | |
| # Replace characters not allowed in Windows filenames: \ / : * ? " < > | | |
| 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 process_reciter(csv_path): | |
| filename = os.path.basename(csv_path) | |
| reciter_name = filename.replace('_phoneme_timestamps.csv', '') | |
| print(f"==================================================") | |
| print(f"Processing Reciter: {reciter_name}") | |
| print(f"==================================================") | |
| # Create Reciter Output Directory | |
| reciter_dir = os.path.join(BASE_DIR, reciter_name) | |
| step1_dir = os.path.join(reciter_dir, "step1_raw_histograms") | |
| step2_dir = os.path.join(reciter_dir, "step2_log_histograms") | |
| step3_dir = os.path.join(reciter_dir, "step3_boxplots_filtering") | |
| step4_dir = os.path.join(reciter_dir, "step4_filtered_histograms") | |
| for d in [step1_dir, step2_dir, step3_dir, step4_dir]: | |
| os.makedirs(d, exist_ok=True) | |
| df = pd.read_csv(csv_path) | |
| # Filter valid durations (> 0) | |
| df = df[df['duration'] > 0].copy() | |
| unique_phones = sorted(df['phone'].dropna().unique()) | |
| print(f"Total Unique Phonemes for {reciter_name}: {len(unique_phones)}") | |
| stats_list = [] | |
| # Configure matplotlib style | |
| plt.rcParams.update({ | |
| 'font.size': 10, | |
| 'axes.labelsize': 11, | |
| 'axes.titlesize': 12, | |
| 'figure.titlesize': 13, | |
| 'figure.autolayout': True | |
| }) | |
| for phone in unique_phones: | |
| phone_str = str(phone) | |
| safe_phone = sanitize_filename(phone_str) | |
| sub_df = df[df['phone'] == phone] | |
| t_raw = sub_df['duration'].values | |
| n_raw = len(t_raw) | |
| if n_raw == 0: | |
| continue | |
| # Step 2: Log Transformation y = ln(t) | |
| y_log = np.log(t_raw) | |
| # Step 3: IQR Outlier Filtering in Log Space | |
| q25 = np.percentile(y_log, 25) | |
| q75 = np.percentile(y_log, 75) | |
| iqr = q75 - q25 | |
| lower_bound_log = q25 - 1.5 * iqr | |
| upper_bound_log = q75 + 1.5 * iqr | |
| # In linear space cutoff | |
| lower_bound_linear = np.exp(lower_bound_log) | |
| upper_bound_linear = np.exp(upper_bound_log) | |
| # Filter mask in log space | |
| valid_mask = (y_log >= lower_bound_log) & (y_log <= upper_bound_log) | |
| # Step 4: Inverse Transform back to Linear Time | |
| t_filtered = t_raw[valid_mask] | |
| n_filtered = len(t_filtered) | |
| n_outliers = n_raw - n_filtered | |
| outlier_ratio = (n_outliers / n_raw) * 100.0 if n_raw > 0 else 0.0 | |
| # Step 5: Compute stats after filtering | |
| if n_filtered > 0: | |
| mean_filt = np.mean(t_filtered) | |
| median_filt = np.median(t_filtered) | |
| min_filt = np.min(t_filtered) | |
| max_filt = np.max(t_filtered) | |
| std_filt = np.std(t_filtered) | |
| else: | |
| mean_filt = median_filt = min_filt = max_filt = std_filt = np.nan | |
| stats_list.append({ | |
| 'reciter': reciter_name, | |
| 'phone': phone_str, | |
| 'raw_count': n_raw, | |
| 'filtered_count': n_filtered, | |
| 'outliers_removed': n_outliers, | |
| 'outlier_ratio_pct': round(outlier_ratio, 2), | |
| 'min_sec': round(min_filt, 4) if not np.isnan(min_filt) else None, | |
| 'max_sec': round(max_filt, 4) if not np.isnan(max_filt) else None, | |
| 'mean_sec': round(mean_filt, 4) if not np.isnan(mean_filt) else None, | |
| 'median_sec': round(median_filt, 4) if not np.isnan(median_filt) else None, | |
| 'std_sec': round(std_filt, 4) if not np.isnan(std_filt) else None, | |
| 'min_ms': round(min_filt * 1000, 1) if not np.isnan(min_filt) else None, | |
| 'max_ms': round(max_filt * 1000, 1) if not np.isnan(max_filt) else None, | |
| 'mean_ms': round(mean_filt * 1000, 1) if not np.isnan(mean_filt) else None, | |
| 'median_ms': round(median_filt * 1000, 1) if not np.isnan(median_filt) else None, | |
| 'lower_bound_cutoff_ms': round(lower_bound_linear * 1000, 1), | |
| 'upper_bound_cutoff_ms': round(upper_bound_linear * 1000, 1) | |
| }) | |
| # ------------------------------------------------------------- | |
| # Plot Step 1: Raw Histogram (Linear Time) | |
| # ------------------------------------------------------------- | |
| fig, ax = plt.subplots(figsize=(6, 4), dpi=100) | |
| bins = min(50, max(10, int(np.sqrt(n_raw)))) | |
| ax.hist(t_raw * 1000, bins=bins, color='#2b5c8f', edgecolor='black', alpha=0.75) | |
| ax.set_title(f"Step 1: Raw Timing Histogram\nReciter: {reciter_name} | Phoneme: [{phone_str}] (N={n_raw})") | |
| ax.set_xlabel("Duration (ms)") | |
| ax.set_ylabel("Frequency") | |
| ax.axvline(np.mean(t_raw) * 1000, color='red', linestyle='--', linewidth=1.5, label=f"Mean: {np.mean(t_raw)*1000:.1f} ms") | |
| ax.axvline(np.median(t_raw) * 1000, color='green', linestyle=':', linewidth=1.5, label=f"Median: {np.median(t_raw)*1000:.1f} ms") | |
| ax.legend(loc='upper right') | |
| ax.grid(axis='y', alpha=0.3) | |
| fig.tight_layout() | |
| fig.savefig(os.path.join(step1_dir, f"{safe_phone}_raw_hist.png")) | |
| plt.close(fig) | |
| # ------------------------------------------------------------- | |
| # Plot Step 2: Log Transform Histogram [ln(t)] | |
| # ------------------------------------------------------------- | |
| fig, ax = plt.subplots(figsize=(6, 4), dpi=100) | |
| ax.hist(y_log, bins=bins, color='#d97724', edgecolor='black', alpha=0.75) | |
| ax.set_title(f"Step 2: Log-Transformed Histogram [ln(t)]\nReciter: {reciter_name} | Phoneme: [{phone_str}]") | |
| ax.set_xlabel("ln(Duration in seconds)") | |
| ax.set_ylabel("Frequency") | |
| ax.axvline(lower_bound_log, color='purple', linestyle='--', linewidth=1.5, label=f"IQR Lower: {lower_bound_log:.2f}") | |
| ax.axvline(upper_bound_log, color='purple', linestyle='--', linewidth=1.5, label=f"IQR Upper: {upper_bound_log:.2f}") | |
| ax.legend(loc='upper right') | |
| ax.grid(axis='y', alpha=0.3) | |
| fig.tight_layout() | |
| fig.savefig(os.path.join(step2_dir, f"{safe_phone}_log_hist.png")) | |
| plt.close(fig) | |
| # ------------------------------------------------------------- | |
| # Plot Step 3: Box Plots Before vs After Outlier Filtering | |
| # ------------------------------------------------------------- | |
| fig, (ax_box1, ax_box2) = plt.subplots(1, 2, figsize=(8, 4.5), dpi=100, sharey=False) | |
| # Left: Linear Space boxplot (Before vs After) | |
| data_to_plot = [t_raw * 1000, t_filtered * 1000] | |
| ax_box1.boxplot(data_to_plot, tick_labels=['Raw (Before)', 'Filtered (After)'], patch_artist=True, | |
| boxprops=dict(facecolor='#8ecae6', color='#023047'), | |
| medianprops=dict(color='#d90429', linewidth=2), | |
| flierprops=dict(marker='o', markersize=4, markerfacecolor='red', alpha=0.5)) | |
| ax_box1.set_ylabel("Duration (ms)") | |
| ax_box1.set_title("Linear Time (ms)") | |
| ax_box1.grid(axis='y', alpha=0.3) | |
| # Right: Log Space boxplot with IQR cutoffs | |
| ax_box2.boxplot([y_log], tick_labels=['Log Space ln(t)'], patch_artist=True, | |
| boxprops=dict(facecolor='#ffb703', color='#fb8500'), | |
| medianprops=dict(color='#023047', linewidth=2), | |
| flierprops=dict(marker='x', markersize=5, markeredgecolor='purple', alpha=0.7)) | |
| ax_box2.axhline(lower_bound_log, color='red', linestyle='--', label=f'Lower Bound ({lower_bound_log:.2f})') | |
| ax_box2.axhline(upper_bound_log, color='red', linestyle='--', label=f'Upper Bound ({upper_bound_log:.2f})') | |
| ax_box2.set_ylabel("ln(t)") | |
| ax_box2.set_title("Log Space & IQR Bounds") | |
| ax_box2.legend(loc='lower right', fontsize=8) | |
| ax_box2.grid(axis='y', alpha=0.3) | |
| fig.suptitle(f"Step 3: Outlier Filtering Comparison | [{phone_str}] ({reciter_name})\nFiltered: {n_outliers} outliers ({outlier_ratio:.1f}%)", fontsize=11) | |
| fig.tight_layout() | |
| fig.savefig(os.path.join(step3_dir, f"{safe_phone}_boxplot.png")) | |
| plt.close(fig) | |
| # ------------------------------------------------------------- | |
| # Plot Step 4: Filtered Histogram (Linear Time) | |
| # ------------------------------------------------------------- | |
| fig, ax = plt.subplots(figsize=(6, 4), dpi=100) | |
| bins_filt = min(40, max(10, int(np.sqrt(n_filtered)))) | |
| ax.hist(t_filtered * 1000, bins=bins_filt, color='#2a9d8f', edgecolor='black', alpha=0.8) | |
| ax.set_title(f"Step 4: Filtered Timing Histogram (Linear Time)\nReciter: {reciter_name} | Phoneme: [{phone_str}] (N={n_filtered})") | |
| ax.set_xlabel("Duration (ms)") | |
| ax.set_ylabel("Frequency") | |
| if n_filtered > 0: | |
| ax.axvline(mean_filt * 1000, color='#e76f51', linestyle='--', linewidth=1.5, label=f"Mean: {mean_filt*1000:.1f} ms") | |
| ax.axvline(median_filt * 1000, color='#264653', linestyle=':', linewidth=1.5, label=f"Median: {median_filt*1000:.1f} ms") | |
| ax.axvline(min_filt * 1000, color='#457b9d', linestyle='-', linewidth=1.0, label=f"Min: {min_filt*1000:.1f} ms") | |
| ax.axvline(max_filt * 1000, color='#457b9d', linestyle='-', linewidth=1.0, label=f"Max: {max_filt*1000:.1f} ms") | |
| ax.legend(loc='upper right') | |
| ax.grid(axis='y', alpha=0.3) | |
| fig.tight_layout() | |
| fig.savefig(os.path.join(step4_dir, f"{safe_phone}_filtered_hist.png")) | |
| plt.close(fig) | |
| # Save CSV Summary for this reciter | |
| stats_df = pd.DataFrame(stats_list) | |
| summary_csv_path = os.path.join(reciter_dir, f"{reciter_name}_phase1_summary.csv") | |
| stats_df.to_csv(summary_csv_path, index=False, encoding='utf-8-sig') | |
| print(f"Saved summary CSV for {reciter_name}: {summary_csv_path}") | |
| print(f"Total Phonemes processed: {len(stats_df)}") | |
| print(f"Overall average outlier ratio: {stats_df['outlier_ratio_pct'].mean():.2f}%\n") | |
| return stats_df | |
| def main(): | |
| csv_files = glob.glob(os.path.join(BASE_DIR, "*_phoneme_timestamps.csv")) | |
| print(f"Found {len(csv_files)} reciter CSVs:") | |
| for f in csv_files: | |
| print(" -", os.path.basename(f)) | |
| all_summaries = [] | |
| for csv_file in csv_files: | |
| reciter_df = process_reciter(csv_file) | |
| all_summaries.append(reciter_df) | |
| master_summary = pd.concat(all_summaries, ignore_index=True) | |
| master_csv_path = os.path.join(BASE_DIR, "all_reciters_phase1_summary.csv") | |
| master_summary.to_csv(master_csv_path, index=False, encoding='utf-8-sig') | |
| print(f"\n Master summary saved across all reciters to: {master_csv_path}") | |
| if __name__ == '__main__': | |
| main() | |