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
2.8 KiB75 linesraw
1import io
2import joblib
3from logger import log, log_err
4import numpy as np
5import pandas as pd
6from pathlib import Path
7import pronouncing
8import re
9import sys
10
11def count_syllables(word):
12    """Count syllables in a word using pronouncing library with regex fallback."""
13    phones = pronouncing.phones_for_word(word.lower())
14    return pronouncing.syllable_count(phones[0])
15def text_syllable_count(text):
16    """Count total syllables in text."""
17    words = re.findall(r'\b\w+\b', text)
18    return sum(count_syllables(word) for word in words)
19class HallucinationFilter:
20    """Filter for detecting hallucinated segments in speech-to-text output."""
21    def __init__(self, model_path: Path = None):
22        """
23        Initialize the hallucination filter.
24        Args:
25            model_path: Optional path to the model file. If not provided,
26                       uses the default path.
27        """
28        self.model = None
29        self.threshold = None
30        self.features = None
31        # Get the project root directory
32        app_root = Path(__file__).resolve().parent
33        project_root = app_root.parent
34        # Use provided path or default
35        if model_path is None:
36            model_path = project_root / "Models" / "thankyou_filter_gb.pkl"
37        # Try to load the model
38        log_err(f"Loading hallucination filter")
39        bundle = joblib.load(model_path)
40        self.model = bundle["model"]
41        self.threshold = bundle["threshold"]
42        self.features = bundle["features"]
43        log_err(f"Loaded hallucination filter model from {model_path}")
44    def is_hallucination(self, segment) -> bool:
45        """
46        Check if a segment is likely a hallucination.
47        Returns False if model is not available.
48        Args:
49            segment: A segment object with attributes avg_logprob, audio_len_s,
50                    no_speech_prob, compression_ratio, text, start, and end.
51        Returns:
52            bool: True if the segment is likely a hallucination, False otherwise.
53        """
54        # Calculate text-based features
55        text = getattr(segment, 'text', '')
56        duration = segment.audio_len_s
57        raw_duration = segment.end_ts - segment.start_ts
58        n_syllables = text_syllable_count(text)
59        sps = n_syllables / duration
60        raw_sps = n_syllables / raw_duration
61        duration_ratio = raw_duration / duration
62        X = pd.DataFrame([[
63            segment.avg_logprob,
64            segment.no_speech_prob,
65            segment.compression_ratio,
66            np.log1p(duration),
67            np.log1p(sps),
68            np.log1p(raw_duration),
69            np.log1p(raw_sps),
70            duration_ratio,
71            segment.avg_logprob * duration
72        ]], columns=self.features)
73        # Get probability
74        prob = self.model.predict_proba(X)[0, 1]
75        return prob >= self.threshold