""" TextAnalyzer — Stage 1 main orchestrator. Runs all sub-analyzers, combines their outputs into the unified AnalysisResult format, sorts instructions by sentence_index, compiles the banned_words list, and generates the summary. This class does NOT modify the input text. It produces a structured instruction set (JSON-serialisable dict) that Stage 2 uses to guide the LLM. """ from __future__ import annotations import logging import time from typing import Any, TYPE_CHECKING from app.utils.text_utils import ( count_words, split_sentences, sentence_word_counts, calculate_burstiness, ) from app.core.analyzers.burstiness import BurstinessAnalyzer from app.core.analyzers.vocabulary import VocabularyAnalyzer from app.core.analyzers.transitions import TransitionAnalyzer from app.core.analyzers.openings import OpeningPatternAnalyzer from app.core.analyzers.structure import StructuralAnalyzer from app.core.analyzers.informality import InformalityAnalyzer from app.core.analyzers.perplexity import PerplexityAnalyzer if TYPE_CHECKING: import spacy # type: ignore from app.core.perplexity_scorer import PerplexityScorer logger = logging.getLogger(__name__) class TextAnalyzer: """Orchestrates all Stage 1 sub-analyzers. A single instance is created at application startup and reused for every request. Heavy resources (spaCy, Qwen2.5) are injected via the constructor so they are loaded only once. Args: nlp: Loaded spaCy Language model (or None — fallback to regex). perplexity_scorer: Loaded PerplexityScorer (or None — perplexity analysis skipped). vocab_path: Path to ai_vocabulary.json. transition_path: Path to transition_words.json. heuristic_path: Path to heuristic_patterns.json. """ def __init__( self, nlp: "spacy.Language | None" = None, perplexity_scorer: "PerplexityScorer | None" = None, vocab_path: str = "app/data/ai_vocabulary.json", transition_path: str = "app/data/transition_words.json", heuristic_path: str = "app/data/heuristic_patterns.json", ) -> None: self.nlp = nlp self._burstiness = BurstinessAnalyzer() self._vocabulary = VocabularyAnalyzer(vocab_path=vocab_path) self._transitions = TransitionAnalyzer(transition_path=transition_path) self._openings = OpeningPatternAnalyzer() self._structure = StructuralAnalyzer() self._informality = InformalityAnalyzer() self._perplexity = PerplexityAnalyzer( scorer=perplexity_scorer, heuristic_path=heuristic_path, ) # ------------------------------------------------------------------ # Public API # ------------------------------------------------------------------ def analyze(self, text: str) -> dict[str, Any]: """Run full Stage 1 analysis on *text*. Args: text: The raw AI-generated text to analyse. Returns: AnalysisResult dict (JSON-serialisable) containing: - summary - instructions (all sub-analyzer outputs, sorted by sentence_index) - banned_words - sentence_perplexities """ t0 = time.perf_counter() # ---- Sentence splitting ---- sentences = split_sentences(text, nlp=self.nlp) if not sentences: return self._empty_result() # ---- Run all sub-analyzers ---- burst_result = self._burstiness.analyze(sentences) vocab_instructions = self._vocabulary.analyze(sentences) transition_instructions = self._transitions.analyze(sentences) opening_instructions = self._openings.analyze(sentences) structure_instructions = self._structure.analyze(text, sentences) informality_instructions = self._informality.analyze(sentences) perplexity_instructions = self._perplexity.analyze(sentences) # ---- Gather perplexity per-sentence for the summary ---- sentence_perplexities = self._build_sentence_perplexities( sentences, perplexity_instructions ) # ---- Combine all instructions ---- all_instructions: list[dict] = [] all_instructions.extend(perplexity_instructions) all_instructions.extend(burst_result["instructions"]) all_instructions.extend(vocab_instructions) all_instructions.extend(transition_instructions) all_instructions.extend(opening_instructions) all_instructions.extend(structure_instructions) all_instructions.extend(informality_instructions) # Sort by sentence_index (structural instructions may have None → put at end) all_instructions.sort( key=lambda x: (x.get("sentence_index") is None, x.get("sentence_index", 999)) ) # ---- Banned words ---- banned_words = self._vocabulary.get_banned_words(text) # ---- Summary ---- high_risk = sum( 1 for s in sentence_perplexities if s.get("risk") == "high_risk" ) medium_risk = sum( 1 for s in sentence_perplexities if s.get("risk") == "medium_risk" ) low_risk = len(sentences) - high_risk - medium_risk overall_risk = _compute_overall_risk(high_risk, medium_risk, len(sentences)) elapsed_ms = round((time.perf_counter() - t0) * 1000, 1) logger.debug("Stage 1 analysis completed in %.1f ms", elapsed_ms) summary: dict[str, Any] = { "total_sentences": len(sentences), "high_risk_sentences": high_risk, "medium_risk_sentences": medium_risk, "low_risk_sentences": low_risk, "burstiness_cv": burst_result["burstiness_stats"]["cv"], "burstiness_rating": burst_result["rating"], "ai_vocabulary_count": len( [i for i in vocab_instructions if i["type"] == "vocabulary"] ), "transition_flags": len( [i for i in transition_instructions if i["type"] == "transition"] ), "opening_pattern_flags": len( [i for i in opening_instructions if i["type"] == "sentence_opening"] ), "overall_risk": overall_risk, "analysis_time_ms": elapsed_ms, } return { "summary": summary, "instructions": all_instructions, "banned_words": banned_words, "sentence_perplexities": sentence_perplexities, } # ------------------------------------------------------------------ # Private helpers # ------------------------------------------------------------------ def _build_sentence_perplexities( self, sentences: list[str], perplexity_instructions: list[dict], ) -> list[dict]: """Build the sentence_perplexities list from perplexity instructions. For sentences that weren't scored (pre-filter excluded them or scorer is None), we assign 'low_risk' with a placeholder perplexity of 100.0. """ # Index perplexity data by sentence_index ppl_by_idx: dict[int, dict] = {} for instr in perplexity_instructions: idx = instr.get("sentence_index", -1) if idx >= 0: ppl_by_idx[idx] = { "index": idx, "text": sentences[idx] if idx < len(sentences) else "", "mean_ppl": instr.get("mean_perplexity", 100.0), "risk": ( "high_risk" if instr.get("severity") == "high" else "medium_risk" ), } result = [] for i, sent in enumerate(sentences): if i in ppl_by_idx: result.append(ppl_by_idx[i]) else: result.append({ "index": i, "text": sent, "mean_ppl": 100.0, "risk": "low_risk", }) return result @staticmethod def _empty_result() -> dict[str, Any]: """Return a valid but empty AnalysisResult for empty/whitespace input.""" return { "summary": { "total_sentences": 0, "high_risk_sentences": 0, "medium_risk_sentences": 0, "low_risk_sentences": 0, "burstiness_cv": 0.0, "burstiness_rating": "acceptable", "ai_vocabulary_count": 0, "transition_flags": 0, "opening_pattern_flags": 0, "overall_risk": "low", "analysis_time_ms": 0.0, }, "instructions": [], "banned_words": [], "sentence_perplexities": [], } # --------------------------------------------------------------------------- # Module-level helper # --------------------------------------------------------------------------- def _compute_overall_risk( high_risk: int, medium_risk: int, total_sentences: int, ) -> str: """Compute overall document risk from per-sentence risk counts.""" if total_sentences == 0: return "low" high_ratio = high_risk / total_sentences medium_ratio = medium_risk / total_sentences if high_ratio >= 0.30 or (high_ratio + medium_ratio) >= 0.60: return "high" if high_ratio >= 0.15 or (high_ratio + medium_ratio) >= 0.40: return "medium" return "low"