""" Transition Pattern Analyzer -- Stage 1 sub-analyzer. Detects AI-like use of formulaic transitions at sentence/paragraph beginnings. Severity tiers: - HIGH (always flag): Furthermore, Moreover, Additionally, Consequently, Therefore, Thus, Hence, In addition, In conclusion, Notably, Importantly, etc. - LOW (only flag when 2+ low-severity appear OR 2+ other transitions already found): However, But, Still, Yet, Although, While, Whereas, Despite, That said, etc. """ from __future__ import annotations import json import re from pathlib import Path # --------------------------------------------------------------------------- # Low-severity transitions: natural contrast words that humans use freely. # Only flagged when overused (2+ in the same text) or context-dependent. # --------------------------------------------------------------------------- _LOW_SEVERITY_STARTERS: set[str] = { "however", "but", "still", "yet", "although", "while", "whereas", "despite", "though", "admittedly", "granted", "that said", "on the other hand", "then again", "at the same time", "even so", "nonetheless", "nevertheless", "notwithstanding", } class TransitionAnalyzer: """Detects problematic transition words/phrases that mark AI writing. Args: transition_path: Path to transition_words.json data file. """ def __init__( self, transition_path: str = "app/data/transition_words.json", ) -> None: self.transition_path = transition_path self._starters: list[str] = [] self._connectors: list[str] = [] self._formulaic: list[str] = [] self._load_transitions() def _load_transitions(self) -> None: """Load transition word lists from JSON file.""" path = Path(self.transition_path) if not path.exists(): alt = Path(__file__).parent.parent.parent / "data" / "transition_words.json" path = alt if alt.exists() else path if path.exists(): with open(path, 'r', encoding='utf-8') as f: data = json.load(f) self._starters = [s.lower() for s in data.get('sentence_starters', [])] self._connectors = [s.lower() for s in data.get('connector_phrases', [])] self._formulaic = [s.lower() for s in data.get('formulaic_openers', [])] else: # Hardcoded fallback self._starters = [ 'furthermore', 'moreover', 'additionally', 'consequently', 'nevertheless', 'however', 'therefore', 'thus', 'hence', 'subsequently', 'notably', 'importantly', ] def analyze(self, sentences: list[str]) -> list[dict]: """Detect transition pattern problems across all sentences. High-severity transitions are always flagged. Low-severity transitions (however, but, while, etc.) are only flagged when they appear 2+ times in the text OR when there are already 2+ high-severity transition flags -- since low-severity transitions are natural in human writing and only become a problem when overused. Args: sentences: List of sentence strings. Returns: List of instruction dicts. """ instructions: list[dict] = [] # First pass: detect all transition matches with their severity. matches: list[tuple[int, str, str]] = [] # (sent_idx, matched_word, severity) for idx, sentence in enumerate(sentences): sent_lower = sentence.strip().lower() matched = self._find_transition_match(sent_lower) if matched: severity = self._get_severity(matched) matches.append((idx, matched, severity)) # Count high-severity and low-severity matches. high_count = sum(1 for _, _, sev in matches if sev == 'high') low_severity_words: dict[str, int] = {} for _, word, sev in matches: if sev == 'low': low_severity_words[word] = low_severity_words.get(word, 0) + 1 # Second pass: build instructions using the severity rules. for sent_idx, matched, severity in matches: if severity == 'high': instructions.append(self._build_instruction(sent_idx, matched, 'high')) else: # Low-severity: only flag if: # (a) this specific low-severity word appears 2+ times, OR # (b) there are already 2+ high-severity flags in the text. word_count = low_severity_words.get(matched, 1) if word_count >= 2 or high_count >= 2: instructions.append( self._build_instruction(sent_idx, matched, 'low') ) # Check for consecutive same-start patterns (independent of severity). consecutive_instructions = self._check_consecutive_patterns(sentences) instructions.extend(consecutive_instructions) return instructions def _get_severity(self, transition: str) -> str: """Return 'low' if the transition is a natural contrast word, else 'high'.""" # Normalize: strip trailing comma/space that may appear in matched text. normalized = transition.rstrip(', ').lower() if normalized in _LOW_SEVERITY_STARTERS: return 'low' return 'high' def _build_instruction( self, sentence_index: int, matched: str, severity: str, ) -> dict: """Build an instruction dict for a flagged transition.""" if severity == 'high': instruction = ( f'Remove or replace the transition "{matched}" at the start of this sentence. ' f'Either restructure to flow naturally from the previous sentence, ' f'or use a less formulaic connector. ' f'Starting directly with the subject is often strongest.' ) else: instruction = ( f'"{matched.capitalize()}" at the start of this sentence is a low-severity ' f'transition -- natural in moderation, but it appears multiple times here. ' f'Vary how you signal contrast: restructure one of these sentences to flow ' f'without a connector, or use more specific phrasing ("The data tell a ' f'different story:", "That optimism has limits:", etc.).' ) return { 'type': 'transition', 'sentence_index': sentence_index, 'severity': severity, 'current_opening': matched, 'instruction': instruction, } def _find_transition_match(self, sentence_lower: str) -> str | None: """Return the transition word/phrase if sentence starts with one.""" # Check formulaic openers first (longer patterns) for phrase in self._formulaic: if sentence_lower.startswith(phrase): return phrase # Check connectors for phrase in self._connectors: if sentence_lower.startswith(phrase): return phrase # Check single-word starters for word in self._starters: # Match word at start, optionally followed by comma or space pattern = r'^' + re.escape(word) + r'[,\s]' if re.match(pattern, sentence_lower): return word return None def _check_consecutive_patterns( self, sentences: list[str], ) -> list[dict]: """Detect 2+ consecutive sentences with the same opening pattern.""" instructions = [] i = 0 while i < len(sentences) - 1: # Check first 1-3 words for repetition first_words_i = ' '.join(sentences[i].split()[:3]).lower().rstrip('.,;:') first_words_next = ' '.join(sentences[i + 1].split()[:3]).lower().rstrip('.,;:') if ( first_words_i == first_words_next and len(first_words_i) > 2 ): instructions.append({ 'type': 'transition', 'sentence_index': i, 'severity': 'medium', 'current_opening': first_words_i, 'instruction': ( f'Sentences {i} and {i+1} both start with "{first_words_i}". ' f'Vary the opening of one of them -- start with a different subject, ' f'a time phrase, or an adverbial clause.' ), }) i += 1 return instructions