File size: 11,550 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
240
241
242
243
244
245
246
247
248
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()