yum-slop/TaSTT

Free self-hosted STT for VRChat.

git clone https://git.yummers.dev/yum-slop/TaSTT

yumWork more on hallucination filtering6815848

v1.0.0-beta03
13.0 KiB357 linesraw
1#!/usr/bin/env python3
2import json
3import os
4import re
5from pathlib import Path
6import numpy as np
7import pandas as pd
8import pronouncing
9from sklearn.ensemble import GradientBoostingClassifier
10from sklearn.neighbors import KNeighborsClassifier
11from sklearn.preprocessing import StandardScaler
12from sklearn.pipeline import Pipeline
13from sklearn.model_selection import train_test_split
14from sklearn.metrics import classification_report, confusion_matrix
15import joblib
16import warnings
17from sklearn.model_selection import StratifiedKFold, cross_val_predict
18
19def count_syllables(word):
20    """Count syllables in a word using pronouncing library with regex fallback."""
21    phones = pronouncing.phones_for_word(word.lower())
22    return pronouncing.syllable_count(phones[0])
23
24def text_syllable_count(text):
25    """Count total syllables in text."""
26    words = re.findall(r'\b\w+\b', text)
27    return sum(count_syllables(word) for word in words)
28
29def load_segments(log_dir):
30    """Load segments from JSON files."""
31    segments = []
32    seen = set()  # To deduplicate identical segment metadata
33    num_dupes = 0
34
35    for root, dirs, files in os.walk(log_dir):
36        for file in files:
37            if not file.endswith('.json'):
38                continue
39            try:
40                with open(os.path.join(root, file), 'r') as f:
41                    data = json.load(f)
42
43                for segment in data.get('segments', []):
44                    if 'duration_sanity' not in segment:
45                        continue
46
47                    # Extract all available features
48                    text = segment.get('text', '')
49                    duration = segment.get('duration_sanity', 0)
50
51                    # Calculate raw duration from timestamps
52                    start_ts = segment.get('start_ts', 0)
53                    end_ts = segment.get('end_ts', 0)
54                    raw_duration = end_ts - start_ts
55
56                    seg_data = {
57                        'avg_logprob': segment.get('avg_logprob', 0),
58                        'no_speech_prob': segment.get('no_speech_prob', 0),
59                        'duration_sanity': duration,
60                        'raw_duration': raw_duration,
61                        'compression_ratio': segment.get('compression_ratio', 1),
62                        'text': text
63                    }
64
65                    # Add speech rate features
66                    n_syllables = text_syllable_count(text)
67                    seg_data['sps'] = n_syllables / duration
68                    seg_data['log_sps'] = np.log1p(seg_data['sps'])
69                    seg_data['raw_sps'] = n_syllables / raw_duration
70                    seg_data['log_raw_sps'] = np.log1p(seg_data['raw_sps'])
71
72                    # Add derived features
73                    seg_data['log_duration'] = np.log1p(duration)
74                    seg_data['logprob_duration_interaction'] = seg_data['avg_logprob'] * duration
75                    seg_data['log_raw_duration'] = np.log1p(raw_duration)
76                    seg_data['duration_ratio'] = raw_duration / duration if duration > 0 else 1.0
77
78                    # Deduplicate: skip if this exact metadata already seen
79                    key = tuple(sorted(seg_data.items()))
80                    if key in seen:
81                        num_dupes += 1
82                        continue
83                    seen.add(key)
84
85                    segments.append(seg_data)
86            except Exception as e:
87                print(f"Error loading {file}: {e}")
88
89    print(f"Skipped {num_dupes} duplicate segments")
90    return pd.DataFrame(segments)
91
92def log_seed_data(seeds_df, seed_type, label_desc):
93    """Log comprehensive data for seed segments."""
94    if len(seeds_df) == 0:
95        return
96
97    print(f"\n{seed_type} seeds ({label_desc}) - {len(seeds_df)} total:")
98    for i, (_, seg) in enumerate(seeds_df.head(10).iterrows(), 1):
99        print(f"  {i:3d}. SPS={seg['sps']:.2f}, Raw_SPS={seg['raw_sps']:.2f}, "
100              f"logprob={seg['avg_logprob']:.3f}, no_speech={seg['no_speech_prob']:.3f}, "
101              f"compression={seg['compression_ratio']:.2f}, duration={seg['duration_sanity']:.2f}s, "
102              f"raw_duration={seg['raw_duration']:.2f}s")
103        print(f"       Text: '{seg['text']}'")
104        print()
105
106    # Show statistics
107    print(f"\n{seed_type} seed statistics:")
108    for metric, col in [('SPS', 'sps'), ('Logprob', 'avg_logprob'), ('Compression', 'compression_ratio')]:
109        data = seeds_df[col]
110        print(f"  {metric}: mean={data.mean():.3f}, std={data.std():.3f}, min={data.min():.3f}, max={data.max():.3f}")
111
112def main():
113    # Find logs directory
114    log_dir = None
115    for pattern in ["ui/dist/logs", "logs", "ui/dist/*/logs", "ui/dist/*/*/logs", "ui/dist/*/*/*/logs"]:
116        paths = list(Path(".").glob(pattern))
117        if paths:
118            log_dir = str(paths[0])
119            break
120
121    if not log_dir:
122        print("Could not find logs directory.")
123        return
124
125    # Load data
126    print("Loading segments from logs...")
127    df = load_segments(log_dir)
128
129    if len(df) == 0:
130        print("No segments found in logs!")
131        return
132
133    print(f"Loaded {len(df)} segments")
134
135    # Print speech rate statistics
136    print("\nSpeech rate statistics:")
137    print(f"Syllables per second: mean={df['sps'].mean():.2f}, std={df['sps'].std():.2f}, max={df['sps'].max():.2f}")
138    print(f"Raw syllables per second: mean={df['raw_sps'].mean():.2f}, std={df['raw_sps'].std():.2f}, max={df['raw_sps'].max():.2f}")
139    print(f"Duration ratio (raw/sanity): mean={df['duration_ratio'].mean():.2f}, std={df['duration_ratio'].std():.2f}")
140
141    # Step 1: Apply heuristic rules for seed labeling
142    print("\nApplying heuristic rules for seed labeling...")
143
144    # Conservative positive seeds (likely hallucinations)
145    h_pos = (
146        ((df['avg_logprob'] < -0.85)          # This low of a logprob is almost always a hallucination
147        | (df['compression_ratio'] > 2.3)    # High compressibility is usually a hallucination
148        | (df['sps'] > 9))                    # No one speaks this fast
149        & df['text'].str.contains("Thank you", na=False)  # Hack. Nothing good enough to
150    )
151
152    # Conservative negative seeds (likely valid)
153    h_neg = (
154        (df['avg_logprob'] > -0.5)          # solid confidence drop
155        & (df['compression_ratio'] < 1.2)
156        & (df['sps'] < 9)
157    )
158
159    # Create seed labels (NaN for unlabeled)
160    df['seed_label'] = np.where(h_pos, 1,
161                                np.where(h_neg, 0, np.nan))
162
163    n_pos_seeds = (df['seed_label'] == 1).sum()
164    n_neg_seeds = (df['seed_label'] == 0).sum()
165    n_unlabeled = df['seed_label'].isna().sum()
166
167    print(f"Seed labeling results:")
168    print(f"  Positive seeds (hallucinations): {n_pos_seeds} ({n_pos_seeds/len(df):.1%})")
169    print(f"  Negative seeds (valid): {n_neg_seeds} ({n_neg_seeds/len(df):.1%})")
170    print(f"  Unlabeled: {n_unlabeled} ({n_unlabeled/len(df):.1%})")
171
172    if n_pos_seeds == 0 or n_neg_seeds == 0:
173        print("Warning: Not enough seed labels. Adjusting thresholds might help.")
174        return
175
176    # Log all seed data
177    pos_seeds = df[df['seed_label'] == 1]
178    neg_seeds = df[df['seed_label'] == 0]
179
180    log_seed_data(pos_seeds, "Positive", "likely hallucinations")
181    log_seed_data(neg_seeds, "Negative", "likely valid")
182
183    # Define features (trimmed to remove redundant transformations)
184    features = [
185        'avg_logprob',
186        'no_speech_prob',
187        'compression_ratio',
188        'log_duration',
189        'log_sps',
190        'log_raw_duration',
191        'log_raw_sps',
192        'duration_ratio',
193        'logprob_duration_interaction'
194    ]
195
196    X = df[features].values
197
198    # Step 2: Train kNN on seed labels
199    print("\nTraining k-NN classifier on seed labels...")
200
201    labeled_mask = df['seed_label'].notna()
202    X_seed = X[labeled_mask]
203    y_seed = df.loc[labeled_mask, 'seed_label'].values.astype(int)
204
205    # Auto-select k based on seed data size
206    n_seed_samples = len(X_seed)
207    optimal_k = min(max(int(np.sqrt(n_seed_samples)), 3), n_seed_samples // 2)
208    print(f"Using k={optimal_k} neighbors (from {n_seed_samples} seed samples)")
209
210    # Create pipeline with scaling (important for kNN)
211    knn_pipeline = Pipeline([
212        ('scale', StandardScaler()),
213        ('knn', KNeighborsClassifier(
214            n_neighbors=optimal_k,
215            weights='distance'       # closer neighbors weigh more
216        ))
217    ])
218
219    # --- step 2: train k-NN on seeds -------------------------------
220    cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
221
222    # out-of-fold probas for the seeds
223    seed_scores = cross_val_predict(
224        knn_pipeline,                # pipeline defined earlier
225        X_seed, y_seed,
226        cv=cv,
227        method="predict_proba"
228    )[:, 1]
229
230    # store the scores for thresholding
231    df.loc[labeled_mask, 'knn_score'] = seed_scores
232
233    # finally fit on the full seed set before scoring the rest
234    knn_pipeline.fit(X_seed, y_seed)
235    df.loc[~labeled_mask, 'knn_score'] = knn_pipeline.predict_proba(
236        X[~labeled_mask])[:, 1]
237
238    # --- step 2 done: kNN scores are in df['knn_score'] ---------------------
239
240    # Debug: how are the scores distributed?
241    for lbl, mask in {
242        "Positive seeds":  df['seed_label'] == 1,
243        "Negative seeds":  df['seed_label'] == 0,
244        "Un-labelled":     df['seed_label'].isna()
245    }.items():
246        scores = df.loc[mask, 'knn_score']
247        if scores.empty:
248            continue
249        print(f"{lbl:15s} | n={len(scores):4d}  min={scores.min():.3f}  "
250              f"25%={scores.quantile(.25):.3f}  median={scores.median():.3f}  "
251              f"75%={scores.quantile(.75):.3f}  max={scores.max():.3f}")
252    print()  # blank line for readability
253
254    # Step 3: derive a threshold from the seed scores
255    print("Applying threshold to segment scores...")
256
257    neg_seed_scores = df.loc[df['seed_label'] == 0, 'knn_score']
258    pos_seed_scores = df.loc[df['seed_label'] == 1, 'knn_score']
259
260    max_neg = neg_seed_scores.max()
261    min_pos = pos_seed_scores.min()
262
263    if min_pos > max_neg:
264        # clear separation – use the midpoint
265        threshold = (max_neg + min_pos) / 2
266        reason = "mid-point between max-neg and min-pos"
267    else:
268        # fallback to percentile rule, but ensure it’s >0
269        threshold = np.percentile(neg_seed_scores, 95)
270        if threshold <= 0:
271            threshold = 1e-3
272        reason = "95th percentile of negative seeds"
273
274    print(f"\nChosen threshold: {threshold:.3f}  ({reason})")
275
276    df['is_hallucination'] = (df['knn_score'] >= threshold).astype(int)
277
278    # Print results
279    n_hallucinations = df['is_hallucination'].sum()
280    print(f"\nDetected hallucinations: {n_hallucinations} ({n_hallucinations/len(df):.1%})")
281
282    # Step 4: Train final gradient boosting model on kNN labels
283    print("\nTraining final Gradient Boosting classifier...")
284
285    X_final = df[features]
286    y_final = df['is_hallucination']
287
288    # Split data
289    X_train, X_test, y_train, y_test = train_test_split(
290        X_final, y_final, test_size=0.3, stratify=y_final, random_state=42
291    )
292
293    # Train model
294    model = GradientBoostingClassifier(
295        n_estimators=80,
296        max_depth=3,
297        learning_rate=0.05,
298        random_state=42
299    )
300    model.fit(X_train, y_train)
301
302    # Evaluate
303    y_pred = model.predict(X_test)
304    y_proba_gb = model.predict_proba(X_test)[:, 1]
305
306    print("\nFinal Model Performance:")
307    print(classification_report(y_test, y_pred))
308
309    # Confusion matrix
310    tn, fp, fn, tp = confusion_matrix(y_test, y_pred).ravel()
311    tpr = tp / (tp + fn) if (tp + fn) > 0 else 0.0
312    fpr = fp / (fp + tn) if (fp + tn) > 0 else 0.0
313
314    print(f"\nDetection rate (TPR): {tpr:.1%}")
315    print(f"False positive rate (FPR): {fpr:.1%}")
316
317    # Feature importance
318    print("\nFeature Importance:")
319    for feat, imp in sorted(zip(features, model.feature_importances_),
320                           key=lambda x: x[1], reverse=True):
321        print(f"  {feat}: {imp:.3f}")
322
323    # Show example detections
324    hallucination_examples = df[df['is_hallucination'] == 1].head(10)
325    print(f"\nExample detected hallucinations:")
326    for _, seg in hallucination_examples.iterrows():
327        print(f"  Score={seg['knn_score']:.3f}, text='{seg['text']}'")
328
329    non_hallucination_examples = df[df['is_hallucination'] == 0].head(10)
330    print(f"\nExample detected non-hallucinations:")
331    for _, seg in non_hallucination_examples.iterrows():
332        print(f"  Score={seg['knn_score']:.3f}, text='{seg['text']}'")
333
334    # --- after training the GB model ---
335    gb_scores = model.predict_proba(X_final)[:, 1]
336
337    # choose threshold on GB scores, e.g. same 95-percentile rule
338    neg_scores = gb_scores[df['seed_label'] == 0]
339    threshold = np.percentile(neg_scores, 95)
340    print(f"\nPost-training threshold: {threshold:.3f}")
341
342    # Save model
343    model_dir = Path("Models")
344    model_dir.mkdir(exist_ok=True)
345
346    model_bundle = {
347        "model": model,
348        "threshold": threshold,
349        "features": features,
350    }
351
352    output_path = model_dir / "thankyou_filter_gb.pkl"
353    joblib.dump(model_bundle, output_path)
354    print(f"\nModel saved to: {output_path}")
355
356if __name__ == "__main__":
357    main()