Spaces:
Runtime error
Runtime error
Download app/core/analyzers/informality.py from digitalytics/humanizer-engine: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/spaces/digitalytics/humanizer-engine/resolve/main/app/core/analyzers/informality.py
- Command line
-
hf download hf://spaces/digitalytics/humanizer-engine/app/core/analyzers/informality.py
-
curl -L -o informality.py https://huggingface.co/spaces/digitalytics/humanizer-engine/resolve/main/app/core/analyzers/informality.py
12.2 kB
| """ | |
| Informality Injection Analyzer β Stage 1 sub-analyzer. | |
| Identifies places where natural human writing would use: | |
| - Contractions ("don't" vs "do not", "it's" vs "it is", "they're", "we're", | |
| "I've", "you'll", "can't", "won't", "isn't", "aren't", "doesn't", "didn't", | |
| "couldn't", "wouldn't", "shouldn't"). | |
| - First-person hedging ("I would argue", "In my view", "I think"). | |
| - Casual phrasing and hedging language ("arguably", "to some extent"). | |
| Targets ~10-15% of sentences for informality injections. | |
| """ | |
| from __future__ import annotations | |
| import re | |
| # --------------------------------------------------------------------------- | |
| # Contraction mapping: expanded form (regex pattern) β contraction | |
| # --------------------------------------------------------------------------- | |
| # Each entry is (expanded_regex_pattern, contraction_string). | |
| # Patterns use word boundaries (\b) and are case-insensitive. | |
| # The expanded forms are ordered from more specific (longer) to more general | |
| # to prevent short patterns from shadowing longer ones on the same word. | |
| _CONTRACTION_MAP: list[tuple[str, str]] = [ | |
| # Two-word expansions β specific first. | |
| (r'\bdo not\b', "don't"), | |
| (r'\bcannot\b', "can't"), | |
| (r'\bwill not\b', "won't"), | |
| (r'\bshould not\b', "shouldn't"), | |
| (r'\bwould not\b', "wouldn't"), | |
| (r'\bcould not\b', "couldn't"), | |
| (r'\bis not\b', "isn't"), | |
| (r'\bare not\b', "aren't"), | |
| (r'\bdoes not\b', "doesn't"), | |
| (r'\bdid not\b', "didn't"), | |
| (r'\bhas not\b', "hasn't"), | |
| (r'\bhave not\b', "haven't"), | |
| (r'\bwas not\b', "wasn't"), | |
| (r'\bwere not\b', "weren't"), | |
| (r'\bthey are\b', "they're"), | |
| (r'\bwe are\b', "we're"), | |
| (r'\byou are\b', "you're"), | |
| (r'\bI am\b', "I'm"), | |
| (r'\bI have\b', "I've"), | |
| (r'\bI will\b', "I'll"), | |
| (r'\bI would\b', "I'd"), | |
| (r'\byou will\b', "you'll"), | |
| (r'\bhe is\b', "he's"), | |
| (r'\bshe is\b', "she's"), | |
| (r'\bit is\b', "it's"), | |
| (r'\bthat is\b', "that's"), | |
| (r'\bthere is\b', "there's"), | |
| (r'\bwhat is\b', "what's"), | |
| (r'\bwho is\b', "who's"), | |
| ] | |
| # Compiled patterns: (compiled_regex, contraction_string) | |
| _COMPILED_CONTRACTIONS: list[tuple[re.Pattern[str], str]] = [ | |
| (re.compile(pattern, re.IGNORECASE), contraction) | |
| for pattern, contraction in _CONTRACTION_MAP | |
| ] | |
| # --------------------------------------------------------------------------- | |
| # Strong-claim trigger words for first-person hedging | |
| # --------------------------------------------------------------------------- | |
| _STRONG_CLAIM_TRIGGERS: list[str] = [ | |
| # Present tense | |
| "shows", | |
| "proves", | |
| "demonstrates", | |
| "supports", | |
| "reveals", | |
| "indicates", | |
| "represents", | |
| "confirms", | |
| "illustrates", | |
| "establishes", | |
| # Past tense (AI often uses past for formal claims) | |
| "demonstrated", | |
| "showed", | |
| "proved", | |
| "supported", | |
| "revealed", | |
| "indicated", | |
| "represented", | |
| "confirmed", | |
| "illustrated", | |
| "established", | |
| # Adverbials and certainty markers | |
| "is clear", | |
| "is evident", | |
| "is obvious", | |
| "clearly shows", | |
| "clearly demonstrates", | |
| "undeniably", | |
| "without doubt", | |
| "it is certain", | |
| "certainly", | |
| "overwhelmingly", | |
| ] | |
| # First-person hedge suggestions rotated through so the rewriter gets variety. | |
| _HEDGE_SUGGESTIONS: list[str] = [ | |
| "I would argue that", | |
| "In my view,", | |
| "I think", | |
| "To my mind,", | |
| "It seems to me that", | |
| ] | |
| # --------------------------------------------------------------------------- | |
| # Factual / evidence indicators β sentences containing these should NOT | |
| # receive hedging suggestions (you don't hedge established facts). | |
| # --------------------------------------------------------------------------- | |
| _FACTUAL_INDICATORS: list[str] = [ | |
| # Evidence and data references | |
| "consensus", | |
| "evidence", | |
| "data", | |
| "studies", | |
| "study", | |
| "research", | |
| "statistics", | |
| "findings", | |
| "survey", | |
| "surveys", | |
| "report", | |
| "reports", | |
| "meta-analysis", | |
| "experiment", | |
| "experiments", | |
| "trial", | |
| "trials", | |
| "peer-reviewed", | |
| "literature", | |
| "publication", | |
| # Citation / attribution markers | |
| "according to", | |
| "found that", | |
| "reported that", | |
| "stated that", | |
| "concluded that", | |
| "published in", | |
| "cited by", | |
| # Quantified claims | |
| "percent", | |
| "%", | |
| "majority of", | |
| "most of", | |
| "proportion of", | |
| "ratio of", | |
| "rate of", | |
| "number of", | |
| "the bulk of", | |
| # Established-fact language | |
| "well-established", | |
| "well-documented", | |
| "widely accepted", | |
| "widely recognized", | |
| "scientifically", | |
| "empirically", | |
| "historically", | |
| "it is known that", | |
| ] | |
| class InformalityAnalyzer: | |
| """Identifies sentences where natural human informality can be injected. | |
| Strategy: | |
| - Scan for expanded contraction forms and suggest the contraction in | |
| approximately 50% of cases (alternating) to avoid over-contracting. | |
| - Detect sentences making strong claims and suggest adding a first-person | |
| hedge phrase at the start. | |
| - Cap total informality instructions at 15% of the total sentence count. | |
| Args: | |
| contraction_rate: Fraction of contraction matches to act on (0-1). | |
| Default 0.5 (every other match). | |
| max_informality_rate: Maximum fraction of sentences to flag for | |
| informality changes. Default 0.15. | |
| """ | |
| def __init__( | |
| self, | |
| contraction_rate: float = 0.5, | |
| max_informality_rate: float = 0.30, | |
| ) -> None: | |
| self.contraction_rate = contraction_rate | |
| self.max_informality_rate = max_informality_rate | |
| # ------------------------------------------------------------------ | |
| # Public API | |
| # ------------------------------------------------------------------ | |
| def analyze(self, sentences: list[str]) -> list[dict]: | |
| """Find informality injection opportunities. | |
| Args: | |
| sentences: List of sentence strings. | |
| Returns: | |
| List of instruction dicts with type='informality', sentence_index, | |
| severity='low', and instruction. | |
| """ | |
| if not sentences: | |
| return [] | |
| instructions: list[dict] = [] | |
| max_instructions = max(1, int(len(sentences) * self.max_informality_rate)) | |
| # -- Contraction opportunities ---------------------------------- | |
| contraction_instructions = self._find_contraction_opportunities(sentences) | |
| instructions.extend(contraction_instructions) | |
| # -- First-person hedging opportunities ------------------------ | |
| hedge_instructions = self._find_hedge_opportunities(sentences) | |
| # Avoid duplicating instructions for sentences already flagged. | |
| already_flagged = {instr['sentence_index'] for instr in instructions} | |
| for instr in hedge_instructions: | |
| if instr['sentence_index'] not in already_flagged: | |
| instructions.append(instr) | |
| already_flagged.add(instr['sentence_index']) | |
| # -- Cap at 15% of total sentences ----------------------------- | |
| if len(instructions) > max_instructions: | |
| instructions = instructions[:max_instructions] | |
| return instructions | |
| # ------------------------------------------------------------------ | |
| # Private helpers | |
| # ------------------------------------------------------------------ | |
| def _find_contraction_opportunities(self, sentences: list[str]) -> list[dict]: | |
| """Scan sentences for expanded contraction forms. | |
| Every other match is selected (contraction_rate β 0.5) to avoid | |
| making the text feel over-contracted. | |
| Args: | |
| sentences: List of sentence strings. | |
| Returns: | |
| List of informality instruction dicts. | |
| """ | |
| instructions: list[dict] = [] | |
| match_count = 0 # Global match counter used for alternation. | |
| for idx, sentence in enumerate(sentences): | |
| matched_pairs: list[tuple[str, str]] = [] | |
| for pattern, contraction in _COMPILED_CONTRACTIONS: | |
| if pattern.search(sentence): | |
| # Find the actual matched text to show in the instruction. | |
| m = pattern.search(sentence) | |
| if m: | |
| matched_pairs.append((m.group(0), contraction)) | |
| if not matched_pairs: | |
| continue | |
| # Apply the alternation filter: only act on ~50% of matches. | |
| for expanded_form, contraction in matched_pairs: | |
| match_count += 1 | |
| if match_count % 2 == 0: | |
| # Skip this match (every other one). | |
| continue | |
| instructions.append({ | |
| 'type': 'informality', | |
| 'sentence_index': idx, | |
| 'severity': 'low', | |
| 'instruction': ( | |
| f'Replace "{expanded_form}" with the contraction ' | |
| f'"{contraction}" to make this sentence feel more natural ' | |
| f'and less robotic. Formal expanded forms are overused in ' | |
| f'AI text; a contraction here matches natural speech rhythm.' | |
| ), | |
| }) | |
| # Only flag one contraction per sentence to keep it readable. | |
| break | |
| return instructions | |
| def _find_hedge_opportunities(self, sentences: list[str]) -> list[dict]: | |
| """Detect sentences making strong claims and suggest hedging. | |
| A sentence is flagged when it contains one of the strong-claim | |
| trigger words/phrases. The suggestion is to prepend a first-person | |
| hedging phrase, rotating through _HEDGE_SUGGESTIONS for variety. | |
| Args: | |
| sentences: List of sentence strings. | |
| Returns: | |
| List of informality instruction dicts. | |
| """ | |
| instructions: list[dict] = [] | |
| hedge_idx = 0 # Rotate through hedge suggestions. | |
| for sent_idx, sentence in enumerate(sentences): | |
| sent_lower = sentence.lower() | |
| matched_trigger: str | None = None | |
| for trigger in _STRONG_CLAIM_TRIGGERS: | |
| # Use word-boundary matching for single-word triggers and | |
| # substring matching for phrase triggers. | |
| if ' ' in trigger: | |
| if trigger in sent_lower: | |
| matched_trigger = trigger | |
| break | |
| else: | |
| if re.search(r'\b' + re.escape(trigger) + r'\b', sent_lower): | |
| matched_trigger = trigger | |
| break | |
| if matched_trigger: | |
| # Skip hedging for factual / evidence-backed sentences. | |
| if self._is_factual_sentence(sent_lower): | |
| continue | |
| hedge = _HEDGE_SUGGESTIONS[hedge_idx % len(_HEDGE_SUGGESTIONS)] | |
| hedge_idx += 1 | |
| instructions.append({ | |
| 'type': 'informality', | |
| 'sentence_index': sent_idx, | |
| 'severity': 'low', | |
| 'instruction': ( | |
| f'This sentence makes a strong claim ("{matched_trigger}") ' | |
| f'without hedging β typical of over-confident AI prose. ' | |
| f'Consider opening it with a first-person qualifier such as ' | |
| f'"{hedge}" to introduce a human perspective and soften the ' | |
| f'assertion into an argued position rather than stated fact.' | |
| ), | |
| }) | |
| return instructions | |
| def _is_factual_sentence(sentence_lower: str) -> bool: | |
| """Return True if the sentence references evidence, data, or consensus. | |
| Factual claims backed by evidence should not receive hedging | |
| suggestions -- hedging "The scientific consensus supports..." would | |
| be misleading. | |
| """ | |
| for indicator in _FACTUAL_INDICATORS: | |
| if indicator in sentence_lower: | |
| return True | |
| return False | |