Spaces:
Runtime error

humanizer-engine / app /core /analyzers /perplexity.py
faseehsandhu's picture
stage 1 completed
f66da21
Raw History Blame Contribute Delete
12.2 kB
"""
Perplexity Analyzer β€” Stage 1 sub-analyzer.
Uses Qwen2.5-0.5B to score sentence perplexity, with a fast heuristic
pre-filter to reduce unnecessary model calls by ~50%.
The pre-filter (<10ms) flags sentences that LOOK AI-like based on:
1. Starts with a known transition word.
2. Length is within Β±3 words of the mean (too uniform).
3. Contains 2+ AI vocabulary trigger words.
4. Contains known AI phrase patterns.
Only pre-flagged sentences (~50-60%) are sent through Qwen2.5 for scoring.
"""
from __future__ import annotations
import json
import logging
import re
import statistics
from pathlib import Path
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from app.core.perplexity_scorer import PerplexityScorer, SentencePerplexityResult
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Hardcoded fallback heuristic data (used when JSON file is not found)
# ---------------------------------------------------------------------------
_FALLBACK_TRANSITION_STARTERS: list[str] = [
"furthermore",
"moreover",
"additionally",
"consequently",
"nevertheless",
"however",
"therefore",
"thus",
"hence",
"subsequently",
"notably",
"importantly",
"significantly",
"evidently",
"clearly",
"essentially",
"ultimately",
"in addition",
"as a result",
"on the other hand",
"in contrast",
"in conclusion",
"to summarize",
"in summary",
]
_FALLBACK_AI_VOCABULARY_TRIGGERS: list[str] = [
"utilize",
"leverage",
"facilitate",
"robust",
"paradigm",
"unprecedented",
"multifaceted",
"holistic",
"synergy",
"comprehensive",
"nuanced",
"pivotal",
"crucial",
"transformative",
"innovative",
"sophisticated",
"delve",
"underscore",
"highlight",
"demonstrate",
"encompass",
"mitigate",
"optimize",
"paramount",
"salient",
"endeavor",
"aforementioned",
]
_FALLBACK_AI_PHRASE_PATTERNS: list[str] = [
"it is important to note that",
"it is worth noting that",
"it should be noted that",
"it goes without saying",
"as previously mentioned",
"in the context of",
"plays a crucial role",
"plays a pivotal role",
"of paramount importance",
"cannot be overstated",
"first and foremost",
"last but not least",
"in order to",
"a myriad of",
"a plethora of",
]
class PerplexityAnalyzer:
"""Combines a fast heuristic pre-filter with Qwen2.5-0.5B perplexity scoring.
The heuristic pre-filter runs in <10ms and decides which sentences are
worth sending to the (slower) language model for perplexity evaluation.
Only pre-flagged sentences (~50-60% of input) are scored by Qwen2.5.
Sentences classified as high_risk or medium_risk by the model receive an
instruction dict in the returned list. low_risk sentences are silently
omitted.
Args:
scorer: An already-loaded PerplexityScorer instance (shared from app
startup). If None, perplexity scoring is skipped entirely
and an empty list is returned (graceful degradation).
heuristic_path: Path to heuristic_patterns.json.
"""
def __init__(
self,
scorer: "PerplexityScorer | None" = None,
heuristic_path: str = "app/data/heuristic_patterns.json",
) -> None:
self.scorer = scorer
self.heuristic_path = heuristic_path
# Heuristic data (populated by _load_heuristics).
self._transition_starters: list[str] = []
self._ai_vocab_triggers: list[str] = []
self._ai_phrase_patterns: list[str] = []
self._load_heuristics()
# ------------------------------------------------------------------
# Heuristic data loading
# ------------------------------------------------------------------
def _load_heuristics(self) -> None:
"""Load heuristic pattern data from JSON, with fallback to hardcoded lists.
Tries the provided path first, then a path relative to this file's
location in the package (``../../data/heuristic_patterns.json``).
Falls back to hardcoded lists if neither file is found.
"""
path = Path(self.heuristic_path)
if not path.exists():
# Try path relative to this source file.
alt = Path(__file__).parent.parent.parent / "data" / "heuristic_patterns.json"
path = alt if alt.exists() else path
if path.exists():
try:
with open(path, 'r', encoding='utf-8') as fh:
data: dict = json.load(fh)
self._transition_starters = [
s.lower() for s in data.get('transition_starters', [])
]
self._ai_vocab_triggers = [
w.lower() for w in data.get('ai_vocabulary_triggers', [])
]
self._ai_phrase_patterns = [
p.lower() for p in data.get('ai_phrase_patterns', [])
]
logger.debug(
"PerplexityAnalyzer loaded heuristics from '%s': "
"%d transition starters, %d vocab triggers, %d phrase patterns.",
path,
len(self._transition_starters),
len(self._ai_vocab_triggers),
len(self._ai_phrase_patterns),
)
return
except (json.JSONDecodeError, OSError) as exc:
logger.warning(
"Failed to load heuristic_patterns.json from '%s': %s. "
"Falling back to hardcoded lists.",
path, exc,
)
# Fallback to hardcoded lists.
logger.warning(
"heuristic_patterns.json not found at '%s'. "
"Using built-in fallback heuristics.",
self.heuristic_path,
)
self._transition_starters = [s.lower() for s in _FALLBACK_TRANSITION_STARTERS]
self._ai_vocab_triggers = [w.lower() for w in _FALLBACK_AI_VOCABULARY_TRIGGERS]
self._ai_phrase_patterns = [p.lower() for p in _FALLBACK_AI_PHRASE_PATTERNS]
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def heuristic_prefilter(self, sentences: list[str]) -> list[bool]:
"""Fast heuristic pre-filter (<10ms).
Evaluates each sentence against four AI-likelihood criteria and
returns True for any sentence that matches at least one criterion.
Criteria (any one match β†’ True):
1. Starts with a transition word from the transition_starters list.
2. Sentence length (word count) is within Β±3 words of the mean
sentence length across all input sentences.
3. Contains 2+ words from ai_vocabulary_triggers list.
4. Contains any phrase from ai_phrase_patterns list.
Args:
sentences: List of sentence strings to evaluate.
Returns:
List of booleans of the same length as *sentences*. True means
the sentence should be scored by Qwen2.5.
"""
if not sentences:
return []
# Pre-compute word counts for criterion 2.
word_counts = [len(s.split()) for s in sentences]
if len(word_counts) >= 2:
mean_wc = statistics.mean(word_counts)
else:
mean_wc = float(word_counts[0]) if word_counts else 0.0
results: list[bool] = []
for idx, sentence in enumerate(sentences):
sent_lower = sentence.lower().strip()
wc = word_counts[idx]
flag = False
# Criterion 1: starts with a known transition word/phrase.
if not flag:
for starter in self._transition_starters:
if sent_lower.startswith(starter):
# Ensure it's a true word boundary (not a substring).
end_pos = len(starter)
if end_pos >= len(sent_lower) or not sent_lower[end_pos].isalpha():
flag = True
break
# Criterion 2: length within Β±3 words of the mean.
if not flag:
if abs(wc - mean_wc) <= 3:
flag = True
# Criterion 3: 2+ AI vocabulary trigger words.
if not flag:
trigger_hits = 0
for trigger in self._ai_vocab_triggers:
# Word-boundary match to avoid partial hits.
if re.search(r'\b' + re.escape(trigger) + r'\b', sent_lower):
trigger_hits += 1
if trigger_hits >= 2:
flag = True
break
# Criterion 4: contains a known AI phrase pattern.
if not flag:
for phrase in self._ai_phrase_patterns:
if phrase in sent_lower:
flag = True
break
results.append(flag)
return results
def analyze(self, sentences: list[str]) -> list[dict]:
"""Run heuristic pre-filter, then score flagged sentences with Qwen2.5.
Sentences that pass the pre-filter are sent to the PerplexityScorer.
Those that do not pass are implicitly treated as low_risk and omitted
from the output.
For scored sentences:
- high_risk β†’ instruction with severity='high'.
- medium_risk β†’ instruction with severity='medium'.
- low_risk β†’ silently omitted.
Args:
sentences: List of sentence strings.
Returns:
List of instruction dicts for high_risk and medium_risk sentences.
Each dict: {'type': 'perplexity', 'sentence_index': int,
'severity': str, 'mean_perplexity': float,
'instruction': str}.
"""
# Graceful degradation: if no scorer is available, return nothing.
if self.scorer is None:
logger.debug(
"PerplexityAnalyzer: no scorer provided β€” skipping perplexity scoring."
)
return []
if not sentences:
return []
# Score all sentences directly β€” no pre-filter, full accuracy.
# The heuristic_prefilter() method is kept for potential future use.
scored_results: list["SentencePerplexityResult"] = (
self.scorer.score_sentences(sentences)
)
# Build instruction list for high_risk and medium_risk results.
instructions: list[dict] = []
for original_idx, result in enumerate(scored_results):
ppl = result.mean_perplexity
classification = result.classification
if classification == 'high_risk':
instructions.append({
'type': 'perplexity',
'sentence_index': original_idx,
'severity': 'high',
'mean_perplexity': ppl,
'instruction': (
f"This sentence has very low perplexity ({ppl:.1f}) β€” "
f"highly predictable AI text. Restructure significantly: "
f"change sentence structure, not just vocabulary."
),
})
elif classification == 'medium_risk':
instructions.append({
'type': 'perplexity',
'sentence_index': original_idx,
'severity': 'medium',
'mean_perplexity': ppl,
'instruction': (
f"Moderate perplexity ({ppl:.1f}) β€” somewhat predictable. "
f"Make targeted changes: vary the structure or replace the "
f"most common phrasing."
),
})
# low_risk β†’ skip silently.
return instructions