Spaces:
Runtime error
Runtime error
Download app/core/analyzers/structure.py from digitalytics/humanizer-engine: direct link, hf CLI and curl.
- Browser
- Download file 11.4 kB
-
https://huggingface.co/spaces/digitalytics/humanizer-engine/resolve/main/app/core/analyzers/structure.py
- Command line
-
hf download hf://spaces/digitalytics/humanizer-engine/app/core/analyzers/structure.py
-
curl -L -o structure.py https://huggingface.co/spaces/digitalytics/humanizer-engine/resolve/main/app/core/analyzers/structure.py
11.4 kB
| """ | |
| Structural Analyzer — Stage 1 sub-analyzer. | |
| Analyzes paragraph-level structure to detect AI-like uniformity: | |
| - Paragraphs of identical or near-identical length. | |
| - Over-predictable claim→evidence→conclusion patterns. | |
| - Missing paragraph breaks (wall of text). | |
| """ | |
| from __future__ import annotations | |
| import re | |
| from collections import Counter | |
| class StructuralAnalyzer: | |
| """Analyzes paragraph structure for AI uniformity patterns. | |
| Checks: | |
| - 2+ paragraphs with identical sentence count where each is 3-5 sentences. | |
| - A single paragraph with more than 7 sentences (wall of text). | |
| - All paragraphs having exactly the same sentence count. | |
| Args: | |
| long_paragraph_threshold: Paragraphs with more sentences than this | |
| are flagged as "wall of text". Default 7. | |
| uniform_length_min: Minimum sentence count per paragraph for the | |
| identical-length uniformity check. Default 3. | |
| uniform_length_max: Maximum sentence count per paragraph for the | |
| identical-length uniformity check. Default 5. | |
| """ | |
| def __init__( | |
| self, | |
| long_paragraph_threshold: int = 7, | |
| uniform_length_min: int = 3, | |
| uniform_length_max: int = 5, | |
| ) -> None: | |
| self.long_paragraph_threshold = long_paragraph_threshold | |
| self.uniform_length_min = uniform_length_min | |
| self.uniform_length_max = uniform_length_max | |
| # ------------------------------------------------------------------ | |
| # Public API | |
| # ------------------------------------------------------------------ | |
| def analyze(self, text: str, sentences: list[str]) -> list[dict]: | |
| """Analyze paragraph structure for AI uniformity patterns. | |
| Args: | |
| text: Full original text (used to detect paragraph breaks via | |
| double-newline or single newline). | |
| sentences: Pre-split list of sentences (used for sentence counts | |
| when the paragraph break approach yields no structure). | |
| Returns: | |
| List of instruction dicts with type='structural'. | |
| """ | |
| if not text.strip(): | |
| return [] | |
| paragraphs = self._split_paragraphs(text) | |
| # Fall back: if no paragraph boundaries found, treat each 4-sentence | |
| # window as a synthetic paragraph so the checks still run. | |
| if len(paragraphs) <= 1: | |
| paragraphs = self._synthetic_paragraphs(sentences) | |
| if not paragraphs: | |
| return [] | |
| instructions: list[dict] = [] | |
| sentence_counts = [self._count_sentences(p) for p in paragraphs] | |
| # -- Check 1: wall of text (single long paragraph) -------------- | |
| wall_instructions = self._check_wall_of_text(paragraphs, sentence_counts) | |
| instructions.extend(wall_instructions) | |
| # -- Check 2: identical sentence counts in 3-5 sentence paras -- | |
| uniformity_instructions = self._check_uniform_paragraph_lengths( | |
| paragraphs, sentence_counts | |
| ) | |
| instructions.extend(uniformity_instructions) | |
| # -- Check 3: all paragraphs have exactly the same length ------- | |
| all_same_instructions = self._check_all_same_length( | |
| paragraphs, sentence_counts | |
| ) | |
| instructions.extend(all_same_instructions) | |
| return instructions | |
| # ------------------------------------------------------------------ | |
| # Private helpers: paragraph splitting | |
| # ------------------------------------------------------------------ | |
| def _split_paragraphs(self, text: str) -> list[str]: | |
| """Split *text* into paragraphs using double or single newlines. | |
| Strategy: | |
| 1. Try splitting on two or more consecutive newlines first. | |
| 2. If that produces only one chunk, fall back to single newlines. | |
| 3. Strip each chunk and discard empty ones. | |
| Args: | |
| text: Raw input text. | |
| Returns: | |
| List of non-empty paragraph strings. | |
| """ | |
| # Try double-newline split first. | |
| chunks = re.split(r'\n{2,}', text.strip()) | |
| non_empty = [c.strip() for c in chunks if c.strip()] | |
| if len(non_empty) >= 2: | |
| return non_empty | |
| # Fall back to single-newline split. | |
| chunks = re.split(r'\n', text.strip()) | |
| non_empty = [c.strip() for c in chunks if c.strip()] | |
| return non_empty if len(non_empty) >= 2 else [text.strip()] | |
| def _synthetic_paragraphs(self, sentences: list[str]) -> list[str]: | |
| """Create synthetic paragraphs from a flat sentence list. | |
| When no paragraph breaks exist in the text, group sentences into | |
| windows of 4 so structural checks still have something to evaluate. | |
| Args: | |
| sentences: All sentences from the document. | |
| Returns: | |
| List of synthetic paragraph strings (each is 4 sentences joined | |
| by a space, or fewer for the last chunk). | |
| """ | |
| window = 4 | |
| paragraphs = [] | |
| for i in range(0, len(sentences), window): | |
| chunk = sentences[i: i + window] | |
| paragraphs.append(' '.join(chunk)) | |
| return paragraphs | |
| # ------------------------------------------------------------------ | |
| # Private helpers: sentence counting | |
| # ------------------------------------------------------------------ | |
| def _count_sentences(self, paragraph: str) -> int: | |
| """Count the number of sentences in *paragraph*. | |
| Uses a simple regex boundary detector (terminal punctuation followed | |
| by whitespace or end-of-string). Accurate enough for structural | |
| uniformity detection. | |
| Args: | |
| paragraph: A paragraph string. | |
| Returns: | |
| Integer count of sentences (minimum 1 for non-empty text). | |
| """ | |
| if not paragraph.strip(): | |
| return 0 | |
| # Split on sentence-ending punctuation followed by whitespace or EOS. | |
| parts = re.split(r'(?<=[.!?])\s+', paragraph.strip()) | |
| non_empty = [p for p in parts if p.strip()] | |
| return max(1, len(non_empty)) | |
| # ------------------------------------------------------------------ | |
| # Private helpers: structural checks | |
| # ------------------------------------------------------------------ | |
| def _check_wall_of_text( | |
| self, | |
| paragraphs: list[str], | |
| sentence_counts: list[int], | |
| ) -> list[dict]: | |
| """Flag any paragraph with more than *long_paragraph_threshold* sentences. | |
| Args: | |
| paragraphs: List of paragraph strings. | |
| sentence_counts: Corresponding sentence count per paragraph. | |
| Returns: | |
| List of instruction dicts. | |
| """ | |
| instructions = [] | |
| for para_idx, (para, count) in enumerate(zip(paragraphs, sentence_counts)): | |
| if count > self.long_paragraph_threshold: | |
| instructions.append({ | |
| 'type': 'structural', | |
| 'severity': 'high', | |
| 'instruction': ( | |
| f'Paragraph {para_idx + 1} contains {count} sentences with no ' | |
| f'break — a wall of text that reads as AI-generated. ' | |
| f'Split it into 2-3 shorter paragraphs at logical topic ' | |
| f'transitions. Each resulting paragraph should cover a single ' | |
| f'sub-point.' | |
| ), | |
| }) | |
| return instructions | |
| def _check_uniform_paragraph_lengths( | |
| self, | |
| paragraphs: list[str], | |
| sentence_counts: list[int], | |
| ) -> list[dict]: | |
| """Flag when 2+ paragraphs share an identical sentence count in [3, 5]. | |
| AI text tends to produce paragraphs that all have the same number of | |
| sentences (claim, evidence, conclusion = 3 sentences, etc.). | |
| Args: | |
| paragraphs: List of paragraph strings. | |
| sentence_counts: Corresponding sentence count per paragraph. | |
| Returns: | |
| List of instruction dicts. | |
| """ | |
| instructions = [] | |
| # Count how many paragraphs have each sentence count in range [3, 5]. | |
| count_freq: Counter[int] = Counter() | |
| for c in sentence_counts: | |
| if self.uniform_length_min <= c <= self.uniform_length_max: | |
| count_freq[c] += 1 | |
| for sent_count, freq in count_freq.items(): | |
| if freq >= 2: | |
| affected_indices = [ | |
| i + 1 # 1-based paragraph numbers for human-readable output | |
| for i, c in enumerate(sentence_counts) | |
| if c == sent_count | |
| ] | |
| instructions.append({ | |
| 'type': 'structural', | |
| 'severity': 'medium', | |
| 'instruction': ( | |
| f'Paragraphs {affected_indices} each contain exactly ' | |
| f'{sent_count} sentences. This rigid uniformity -- ' | |
| f'{"claim / evidence / conclusion" if sent_count == 3 else "uniform block"} ' | |
| f'repeated {freq} times -- is a strong AI marker. ' | |
| f'Vary paragraph length: expand one paragraph with additional ' | |
| f'detail or examples, and compress another to 1-2 punchy ' | |
| f'sentences for rhythm contrast.' | |
| ), | |
| }) | |
| return instructions | |
| def _check_all_same_length( | |
| self, | |
| paragraphs: list[str], | |
| sentence_counts: list[int], | |
| ) -> list[dict]: | |
| """Flag when every paragraph in the document has the same sentence count. | |
| This check is only meaningful with 3+ paragraphs; it catches the | |
| case where uniform length falls outside the [3, 5] range targeted by | |
| the previous check. | |
| Args: | |
| paragraphs: List of paragraph strings. | |
| sentence_counts: Corresponding sentence count per paragraph. | |
| Returns: | |
| List of instruction dicts (at most one). | |
| """ | |
| # Need at least 3 paragraphs for this signal to be meaningful. | |
| if len(sentence_counts) < 3: | |
| return [] | |
| non_zero = [c for c in sentence_counts if c > 0] | |
| if not non_zero: | |
| return [] | |
| if len(set(non_zero)) == 1: | |
| uniform_count = non_zero[0] | |
| # Skip if this was already covered by _check_uniform_paragraph_lengths | |
| # (i.e. the count is in [3, 5] — that check already generates an | |
| # instruction, so avoid duplication). | |
| if self.uniform_length_min <= uniform_count <= self.uniform_length_max: | |
| return [] | |
| return [{ | |
| 'type': 'structural', | |
| 'severity': 'high', | |
| 'instruction': ( | |
| f'Every paragraph in the text contains exactly {uniform_count} ' | |
| f'sentences. Perfect structural uniformity across all ' | |
| f'{len(non_zero)} paragraphs is a clear AI writing pattern. ' | |
| f'Deliberately vary the length: write at least one short ' | |
| f'(1-2 sentence) paragraph for emphasis and at least one longer ' | |
| f'paragraph that develops an idea with more depth.' | |
| ), | |
| }] | |
| return [] | |