""" Opening Pattern Analyzer — Stage 1 sub-analyzer. Detects repetitive sentence-opening patterns (e.g. "The... The... The..."), formulaic openers ("It is...", "This is...", "There are..."), and flags them for the LLM to vary. """ from __future__ import annotations import re from collections import defaultdict # --------------------------------------------------------------------------- # Formulaic opener list # --------------------------------------------------------------------------- FORMULAIC_OPENERS: list[str] = [ "it is", "this is", "there are", "there is", "this shows", "this demonstrates", "this indicates", "this suggests", "this means", "this highlights", "this allows", "this enables", "this helps", "this makes", "this provides", "this creates", "this leads", "this results", "it can", "it should", "it must", "it may", "it will", # AI aggregating/concluding starters "these innovations", "these findings", "these results", "these developments", "these advances", "these changes", "these approaches", "these strategies", "these improvements", "these efforts", "these factors", "these technologies", "these methods", "these tools", ] class OpeningPatternAnalyzer: """Detects repetitive and formulaic sentence opening patterns. Checks: 1. 3+ sentences (globally) starting with the same first word. 2. 2+ consecutive sentences within the same paragraph starting the same way. 3. Formulaic openers such as "It is", "This is", "There are/is", and "This [verb]" constructions. Each finding is returned as an instruction dict that the rewriting stage can act on. """ def __init__(self) -> None: # Pre-lowercase the formulaic openers once for speed. self._formulaic: list[str] = [o.lower() for o in FORMULAIC_OPENERS] # ------------------------------------------------------------------ # Public API # ------------------------------------------------------------------ def analyze(self, sentences: list[str]) -> list[dict]: """Detect repetitive and formulaic sentence opening patterns. Checks: 1. 3+ sentences starting with the same word (e.g. "The"). 2. 2+ sentences in a paragraph starting the same way. 3. Formulaic openers: "It is", "This is", "There are", "There is", "This shows", "This demonstrates", "This indicates", "This suggests", "This means", "This highlights", and others. Args: sentences: Pre-split list of sentence strings. Returns: List of instruction dicts with type='sentence_opening', sentence_index, affected_sentences, pattern, severity, instruction. """ if not sentences: return [] instructions: list[dict] = [] # Track which sentence indices have already been flagged to avoid # duplicate instructions for the same sentence. flagged: set[int] = set() # -- Check 1 & 2: repetitive first-word patterns ---------------- first_word_instructions = self._check_first_word_repetition(sentences, flagged) instructions.extend(first_word_instructions) # -- Check 3: formulaic openers --------------------------------- formulaic_instructions = self._check_formulaic_openers(sentences, flagged) instructions.extend(formulaic_instructions) # -- Check 4: "The [noun] of ..." AI structural pattern --------- the_of_instructions = self._check_the_noun_of_pattern(sentences, flagged) instructions.extend(the_of_instructions) return instructions # ------------------------------------------------------------------ # Private helpers # ------------------------------------------------------------------ def _get_first_word(self, sentence: str) -> str: """Return the lowercase first word of *sentence*, stripped of punctuation.""" stripped = sentence.strip() if not stripped: return "" # Split on whitespace and take the first token, removing leading # non-alpha characters (e.g. quote marks, parentheses). first_token = stripped.split()[0] # Remove leading/trailing punctuation but keep the word itself. word = re.sub(r'^[^a-zA-Z]+|[^a-zA-Z]+$', '', first_token) return word.lower() def _check_first_word_repetition( self, sentences: list[str], flagged: set[int], ) -> list[dict]: """Generate instructions for repeated first-word patterns. Two sub-checks: a) 3+ sentences globally that share the same first word → one consolidated instruction listing all affected indices. b) 2+ consecutive sentences in the same paragraph that share the same first word (even if the global count is below 3). Paragraph boundaries are estimated by looking for sentence indices where a new paragraph starts. Since only ``sentences`` is available (no raw text here), paragraphs are approximated by grouping consecutive sentences that do not begin with a blank string. The paragraph detection for check (b) relies on the caller having split on paragraph breaks — if not, the whole list is treated as one paragraph for check (b) and check (a) still applies globally. """ instructions: list[dict] = [] # ---- Global first-word counts (check a) ----------------------- first_words: list[str] = [self._get_first_word(s) for s in sentences] # Map: first_word → list of sentence indices word_to_indices: dict[str, list[int]] = defaultdict(list) for idx, fw in enumerate(first_words): if fw: word_to_indices[fw].append(idx) globally_flagged_words: set[str] = set() for word, indices in word_to_indices.items(): if len(indices) >= 2: globally_flagged_words.add(word) severity = 'high' if len(indices) >= 4 else 'medium' instruction = ( f'Sentences {indices} all begin with "{word.capitalize()}". ' f'This repetitive opening is a hallmark of AI-generated text. ' f'Vary the sentence starters: restructure some sentences so they ' f'open with a different subject, an adverb, a dependent clause, ' f'or a prepositional phrase.' ) # Use the first index as the primary sentence_index. instructions.append({ 'type': 'sentence_opening', 'sentence_index': indices[0], 'affected_sentences': indices, 'pattern': f'repeated_first_word:"{word}"', 'severity': severity, 'instruction': instruction, }) for idx in indices: flagged.add(idx) # ---- Consecutive same-start within a paragraph (check b) ------ # Treat the entire sentence list as one paragraph for consecutive # scanning. Already-flagged global repeats are still reported here # if they form consecutive pairs not already covered. i = 0 while i < len(sentences) - 1: fw_i = first_words[i] fw_next = first_words[i + 1] if ( fw_i and fw_i == fw_next # Skip if this word was already handled by the global check and fw_i not in globally_flagged_words # Skip if both are already flagged and not (i in flagged and (i + 1) in flagged) ): affected = [i, i + 1] # Extend the run if more consecutive sentences match. j = i + 2 while j < len(sentences) and first_words[j] == fw_i: affected.append(j) j += 1 instruction = ( f'Sentences {affected} (consecutive) all open with ' f'"{fw_i.capitalize()}". Vary the paragraph rhythm by starting ' f'at least one of these sentences differently — use an adverb, ' f'a subordinate clause, or invert the subject-verb order.' ) instructions.append({ 'type': 'sentence_opening', 'sentence_index': i, 'affected_sentences': affected, 'pattern': f'consecutive_same_opener:"{fw_i}"', 'severity': 'medium', 'instruction': instruction, }) for idx in affected: flagged.add(idx) # Jump past the whole run. i = affected[-1] + 1 else: i += 1 return instructions def _check_formulaic_openers( self, sentences: list[str], flagged: set[int], ) -> list[dict]: """Flag individual sentences that begin with a formulaic opener. Each formulaic match generates its own medium-severity instruction regardless of whether the sentence was already flagged by the repetition check — formulaic openers are a distinct signal. Args: sentences: Full list of sentence strings. flagged: Set of indices already flagged (modified in place to record newly flagged indices). Returns: List of instruction dicts. """ instructions: list[dict] = [] for idx, sentence in enumerate(sentences): sent_lower = sentence.strip().lower() matched_opener = self._match_formulaic(sent_lower) if matched_opener: instruction = ( f'This sentence opens with the formulaic phrase ' f'"{matched_opener.capitalize()}...", which is strongly associated ' f'with AI writing. Rewrite the sentence so it opens with a more ' f'specific subject or a concrete detail rather than a generic ' f'placeholder construction.' ) instructions.append({ 'type': 'sentence_opening', 'sentence_index': idx, 'affected_sentences': [idx], 'pattern': f'formulaic_opener:"{matched_opener}"', 'severity': 'medium', 'instruction': instruction, }) flagged.add(idx) return instructions def _check_the_noun_of_pattern( self, sentences: list[str], flagged: set[int], ) -> list[dict]: """Flag 'The [noun] of ...' openings — a common AI structural marker. Pattern: sentence starts with 'the ', followed by 1-2 words, then 'of '. Examples: 'The integration of...', 'The advancement of...', 'The impact of...' These abstract nominalization openings are heavily overused in AI text. Args: sentences: Full list of sentence strings. flagged: Set of indices already flagged (modified in place). Returns: List of instruction dicts. """ instructions: list[dict] = [] for idx, sentence in enumerate(sentences): sent_lower = sentence.strip().lower() if not sent_lower.startswith("the "): continue # Check if "of " appears within the first ~35 characters # after "the " — catches "The X of" and "The X Y of" patterns. prefix = sent_lower[4:35] # skip "the " if " of " in prefix: # Avoid re-flagging if already covered by formulaic check. if idx in flagged: continue # Extract the noun phrase for the instruction. end = sent_lower.find(" of ") noun_phrase = sent_lower[:end + 4].strip() # "the X of" instruction = ( f'This sentence opens with "{noun_phrase}..." — an abstract ' f'nominalization structure ("The [noun] of") that is heavily ' f'overused in AI text. Rewrite to lead with a verb or a more ' f'concrete subject: e.g. instead of "The integration of AI..." ' f'try "AI has been integrated into..." or "Clinicians now use AI..."' ) instructions.append({ 'type': 'sentence_opening', 'sentence_index': idx, 'affected_sentences': [idx], 'pattern': f'the_noun_of:"{noun_phrase}"', 'severity': 'medium', 'instruction': instruction, }) flagged.add(idx) return instructions def _match_formulaic(self, sentence_lower: str) -> str | None: """Return the matched formulaic opener string, or None. Sorts by length descending so that longer/more-specific openers (e.g. "this demonstrates") are matched before shorter substrings (e.g. "this"). Args: sentence_lower: Lowercase sentence text. Returns: The matched opener string (lowercase) or None. """ # Sort longest first to prefer specific matches. for opener in sorted(self._formulaic, key=len, reverse=True): if sentence_lower.startswith(opener): # Ensure it is followed by a word boundary (space, comma, etc.) # to avoid false positives on e.g. "These are" matching "there". end_pos = len(opener) if end_pos >= len(sentence_lower) or not sentence_lower[end_pos].isalpha(): return opener return None