Spaces:
Runtime error

humanizer-engine / app /utils /text_utils.py
faseehsandhu's picture
stage 1 completed
f66da21
Raw History Blame Contribute Delete
4.57 kB
"""
Text utility functions used across all pipeline stages.
All functions are pure (no side effects) and operate on plain strings.
spaCy is used for sentence splitting to ensure accuracy; callers must pass
the loaded nlp object rather than importing it here (keeps this module
side-effect free and testable without spaCy installed).
"""
from __future__ import annotations
import re
import statistics
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import spacy # type: ignore
# ---------------------------------------------------------------------------
# Word counting
# ---------------------------------------------------------------------------
def count_words(text: str) -> int:
"""Return the number of whitespace-delimited tokens in *text*.
Args:
text: Input string (any length).
Returns:
Integer word count. Empty or whitespace-only strings return 0.
"""
return len(text.split())
# ---------------------------------------------------------------------------
# Sentence splitting
# ---------------------------------------------------------------------------
def split_sentences(text: str, nlp: "spacy.Language | None" = None) -> list[str]:
"""Split *text* into a list of sentence strings.
Uses spaCy's sentenciser when *nlp* is provided for high accuracy.
Falls back to a simple regex-based splitter when spaCy is unavailable
(e.g. in unit tests that do not load the model).
Args:
text: The input text to split.
nlp: An already-loaded spaCy Language model, or None.
Returns:
List of sentence strings with leading/trailing whitespace stripped.
Empty sentences are excluded.
"""
if nlp is not None:
doc = nlp(text)
return [sent.text.strip() for sent in doc.sents if sent.text.strip()]
# Fallback: split on ". ", "! ", "? " boundaries
raw = re.split(r"(?<=[.!?])\s+", text.strip())
return [s.strip() for s in raw if s.strip()]
# ---------------------------------------------------------------------------
# Burstiness / sentence-length statistics
# ---------------------------------------------------------------------------
def calculate_burstiness(sentence_lengths: list[int]) -> dict[str, float]:
"""Calculate burstiness statistics for a list of sentence word-counts.
Burstiness is measured by the coefficient of variation (CV = std / mean).
Human writing typically has CV ≥ 0.45; AI text tends to cluster around
CV 0.15-0.30.
Args:
sentence_lengths: List of word counts, one per sentence.
Returns:
Dict with keys: mean, std, cv, min_length, max_length.
If fewer than 2 sentences are provided all values are 0.0.
"""
if len(sentence_lengths) < 2:
single = float(sentence_lengths[0]) if sentence_lengths else 0.0
return {
"mean": single,
"std": 0.0,
"cv": 0.0,
"min_length": single,
"max_length": single,
}
mean = statistics.mean(sentence_lengths)
std = statistics.stdev(sentence_lengths)
cv = std / mean if mean > 0 else 0.0
return {
"mean": round(mean, 2),
"std": round(std, 2),
"cv": round(cv, 4),
"min_length": float(min(sentence_lengths)),
"max_length": float(max(sentence_lengths)),
}
# ---------------------------------------------------------------------------
# Expansion / length comparison
# ---------------------------------------------------------------------------
def calculate_expansion_percentage(input_count: int, output_count: int) -> float:
"""Return how much longer (as a percentage) the output is vs the input.
Args:
input_count: Word count of the original text.
output_count: Word count of the rewritten text.
Returns:
Positive value means expansion; negative means contraction.
Returns 0.0 when input_count is 0.
"""
if input_count == 0:
return 0.0
return round((output_count - input_count) / input_count * 100, 2)
# ---------------------------------------------------------------------------
# Sentence word-count helper
# ---------------------------------------------------------------------------
def sentence_word_counts(sentences: list[str]) -> list[int]:
"""Return a list of word counts for each sentence.
Args:
sentences: List of sentence strings.
Returns:
List of integers, same length as *sentences*.
"""
return [count_words(s) for s in sentences]