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