Spaces:
Runtime error
Runtime error
Commit ·
446613d
1
Parent(s): f66da21
stage 2 working
Browse files- .claude/settings.local.json +8 -1
- .gitignore +56 -0
- app/api/routes.py +216 -4
- app/core/analyzers/__pycache__/informality.cpython-313.pyc +0 -0
- app/core/analyzers/informality.py +73 -0
- app/core/llm_rewriter.py +191 -0
- app/core/perturbation.py +677 -0
- app/core/pipeline.py +187 -0
- app/core/post_validator.py +363 -0
- app/core/prompt_manager.py +176 -0
- app/main.py +92 -29
- app/prompts/variants.py +200 -0
- testing_texts.txt +184 -0
.claude/settings.local.json
CHANGED
|
@@ -6,7 +6,14 @@
|
|
| 6 |
"Bash(python3:*)",
|
| 7 |
"Bash(node:*)",
|
| 8 |
"Bash(python:*)",
|
| 9 |
-
"Bash(pip install:*)"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
]
|
| 11 |
}
|
| 12 |
}
|
|
|
|
| 6 |
"Bash(python3:*)",
|
| 7 |
"Bash(node:*)",
|
| 8 |
"Bash(python:*)",
|
| 9 |
+
"Bash(pip install:*)",
|
| 10 |
+
"WebFetch(domain:originality.ai)",
|
| 11 |
+
"WebFetch(domain:aclanthology.org)",
|
| 12 |
+
"WebFetch(domain:arxiv.org)",
|
| 13 |
+
"WebFetch(domain:www.pangram.com)",
|
| 14 |
+
"WebFetch(domain:www.academia.edu)",
|
| 15 |
+
"WebFetch(domain:www.stealthgpt.ai)",
|
| 16 |
+
"WebFetch(domain:help.originality.ai)"
|
| 17 |
]
|
| 18 |
}
|
| 19 |
}
|
.gitignore
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[cod]
|
| 4 |
+
*.pyo
|
| 5 |
+
*.pyd
|
| 6 |
+
*.egg
|
| 7 |
+
*.egg-info/
|
| 8 |
+
dist/
|
| 9 |
+
build/
|
| 10 |
+
.eggs/
|
| 11 |
+
*.whl
|
| 12 |
+
|
| 13 |
+
# Virtual environments
|
| 14 |
+
.venv/
|
| 15 |
+
venv/
|
| 16 |
+
env/
|
| 17 |
+
ENV/
|
| 18 |
+
|
| 19 |
+
# Environment variables
|
| 20 |
+
.env
|
| 21 |
+
.env.*
|
| 22 |
+
|
| 23 |
+
# Pytest / testing
|
| 24 |
+
.pytest_cache/
|
| 25 |
+
.coverage
|
| 26 |
+
htmlcov/
|
| 27 |
+
*.log
|
| 28 |
+
|
| 29 |
+
# Model cache (HuggingFace / torch)
|
| 30 |
+
.cache/
|
| 31 |
+
*.bin
|
| 32 |
+
*.pt
|
| 33 |
+
*.ckpt
|
| 34 |
+
*.safetensors
|
| 35 |
+
|
| 36 |
+
# spaCy models
|
| 37 |
+
en_core_web*/
|
| 38 |
+
|
| 39 |
+
# Jupyter
|
| 40 |
+
.ipynb_checkpoints/
|
| 41 |
+
*.ipynb
|
| 42 |
+
|
| 43 |
+
# IDE
|
| 44 |
+
.vscode/
|
| 45 |
+
.idea/
|
| 46 |
+
*.swp
|
| 47 |
+
*.swo
|
| 48 |
+
|
| 49 |
+
# OS
|
| 50 |
+
.DS_Store
|
| 51 |
+
Thumbs.db
|
| 52 |
+
|
| 53 |
+
# Misc
|
| 54 |
+
NUL
|
| 55 |
+
err.txt
|
| 56 |
+
errors.txt
|
app/api/routes.py
CHANGED
|
@@ -1,12 +1,224 @@
|
|
| 1 |
"""
|
| 2 |
-
API route definitions
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
"""
|
| 4 |
|
| 5 |
from __future__ import annotations
|
| 6 |
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
router = APIRouter()
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
+
API route definitions for the Humanization Engine.
|
| 3 |
+
|
| 4 |
+
Endpoints:
|
| 5 |
+
POST /humanize -- full 3-stage pipeline
|
| 6 |
+
POST /analyze -- Stage 1 analysis only (debug/testing)
|
| 7 |
+
GET /health -- health check
|
| 8 |
"""
|
| 9 |
|
| 10 |
from __future__ import annotations
|
| 11 |
|
| 12 |
+
import logging
|
| 13 |
+
import time
|
| 14 |
+
from collections import defaultdict
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
from fastapi import APIRouter, HTTPException, Request
|
| 18 |
+
from fastapi.responses import JSONResponse
|
| 19 |
+
|
| 20 |
+
from app.api.models import (
|
| 21 |
+
AnalyzeRequest,
|
| 22 |
+
AnalyzeResponse,
|
| 23 |
+
HealthResponse,
|
| 24 |
+
HumanizeRequest,
|
| 25 |
+
HumanizeResponse,
|
| 26 |
+
ProcessingStats,
|
| 27 |
+
)
|
| 28 |
+
from app.utils.text_utils import count_words
|
| 29 |
+
|
| 30 |
+
logger = logging.getLogger(__name__)
|
| 31 |
|
| 32 |
router = APIRouter()
|
| 33 |
|
| 34 |
+
# ---------------------------------------------------------------------------
|
| 35 |
+
# Simple in-memory rate limiter (per-IP, 17 requests per minute)
|
| 36 |
+
# ---------------------------------------------------------------------------
|
| 37 |
+
|
| 38 |
+
_rate_limit: dict[str, list[float]] = defaultdict(list)
|
| 39 |
+
_RATE_WINDOW: float = 60.0 # seconds
|
| 40 |
+
_RATE_MAX: int = 17 # requests per window
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _check_rate_limit(client_ip: str) -> bool:
|
| 44 |
+
"""Return True if the request is allowed, False if rate-limited."""
|
| 45 |
+
now = time.time()
|
| 46 |
+
timestamps = _rate_limit[client_ip]
|
| 47 |
+
|
| 48 |
+
# Remove timestamps outside the window.
|
| 49 |
+
_rate_limit[client_ip] = [t for t in timestamps if now - t < _RATE_WINDOW]
|
| 50 |
+
|
| 51 |
+
if len(_rate_limit[client_ip]) >= _RATE_MAX:
|
| 52 |
+
return False
|
| 53 |
+
|
| 54 |
+
_rate_limit[client_ip].append(now)
|
| 55 |
+
return True
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# ---------------------------------------------------------------------------
|
| 59 |
+
# POST /humanize
|
| 60 |
+
# ---------------------------------------------------------------------------
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@router.post("/humanize", response_model=HumanizeResponse)
|
| 64 |
+
async def humanize(request: Request, body: HumanizeRequest) -> Any:
|
| 65 |
+
"""Run the full humanization pipeline (Stage 1 -> 2 -> 3)."""
|
| 66 |
+
client_ip = request.client.host if request.client else "unknown"
|
| 67 |
+
|
| 68 |
+
if not _check_rate_limit(client_ip):
|
| 69 |
+
return JSONResponse(
|
| 70 |
+
status_code=429,
|
| 71 |
+
content={"success": False, "error": "Rate limit exceeded", "code": "RATE_LIMITED"},
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
# Input validation.
|
| 75 |
+
from app.config import get_settings
|
| 76 |
+
settings = get_settings()
|
| 77 |
+
word_count = count_words(body.text)
|
| 78 |
+
|
| 79 |
+
if word_count < settings.min_input_words:
|
| 80 |
+
return JSONResponse(
|
| 81 |
+
status_code=400,
|
| 82 |
+
content={
|
| 83 |
+
"success": False,
|
| 84 |
+
"error": f"Input too short: {word_count} words (minimum {settings.min_input_words})",
|
| 85 |
+
"code": "INPUT_TOO_SHORT",
|
| 86 |
+
},
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
if word_count > settings.max_input_words:
|
| 90 |
+
return JSONResponse(
|
| 91 |
+
status_code=400,
|
| 92 |
+
content={
|
| 93 |
+
"success": False,
|
| 94 |
+
"error": f"Input too long: {word_count} words (maximum {settings.max_input_words})",
|
| 95 |
+
"code": "INPUT_TOO_LONG",
|
| 96 |
+
},
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
# Get pipeline from app state.
|
| 100 |
+
pipeline = getattr(request.app.state, "pipeline", None)
|
| 101 |
+
if pipeline is None:
|
| 102 |
+
return JSONResponse(
|
| 103 |
+
status_code=503,
|
| 104 |
+
content={
|
| 105 |
+
"success": False,
|
| 106 |
+
"error": "Pipeline not initialized. Server is starting up.",
|
| 107 |
+
"code": "PROCESSING_ERROR",
|
| 108 |
+
},
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
logger.info("POST /humanize: %d words, mode=%s, ip=%s", word_count, body.mode, client_ip)
|
| 112 |
+
|
| 113 |
+
try:
|
| 114 |
+
result = await pipeline.process(body.text, mode=body.mode)
|
| 115 |
+
except Exception as exc:
|
| 116 |
+
logger.error("Pipeline error: %s", exc, exc_info=True)
|
| 117 |
+
return JSONResponse(
|
| 118 |
+
status_code=500,
|
| 119 |
+
content={
|
| 120 |
+
"success": False,
|
| 121 |
+
"error": "Internal processing error",
|
| 122 |
+
"code": "PROCESSING_ERROR",
|
| 123 |
+
},
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
# If both LLMs failed, return an error instead of the original text.
|
| 127 |
+
if not result.get("success", False):
|
| 128 |
+
error_msg = result.get("error", "LLM rewrite failed")
|
| 129 |
+
logger.error("Pipeline returned failure: %s", error_msg)
|
| 130 |
+
return JSONResponse(
|
| 131 |
+
status_code=502,
|
| 132 |
+
content={
|
| 133 |
+
"success": False,
|
| 134 |
+
"error": f"LLM rewrite failed: {error_msg}",
|
| 135 |
+
"code": "LLM_TIMEOUT",
|
| 136 |
+
},
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
stats_raw = result.get("stats", {})
|
| 140 |
+
stats = ProcessingStats(
|
| 141 |
+
input_word_count=stats_raw.get("input_word_count", word_count),
|
| 142 |
+
output_word_count=stats_raw.get("output_word_count", 0),
|
| 143 |
+
expansion_percentage=stats_raw.get("expansion_percentage", 0.0),
|
| 144 |
+
input_avg_perplexity=stats_raw.get("input_avg_perplexity"),
|
| 145 |
+
output_avg_perplexity=stats_raw.get("output_avg_perplexity"),
|
| 146 |
+
input_burstiness_cv=stats_raw.get("input_burstiness_cv"),
|
| 147 |
+
output_burstiness_cv=stats_raw.get("output_burstiness_cv"),
|
| 148 |
+
banned_words_found_in_output=stats_raw.get("banned_words_found_in_output", []),
|
| 149 |
+
banned_words_auto_fixed=stats_raw.get("banned_words_auto_fixed", 0),
|
| 150 |
+
instructions_generated=stats_raw.get("instructions_generated", 0),
|
| 151 |
+
high_risk_sentences=stats_raw.get("high_risk_sentences", 0),
|
| 152 |
+
processing_time_ms=stats_raw.get("processing_time_ms", 0.0),
|
| 153 |
+
stage1_time_ms=stats_raw.get("stage1_time_ms", 0.0),
|
| 154 |
+
stage2_time_ms=stats_raw.get("stage2_time_ms", 0.0),
|
| 155 |
+
stage3_time_ms=stats_raw.get("stage3_time_ms", 0.0),
|
| 156 |
+
prompt_variant_used=stats_raw.get("prompt_variant_used", ""),
|
| 157 |
+
llm_used=stats_raw.get("llm_used", ""),
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
return HumanizeResponse(
|
| 161 |
+
output_text=result.get("output_text", body.text),
|
| 162 |
+
stats=stats,
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
# ---------------------------------------------------------------------------
|
| 167 |
+
# POST /analyze
|
| 168 |
+
# ---------------------------------------------------------------------------
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
@router.post("/analyze", response_model=AnalyzeResponse)
|
| 172 |
+
async def analyze(request: Request, body: AnalyzeRequest) -> Any:
|
| 173 |
+
"""Run Stage 1 analysis only (no LLM call). Useful for debugging."""
|
| 174 |
+
analyzer = getattr(request.app.state, "analyzer", None)
|
| 175 |
+
if analyzer is None:
|
| 176 |
+
return JSONResponse(
|
| 177 |
+
status_code=503,
|
| 178 |
+
content={
|
| 179 |
+
"success": False,
|
| 180 |
+
"error": "Analyzer not initialized. Server is starting up.",
|
| 181 |
+
"code": "PROCESSING_ERROR",
|
| 182 |
+
},
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
logger.info("POST /analyze: %d words", count_words(body.text))
|
| 186 |
+
|
| 187 |
+
try:
|
| 188 |
+
analysis = analyzer.analyze(body.text)
|
| 189 |
+
except Exception as exc:
|
| 190 |
+
logger.error("Analysis error: %s", exc, exc_info=True)
|
| 191 |
+
return JSONResponse(
|
| 192 |
+
status_code=500,
|
| 193 |
+
content={"success": False, "error": str(exc), "code": "PROCESSING_ERROR"},
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
return AnalyzeResponse(analysis=analysis)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
# ---------------------------------------------------------------------------
|
| 200 |
+
# GET /health
|
| 201 |
+
# ---------------------------------------------------------------------------
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
@router.get("/health", response_model=HealthResponse)
|
| 205 |
+
async def health(request: Request) -> Any:
|
| 206 |
+
"""Health check endpoint."""
|
| 207 |
+
from app.main import get_start_time, get_models_loaded
|
| 208 |
+
|
| 209 |
+
models_loaded = get_models_loaded()
|
| 210 |
+
start_time = get_start_time()
|
| 211 |
+
uptime = round(time.time() - start_time, 1) if start_time > 0 else 0.0
|
| 212 |
+
|
| 213 |
+
status = "healthy" if models_loaded else "starting"
|
| 214 |
+
|
| 215 |
+
# Check if critical components are available.
|
| 216 |
+
has_pipeline = getattr(request.app.state, "pipeline", None) is not None
|
| 217 |
+
if models_loaded and not has_pipeline:
|
| 218 |
+
status = "degraded"
|
| 219 |
+
|
| 220 |
+
return HealthResponse(
|
| 221 |
+
status=status,
|
| 222 |
+
models_loaded=models_loaded,
|
| 223 |
+
uptime_seconds=uptime,
|
| 224 |
+
)
|
app/core/analyzers/__pycache__/informality.cpython-313.pyc
CHANGED
|
Binary files a/app/core/analyzers/__pycache__/informality.cpython-313.pyc and b/app/core/analyzers/__pycache__/informality.cpython-313.pyc differ
|
|
|
app/core/analyzers/informality.py
CHANGED
|
@@ -112,6 +112,62 @@ _HEDGE_SUGGESTIONS: list[str] = [
|
|
| 112 |
"It seems to me that",
|
| 113 |
]
|
| 114 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
class InformalityAnalyzer:
|
| 117 |
"""Identifies sentences where natural human informality can be injected.
|
|
@@ -265,6 +321,10 @@ class InformalityAnalyzer:
|
|
| 265 |
break
|
| 266 |
|
| 267 |
if matched_trigger:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
hedge = _HEDGE_SUGGESTIONS[hedge_idx % len(_HEDGE_SUGGESTIONS)]
|
| 269 |
hedge_idx += 1
|
| 270 |
|
|
@@ -282,3 +342,16 @@ class InformalityAnalyzer:
|
|
| 282 |
})
|
| 283 |
|
| 284 |
return instructions
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
"It seems to me that",
|
| 113 |
]
|
| 114 |
|
| 115 |
+
# ---------------------------------------------------------------------------
|
| 116 |
+
# Factual / evidence indicators — sentences containing these should NOT
|
| 117 |
+
# receive hedging suggestions (you don't hedge established facts).
|
| 118 |
+
# ---------------------------------------------------------------------------
|
| 119 |
+
|
| 120 |
+
_FACTUAL_INDICATORS: list[str] = [
|
| 121 |
+
# Evidence and data references
|
| 122 |
+
"consensus",
|
| 123 |
+
"evidence",
|
| 124 |
+
"data",
|
| 125 |
+
"studies",
|
| 126 |
+
"study",
|
| 127 |
+
"research",
|
| 128 |
+
"statistics",
|
| 129 |
+
"findings",
|
| 130 |
+
"survey",
|
| 131 |
+
"surveys",
|
| 132 |
+
"report",
|
| 133 |
+
"reports",
|
| 134 |
+
"meta-analysis",
|
| 135 |
+
"experiment",
|
| 136 |
+
"experiments",
|
| 137 |
+
"trial",
|
| 138 |
+
"trials",
|
| 139 |
+
"peer-reviewed",
|
| 140 |
+
"literature",
|
| 141 |
+
"publication",
|
| 142 |
+
# Citation / attribution markers
|
| 143 |
+
"according to",
|
| 144 |
+
"found that",
|
| 145 |
+
"reported that",
|
| 146 |
+
"stated that",
|
| 147 |
+
"concluded that",
|
| 148 |
+
"published in",
|
| 149 |
+
"cited by",
|
| 150 |
+
# Quantified claims
|
| 151 |
+
"percent",
|
| 152 |
+
"%",
|
| 153 |
+
"majority of",
|
| 154 |
+
"most of",
|
| 155 |
+
"proportion of",
|
| 156 |
+
"ratio of",
|
| 157 |
+
"rate of",
|
| 158 |
+
"number of",
|
| 159 |
+
"the bulk of",
|
| 160 |
+
# Established-fact language
|
| 161 |
+
"well-established",
|
| 162 |
+
"well-documented",
|
| 163 |
+
"widely accepted",
|
| 164 |
+
"widely recognized",
|
| 165 |
+
"scientifically",
|
| 166 |
+
"empirically",
|
| 167 |
+
"historically",
|
| 168 |
+
"it is known that",
|
| 169 |
+
]
|
| 170 |
+
|
| 171 |
|
| 172 |
class InformalityAnalyzer:
|
| 173 |
"""Identifies sentences where natural human informality can be injected.
|
|
|
|
| 321 |
break
|
| 322 |
|
| 323 |
if matched_trigger:
|
| 324 |
+
# Skip hedging for factual / evidence-backed sentences.
|
| 325 |
+
if self._is_factual_sentence(sent_lower):
|
| 326 |
+
continue
|
| 327 |
+
|
| 328 |
hedge = _HEDGE_SUGGESTIONS[hedge_idx % len(_HEDGE_SUGGESTIONS)]
|
| 329 |
hedge_idx += 1
|
| 330 |
|
|
|
|
| 342 |
})
|
| 343 |
|
| 344 |
return instructions
|
| 345 |
+
|
| 346 |
+
@staticmethod
|
| 347 |
+
def _is_factual_sentence(sentence_lower: str) -> bool:
|
| 348 |
+
"""Return True if the sentence references evidence, data, or consensus.
|
| 349 |
+
|
| 350 |
+
Factual claims backed by evidence should not receive hedging
|
| 351 |
+
suggestions -- hedging "The scientific consensus supports..." would
|
| 352 |
+
be misleading.
|
| 353 |
+
"""
|
| 354 |
+
for indicator in _FACTUAL_INDICATORS:
|
| 355 |
+
if indicator in sentence_lower:
|
| 356 |
+
return True
|
| 357 |
+
return False
|
app/core/llm_rewriter.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
LLM Rewriter -- Stage 2 of the humanization pipeline.
|
| 3 |
+
|
| 4 |
+
KEY INSIGHT FROM RESEARCH (RAID Benchmark ACL 2024):
|
| 5 |
+
- Originality.ai uses an ELECTRA-style discriminator trained on millions of samples
|
| 6 |
+
including humanized/paraphrased content.
|
| 7 |
+
- GPT-4o is detected at 97.8% under standard parameters.
|
| 8 |
+
- Using the same model twice (two-pass) reinforces the same statistical fingerprint.
|
| 9 |
+
- High frequency/presence penalty + high temperature = more unusual token choices
|
| 10 |
+
= higher perplexity = harder to detect.
|
| 11 |
+
- Changing the generation FRAMING (not "rewrite" but "write from notes") produces
|
| 12 |
+
different statistical distributions.
|
| 13 |
+
|
| 14 |
+
Strategy:
|
| 15 |
+
Single pass. High diversity parameters. "Write from notes" framing, not "rewrite".
|
| 16 |
+
Fallback to secondary LLM if primary fails.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import asyncio
|
| 22 |
+
import logging
|
| 23 |
+
import time
|
| 24 |
+
from dataclasses import dataclass
|
| 25 |
+
from typing import Any
|
| 26 |
+
|
| 27 |
+
from app.config import get_settings
|
| 28 |
+
from app.core.prompt_manager import PromptManager
|
| 29 |
+
from app.utils.text_utils import count_words
|
| 30 |
+
from app.utils.token_utils import calculate_max_tokens
|
| 31 |
+
|
| 32 |
+
logger = logging.getLogger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@dataclass
|
| 36 |
+
class RewriteResult:
|
| 37 |
+
"""Return value from LLMRewriter.rewrite()."""
|
| 38 |
+
|
| 39 |
+
output_text: str = ""
|
| 40 |
+
success: bool = False
|
| 41 |
+
llm_used: str = ""
|
| 42 |
+
variant_used: str = ""
|
| 43 |
+
stage2_time_ms: float = 0.0
|
| 44 |
+
error: str = ""
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class LLMRewriter:
|
| 48 |
+
"""Async LLM rewriter with primary/fallback support.
|
| 49 |
+
|
| 50 |
+
Uses a single-pass approach with high diversity parameters.
|
| 51 |
+
Two-pass (same model) was removed: it reinforces the statistical fingerprint.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
def __init__(self, prompt_manager: PromptManager | None = None) -> None:
|
| 55 |
+
self.prompt_manager = prompt_manager or PromptManager()
|
| 56 |
+
self._settings = get_settings()
|
| 57 |
+
|
| 58 |
+
async def rewrite(
|
| 59 |
+
self,
|
| 60 |
+
original_text: str,
|
| 61 |
+
analysis_result: dict[str, Any],
|
| 62 |
+
) -> RewriteResult:
|
| 63 |
+
"""Single-pass rewrite with high diversity parameters."""
|
| 64 |
+
t0 = time.perf_counter()
|
| 65 |
+
|
| 66 |
+
system_prompt, user_content, variant_id = self.prompt_manager.build_prompt(
|
| 67 |
+
original_text, analysis_result
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
word_count = count_words(original_text)
|
| 71 |
+
max_tokens = calculate_max_tokens(word_count)
|
| 72 |
+
|
| 73 |
+
# Determine primary and fallback
|
| 74 |
+
if self._settings.primary_llm == "claude":
|
| 75 |
+
primary_fn = self._call_claude
|
| 76 |
+
fallback_fn = self._call_openai
|
| 77 |
+
primary_name = f"claude ({self._settings.claude_model})"
|
| 78 |
+
fallback_name = f"openai ({self._settings.openai_model})"
|
| 79 |
+
else:
|
| 80 |
+
primary_fn = self._call_openai
|
| 81 |
+
fallback_fn = self._call_claude
|
| 82 |
+
primary_name = f"openai ({self._settings.openai_model})"
|
| 83 |
+
fallback_name = f"claude ({self._settings.claude_model})"
|
| 84 |
+
|
| 85 |
+
# Try primary
|
| 86 |
+
output_text, error = await self._try_call(
|
| 87 |
+
primary_fn, system_prompt, user_content, max_tokens, primary_name
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
if output_text:
|
| 91 |
+
elapsed = (time.perf_counter() - t0) * 1000
|
| 92 |
+
return RewriteResult(
|
| 93 |
+
output_text=output_text,
|
| 94 |
+
success=True,
|
| 95 |
+
llm_used=primary_name,
|
| 96 |
+
variant_used=variant_id,
|
| 97 |
+
stage2_time_ms=round(elapsed, 1),
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
# Try fallback
|
| 101 |
+
logger.warning("Primary (%s) failed: %s. Trying fallback.", primary_name, error)
|
| 102 |
+
output_text, error2 = await self._try_call(
|
| 103 |
+
fallback_fn, system_prompt, user_content, max_tokens, fallback_name
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
elapsed = (time.perf_counter() - t0) * 1000
|
| 107 |
+
|
| 108 |
+
if output_text:
|
| 109 |
+
return RewriteResult(
|
| 110 |
+
output_text=output_text,
|
| 111 |
+
success=True,
|
| 112 |
+
llm_used=fallback_name,
|
| 113 |
+
variant_used=variant_id,
|
| 114 |
+
stage2_time_ms=round(elapsed, 1),
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
logger.error("Both LLMs failed. Primary: %s. Fallback: %s.", error, error2)
|
| 118 |
+
return RewriteResult(
|
| 119 |
+
output_text=original_text,
|
| 120 |
+
success=False,
|
| 121 |
+
llm_used="none",
|
| 122 |
+
variant_used=variant_id,
|
| 123 |
+
stage2_time_ms=round(elapsed, 1),
|
| 124 |
+
error=f"Primary: {error}; Fallback: {error2}",
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
async def _try_call(self, call_fn, system_prompt, user_content, max_tokens, name):
|
| 128 |
+
"""Call an LLM with timeout. Returns (text, error)."""
|
| 129 |
+
timeout = self._settings.llm_timeout_seconds
|
| 130 |
+
try:
|
| 131 |
+
output = await asyncio.wait_for(
|
| 132 |
+
call_fn(system_prompt, user_content, max_tokens),
|
| 133 |
+
timeout=timeout,
|
| 134 |
+
)
|
| 135 |
+
if output and output.strip():
|
| 136 |
+
return output.strip(), ""
|
| 137 |
+
return "", f"{name} returned empty output"
|
| 138 |
+
except asyncio.TimeoutError:
|
| 139 |
+
return "", f"{name} timed out after {timeout}s"
|
| 140 |
+
except Exception as exc:
|
| 141 |
+
return "", f"{name} error: {exc}"
|
| 142 |
+
|
| 143 |
+
async def _call_claude(self, system_prompt: str, user_content: str, max_tokens: int) -> str:
|
| 144 |
+
"""Call Anthropic Claude API."""
|
| 145 |
+
from anthropic import AsyncAnthropic
|
| 146 |
+
|
| 147 |
+
api_key = self._settings.anthropic_api_key
|
| 148 |
+
if not api_key:
|
| 149 |
+
raise ValueError("ANTHROPIC_API_KEY not set")
|
| 150 |
+
|
| 151 |
+
client = AsyncAnthropic(api_key=api_key)
|
| 152 |
+
message = await client.messages.create(
|
| 153 |
+
model=self._settings.claude_model,
|
| 154 |
+
max_tokens=max_tokens,
|
| 155 |
+
temperature=1.0, # Claude performs well at max temperature
|
| 156 |
+
top_p=0.99,
|
| 157 |
+
system=system_prompt,
|
| 158 |
+
messages=[{"role": "user", "content": user_content}],
|
| 159 |
+
)
|
| 160 |
+
return message.content[0].text if message.content else ""
|
| 161 |
+
|
| 162 |
+
async def _call_openai(self, system_prompt: str, user_content: str, max_tokens: int) -> str:
|
| 163 |
+
"""Call OpenAI ChatCompletion API.
|
| 164 |
+
|
| 165 |
+
Diversity parameters calibrated to raise perplexity without causing degeneration:
|
| 166 |
+
- frequency_penalty=0.9: Raises perplexity meaningfully without word-salad collapse
|
| 167 |
+
- presence_penalty=0.6: Broadens vocabulary range at a stable level
|
| 168 |
+
- temperature=1.0: Max safe temperature; above 1.0 triggers degeneration on long outputs
|
| 169 |
+
- top_p=0.98: Near-full distribution, allows rare tokens to surface
|
| 170 |
+
"""
|
| 171 |
+
from openai import AsyncOpenAI
|
| 172 |
+
|
| 173 |
+
api_key = self._settings.openai_api_key
|
| 174 |
+
if not api_key:
|
| 175 |
+
raise ValueError("OPENAI_API_KEY not set")
|
| 176 |
+
|
| 177 |
+
client = AsyncOpenAI(api_key=api_key)
|
| 178 |
+
response = await client.chat.completions.create(
|
| 179 |
+
model=self._settings.openai_model,
|
| 180 |
+
max_tokens=max_tokens,
|
| 181 |
+
temperature=1.0,
|
| 182 |
+
top_p=0.98,
|
| 183 |
+
frequency_penalty=0.9,
|
| 184 |
+
presence_penalty=0.6,
|
| 185 |
+
messages=[
|
| 186 |
+
{"role": "system", "content": system_prompt},
|
| 187 |
+
{"role": "user", "content": user_content},
|
| 188 |
+
],
|
| 189 |
+
)
|
| 190 |
+
choice = response.choices[0] if response.choices else None
|
| 191 |
+
return choice.message.content if choice and choice.message else ""
|
app/core/perturbation.py
ADDED
|
@@ -0,0 +1,677 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Text Perturbation Engine -- breaks AI statistical fingerprint.
|
| 3 |
+
|
| 4 |
+
Based on Wikipedia's "Signs of AI writing" (WikiProject AI Cleanup).
|
| 5 |
+
|
| 6 |
+
Three layers of cleanup:
|
| 7 |
+
|
| 8 |
+
1. AI pattern elimination (rule-based, deterministic):
|
| 9 |
+
- Negative parallelisms ("It's not just X; it's Y")
|
| 10 |
+
- Copula avoidance ("serves as" -> "is", "stands as" -> "is")
|
| 11 |
+
- Superficial -ing tails ("...highlighting X", "...underscoring Y")
|
| 12 |
+
- Generic positive conclusions
|
| 13 |
+
- Filler phrases ("In order to", "Due to the fact that", "At its core")
|
| 14 |
+
|
| 15 |
+
2. Surface cleanup:
|
| 16 |
+
- Strip AI formatting (em-dashes, markdown, smart quotes)
|
| 17 |
+
- Replace AI vocabulary the LLM generated fresh
|
| 18 |
+
- Remove AI-style paragraph openers
|
| 19 |
+
|
| 20 |
+
3. Contraction variation (humans are inconsistent with contractions)
|
| 21 |
+
|
| 22 |
+
Applied AFTER the LLM rewrite (Stage 3 post-processing).
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import logging
|
| 28 |
+
import random
|
| 29 |
+
import re
|
| 30 |
+
from typing import Any
|
| 31 |
+
|
| 32 |
+
logger = logging.getLogger(__name__)
|
| 33 |
+
|
| 34 |
+
# ---------------------------------------------------------------------------
|
| 35 |
+
# AI formatting artifacts that MUST be stripped (100%)
|
| 36 |
+
# ---------------------------------------------------------------------------
|
| 37 |
+
|
| 38 |
+
_FORMAT_REPLACEMENTS: list[tuple[str, list[str]]] = [
|
| 39 |
+
("\u2014", [", ", " -- ", " - "]), # em-dash
|
| 40 |
+
("\u2013", [", ", " - ", " -- "]), # en-dash
|
| 41 |
+
("\u2018", ["'"]), # left single smart quote
|
| 42 |
+
("\u2019", ["'"]), # right single smart quote
|
| 43 |
+
("\u201c", ['"']), # left double smart quote
|
| 44 |
+
("\u201d", ['"']), # right double smart quote
|
| 45 |
+
("\u2026", ["..."]), # ellipsis character
|
| 46 |
+
]
|
| 47 |
+
|
| 48 |
+
# ---------------------------------------------------------------------------
|
| 49 |
+
# Global AI vocabulary the LLM commonly GENERATES fresh.
|
| 50 |
+
# Single-word-safe replacements only.
|
| 51 |
+
# ---------------------------------------------------------------------------
|
| 52 |
+
|
| 53 |
+
_GLOBAL_AI_WORDS: dict[str, list[str]] = {
|
| 54 |
+
# Verbs
|
| 55 |
+
"enhance": ["lift", "raise", "sharpen", "strengthen"],
|
| 56 |
+
"utilize": ["use", "apply", "try"],
|
| 57 |
+
"optimize": ["tune", "refine", "sharpen", "fix up"],
|
| 58 |
+
"leverage": ["use", "apply", "tap"],
|
| 59 |
+
"facilitate": ["support", "enable", "help"],
|
| 60 |
+
"implement": ["deploy", "apply", "install"],
|
| 61 |
+
"streamline": ["simplify", "trim", "tighten"],
|
| 62 |
+
"prioritize": ["favor", "target", "prefer"],
|
| 63 |
+
"navigate": ["handle", "manage", "tackle"],
|
| 64 |
+
"foster": ["encourage", "build", "grow"],
|
| 65 |
+
"empower": ["enable", "free", "let"],
|
| 66 |
+
"bolster": ["strengthen", "support", "reinforce"],
|
| 67 |
+
"mitigate": ["lessen", "ease", "soften"],
|
| 68 |
+
"encompass": ["include", "cover", "span"],
|
| 69 |
+
"underscore": ["highlight", "stress", "show"],
|
| 70 |
+
"spearhead": ["lead", "drive", "champion"],
|
| 71 |
+
"revolutionize": ["reshape", "change", "overhaul"],
|
| 72 |
+
"elevate": ["raise", "lift", "heighten"],
|
| 73 |
+
"cultivate": ["grow", "build", "nurture"],
|
| 74 |
+
|
| 75 |
+
# Adjectives
|
| 76 |
+
"seamless": ["smooth", "easy", "simple", "clean"],
|
| 77 |
+
"robust": ["strong", "solid", "reliable", "sturdy"],
|
| 78 |
+
"comprehensive": ["full", "complete", "thorough", "broad"],
|
| 79 |
+
"innovative": ["new", "fresh", "creative", "novel"],
|
| 80 |
+
"pivotal": ["key", "central", "critical", "vital"],
|
| 81 |
+
"crucial": ["key", "vital", "critical", "core"],
|
| 82 |
+
"significant": ["real", "major", "big", "notable"],
|
| 83 |
+
"substantial": ["large", "sizable", "hefty", "major"],
|
| 84 |
+
"remarkable": ["impressive", "striking", "notable", "unusual"],
|
| 85 |
+
"essential": ["vital", "needed", "critical", "core"],
|
| 86 |
+
"effective": ["solid", "strong", "good", "useful"],
|
| 87 |
+
"efficient": ["fast", "quick", "capable"],
|
| 88 |
+
"straightforward": ["simple", "easy", "clear", "plain"],
|
| 89 |
+
"paramount": ["critical", "top", "supreme", "chief"],
|
| 90 |
+
"transformative": ["major", "powerful", "radical"],
|
| 91 |
+
"unprecedented": ["rare", "unusual", "unmatched"],
|
| 92 |
+
"multifaceted": ["complex", "layered", "varied"],
|
| 93 |
+
"intricate": ["complex", "detailed", "involved"],
|
| 94 |
+
"invaluable": ["priceless", "vital", "irreplaceable"],
|
| 95 |
+
"indispensable": ["vital", "necessary", "irreplaceable"],
|
| 96 |
+
"noteworthy": ["interesting", "notable", "striking"],
|
| 97 |
+
"burgeoning": ["growing", "rising", "booming"],
|
| 98 |
+
"overarching": ["main", "broad", "central"],
|
| 99 |
+
|
| 100 |
+
# Adverbs
|
| 101 |
+
"significantly": ["really", "noticeably", "greatly", "considerably"],
|
| 102 |
+
"dramatically": ["hugely", "massively", "sharply", "wildly"],
|
| 103 |
+
"particularly": ["especially", "mainly", "mostly", "chiefly"],
|
| 104 |
+
"essentially": ["basically", "really", "largely"],
|
| 105 |
+
"increasingly": ["gradually", "steadily", "progressively"],
|
| 106 |
+
"predominantly": ["mostly", "mainly", "largely", "chiefly"],
|
| 107 |
+
"subsequently": ["then", "later", "next", "afterwards"],
|
| 108 |
+
"fundamentally": ["basically", "deeply", "really", "truly"],
|
| 109 |
+
|
| 110 |
+
# Nouns
|
| 111 |
+
"landscape": ["field", "area", "scene", "world"],
|
| 112 |
+
"paradigm": ["model", "approach", "pattern"],
|
| 113 |
+
"realm": ["area", "field", "space", "domain"],
|
| 114 |
+
"framework": ["structure", "system", "setup"],
|
| 115 |
+
"methodology": ["method", "approach", "way"],
|
| 116 |
+
"infrastructure": ["setup", "backbone", "foundation"],
|
| 117 |
+
"trajectory": ["path", "direction", "course"],
|
| 118 |
+
"implications": ["effects", "results", "consequences"],
|
| 119 |
+
"dynamics": ["forces", "interactions", "workings"],
|
| 120 |
+
"stakeholders": ["parties", "players", "groups"],
|
| 121 |
+
"synergy": ["teamwork", "cooperation", "harmony"],
|
| 122 |
+
|
| 123 |
+
# Phrases
|
| 124 |
+
"it is important to note": ["keep in mind", "worth noting"],
|
| 125 |
+
"plays a crucial role": ["is central", "matters greatly"],
|
| 126 |
+
"in today's world": ["these days", "right now", "currently"],
|
| 127 |
+
"it goes without saying": ["obviously", "clearly", "of course"],
|
| 128 |
+
"in light of": ["given", "considering"],
|
| 129 |
+
"serves as a": ["acts as", "works as", "is"],
|
| 130 |
+
"has the potential to": ["could", "might", "can"],
|
| 131 |
+
"on the other hand": ["then again", "that said"],
|
| 132 |
+
|
| 133 |
+
# Common LLM transitions
|
| 134 |
+
"furthermore": ["plus", "also", "and"],
|
| 135 |
+
"moreover": ["also", "and", "plus"],
|
| 136 |
+
"additionally": ["also", "plus", "and"],
|
| 137 |
+
"consequently": ["so", "hence", "thus"],
|
| 138 |
+
"nevertheless": ["still", "yet", "but"],
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
# Word substitution map for random perturbation
|
| 142 |
+
_WORD_SUBS: dict[str, list[str]] = {
|
| 143 |
+
"boost": ["lift", "raise", "ramp up", "bump up"],
|
| 144 |
+
"improve": ["lift", "tighten up", "make better", "step up"],
|
| 145 |
+
"reduce": ["cut", "trim", "bring down", "shrink"],
|
| 146 |
+
"increase": ["bump up", "push higher", "grow", "ramp up"],
|
| 147 |
+
"provide": ["give", "offer up", "supply"],
|
| 148 |
+
"ensure": ["make sure", "confirm"],
|
| 149 |
+
"require": ["need", "call for", "take"],
|
| 150 |
+
"maintain": ["keep", "hold onto", "stick with"],
|
| 151 |
+
"achieve": ["pull off", "reach", "get to"],
|
| 152 |
+
"demonstrate": ["show", "prove", "make clear"],
|
| 153 |
+
"establish": ["set up", "build", "put together"],
|
| 154 |
+
"obtain": ["get", "grab", "pick up"],
|
| 155 |
+
"indicate": ["point to", "suggest", "hint at"],
|
| 156 |
+
"contribute": ["add to", "chip in", "feed into"],
|
| 157 |
+
"determine": ["figure out", "work out", "pin down"],
|
| 158 |
+
"develop": ["build", "put together", "grow"],
|
| 159 |
+
"generate": ["create", "produce", "come up with"],
|
| 160 |
+
"monitor": ["track", "keep an eye on", "watch"],
|
| 161 |
+
"employ": ["use", "put to work", "lean on"],
|
| 162 |
+
"address": ["deal with", "tackle", "handle"],
|
| 163 |
+
"encounter": ["run into", "face", "come across"],
|
| 164 |
+
"select": ["pick", "go with", "choose"],
|
| 165 |
+
"modify": ["change", "tweak", "adjust"],
|
| 166 |
+
"eliminate": ["get rid of", "cut out", "drop"],
|
| 167 |
+
"evaluate": ["weigh", "size up", "assess"],
|
| 168 |
+
"minimize": ["keep low", "cut down on", "limit"],
|
| 169 |
+
|
| 170 |
+
"important": ["key", "big", "a big deal"],
|
| 171 |
+
"various": ["different", "a mix of", "several"],
|
| 172 |
+
"numerous": ["plenty of", "lots of", "a bunch of"],
|
| 173 |
+
"sufficient": ["enough", "plenty"],
|
| 174 |
+
"appropriate": ["right", "fitting", "suitable"],
|
| 175 |
+
"relevant": ["related", "tied to", "connected"],
|
| 176 |
+
"specific": ["exact", "particular", "precise"],
|
| 177 |
+
"primary": ["main", "top", "chief"],
|
| 178 |
+
"potential": ["possible", "likely"],
|
| 179 |
+
"additional": ["extra", "more", "added"],
|
| 180 |
+
"initial": ["first", "early", "starting"],
|
| 181 |
+
"consistent": ["steady", "reliable", "regular"],
|
| 182 |
+
"beneficial": ["helpful", "good for", "useful"],
|
| 183 |
+
"prevalent": ["common", "widespread"],
|
| 184 |
+
"extensive": ["wide", "broad", "sweeping"],
|
| 185 |
+
|
| 186 |
+
"specifically": ["in particular", "namely"],
|
| 187 |
+
"effectively": ["in practice", "really"],
|
| 188 |
+
"traditionally": ["in the past", "historically"],
|
| 189 |
+
"ultimately": ["in the end", "when it comes down to it"],
|
| 190 |
+
"approximately": ["around", "roughly", "about"],
|
| 191 |
+
|
| 192 |
+
"individuals": ["people", "folks"],
|
| 193 |
+
"functionality": ["features", "what it does"],
|
| 194 |
+
"challenges": ["problems", "issues", "hurdles"],
|
| 195 |
+
"opportunities": ["chances", "openings"],
|
| 196 |
+
"requirements": ["needs", "demands"],
|
| 197 |
+
"objectives": ["goals", "targets"],
|
| 198 |
+
"perspective": ["view", "angle", "take"],
|
| 199 |
+
"components": ["parts", "pieces"],
|
| 200 |
+
"aspects": ["parts", "sides", "angles"],
|
| 201 |
+
"factors": ["things", "reasons", "pieces"],
|
| 202 |
+
"characteristics": ["traits", "qualities", "features"],
|
| 203 |
+
|
| 204 |
+
"however": ["but", "that said", "then again"],
|
| 205 |
+
"therefore": ["so", "that's why", "because of this"],
|
| 206 |
+
"alternatively": ["or", "another option is"],
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
# AI-style paragraph openers that should be replaced with direct starts
|
| 210 |
+
_AI_OPENERS: list[tuple[re.Pattern, str]] = [
|
| 211 |
+
(re.compile(r'^First off,?\s+', re.IGNORECASE), ""),
|
| 212 |
+
(re.compile(r'^Another trick is\s+', re.IGNORECASE), ""),
|
| 213 |
+
(re.compile(r'^How about\s+\w+\?\s*', re.IGNORECASE), ""),
|
| 214 |
+
(re.compile(r'^Now let\'?s talk about\s+', re.IGNORECASE), ""),
|
| 215 |
+
(re.compile(r'^What about\s+\w+\?\s*', re.IGNORECASE), ""),
|
| 216 |
+
(re.compile(r'^And don\'?t forget\s+', re.IGNORECASE), ""),
|
| 217 |
+
(re.compile(r'^Let\'?s dive into\s+', re.IGNORECASE), ""),
|
| 218 |
+
(re.compile(r'^Let\'?s explore\s+', re.IGNORECASE), ""),
|
| 219 |
+
(re.compile(r'^Here\'?s the (?:thing|deal)[:,]?\s*', re.IGNORECASE), ""),
|
| 220 |
+
(re.compile(r'^So what\'?s the bottom line\?\s*', re.IGNORECASE), ""),
|
| 221 |
+
(re.compile(r'^Moving on,?\s+', re.IGNORECASE), ""),
|
| 222 |
+
(re.compile(r'^Next up,?\s+', re.IGNORECASE), ""),
|
| 223 |
+
]
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
# ---------------------------------------------------------------------------
|
| 227 |
+
# Public API
|
| 228 |
+
# ---------------------------------------------------------------------------
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
class TextPerturber:
|
| 232 |
+
"""Introduces controlled imperfections to break AI statistical fingerprint.
|
| 233 |
+
|
| 234 |
+
Works at the word/phrase level only. Does NOT restructure paragraphs,
|
| 235 |
+
merge/split sentences, or inject fragments. Those structural changes
|
| 236 |
+
follow LLM rewriting patterns that detectors flag.
|
| 237 |
+
"""
|
| 238 |
+
|
| 239 |
+
def __init__(
|
| 240 |
+
self,
|
| 241 |
+
intensity: float = 0.12,
|
| 242 |
+
filler_rate: float = 0.05,
|
| 243 |
+
) -> None:
|
| 244 |
+
self.intensity = max(0.0, min(1.0, intensity))
|
| 245 |
+
self.filler_rate = filler_rate # kept for interface compat but not used
|
| 246 |
+
|
| 247 |
+
# Pre-compile patterns
|
| 248 |
+
self._sub_patterns: list[tuple[re.Pattern, list[str]]] = []
|
| 249 |
+
for word, replacements in _WORD_SUBS.items():
|
| 250 |
+
pattern = re.compile(r'\b' + re.escape(word) + r'\b', re.IGNORECASE)
|
| 251 |
+
self._sub_patterns.append((pattern, replacements))
|
| 252 |
+
|
| 253 |
+
self._ai_patterns: list[tuple[re.Pattern, list[str], str]] = []
|
| 254 |
+
for word, replacements in _GLOBAL_AI_WORDS.items():
|
| 255 |
+
pattern = re.compile(r'\b' + re.escape(word) + r'\b', re.IGNORECASE)
|
| 256 |
+
self._ai_patterns.append((pattern, replacements, word))
|
| 257 |
+
|
| 258 |
+
# ------------------------------------------------------------------
|
| 259 |
+
# Main entry point
|
| 260 |
+
# ------------------------------------------------------------------
|
| 261 |
+
|
| 262 |
+
def perturb(self, text: str) -> str:
|
| 263 |
+
"""Apply perturbations to the text.
|
| 264 |
+
|
| 265 |
+
Order:
|
| 266 |
+
1. Wikipedia AI pattern elimination (rule-based)
|
| 267 |
+
2. Strip AI formatting (em-dashes, markdown, smart quotes)
|
| 268 |
+
3. Remove AI-style paragraph openers
|
| 269 |
+
4. Global AI vocabulary replacement
|
| 270 |
+
5. Random word substitutions
|
| 271 |
+
6. Contraction inconsistency
|
| 272 |
+
"""
|
| 273 |
+
text = self._eliminate_ai_patterns(text)
|
| 274 |
+
text = self._strip_ai_formatting(text)
|
| 275 |
+
text = self._remove_ai_openers(text)
|
| 276 |
+
text = self._replace_global_ai_words(text)
|
| 277 |
+
text = self._substitute_words(text)
|
| 278 |
+
text = self._vary_contractions(text)
|
| 279 |
+
return text
|
| 280 |
+
|
| 281 |
+
# ------------------------------------------------------------------
|
| 282 |
+
# Step 0: Wikipedia AI pattern elimination (rule-based)
|
| 283 |
+
# ------------------------------------------------------------------
|
| 284 |
+
|
| 285 |
+
# Copula avoidance -- "serves as X" -> "is X", "stands as X" -> "is X"
|
| 286 |
+
_COPULA_PATTERNS: list[tuple[re.Pattern, str]] = [
|
| 287 |
+
(re.compile(r'\bserves as a\b', re.IGNORECASE), "is a"),
|
| 288 |
+
(re.compile(r'\bserves as an\b', re.IGNORECASE), "is an"),
|
| 289 |
+
(re.compile(r'\bserves as the\b', re.IGNORECASE), "is the"),
|
| 290 |
+
(re.compile(r'\bstands as a\b', re.IGNORECASE), "is a"),
|
| 291 |
+
(re.compile(r'\bstands as an\b', re.IGNORECASE), "is an"),
|
| 292 |
+
(re.compile(r'\bstands as the\b', re.IGNORECASE), "is the"),
|
| 293 |
+
(re.compile(r'\bacts as a\b', re.IGNORECASE), "is a"),
|
| 294 |
+
(re.compile(r'\bacts as an\b', re.IGNORECASE), "is an"),
|
| 295 |
+
(re.compile(r'\bfunctions as a\b', re.IGNORECASE), "is a"),
|
| 296 |
+
(re.compile(r'\bfunctions as an\b', re.IGNORECASE), "is an"),
|
| 297 |
+
]
|
| 298 |
+
|
| 299 |
+
# Filler phrases -- replace with shorter equivalent
|
| 300 |
+
_FILLER_PATTERNS: list[tuple[re.Pattern, str]] = [
|
| 301 |
+
(re.compile(r'\bin order to\b', re.IGNORECASE), "to"),
|
| 302 |
+
(re.compile(r'\bdue to the fact that\b', re.IGNORECASE), "because"),
|
| 303 |
+
(re.compile(r'\bat this point in time\b', re.IGNORECASE), "now"),
|
| 304 |
+
(re.compile(r'\bin the event that\b', re.IGNORECASE), "if"),
|
| 305 |
+
(re.compile(r'\bhas the ability to\b', re.IGNORECASE), "can"),
|
| 306 |
+
(re.compile(r'\bhas the potential to\b', re.IGNORECASE), "can"),
|
| 307 |
+
(re.compile(r'\bit is important to note that\b', re.IGNORECASE), ""),
|
| 308 |
+
(re.compile(r'\bit is worth noting that\b', re.IGNORECASE), ""),
|
| 309 |
+
(re.compile(r'\bit goes without saying that\b', re.IGNORECASE), ""),
|
| 310 |
+
(re.compile(r'\bit should be noted that\b', re.IGNORECASE), ""),
|
| 311 |
+
(re.compile(r'\bthe fact that\b', re.IGNORECASE), "that"),
|
| 312 |
+
(re.compile(r'\bat its core,?\s*', re.IGNORECASE), ""),
|
| 313 |
+
(re.compile(r'\bfirst and foremost,?\s*', re.IGNORECASE), ""),
|
| 314 |
+
(re.compile(r'\bneedless to say,?\s*', re.IGNORECASE), ""),
|
| 315 |
+
]
|
| 316 |
+
|
| 317 |
+
# Negative parallelisms -- detect and flatten
|
| 318 |
+
# These are very hard to fix cleanly without an LLM, so we just
|
| 319 |
+
# strip the "not just X; it's" framing and keep the second half
|
| 320 |
+
_NEG_PARALLEL_PATTERNS: list[tuple[re.Pattern, str]] = [
|
| 321 |
+
# "It's not just about X; it's about Y" -> "Y"
|
| 322 |
+
(re.compile(
|
| 323 |
+
r"It'?s not just about [^;.!?]+[;,]\s*it'?s about\s*",
|
| 324 |
+
re.IGNORECASE
|
| 325 |
+
), ""),
|
| 326 |
+
# "Not merely X; it's Y" -> "Y"
|
| 327 |
+
(re.compile(
|
| 328 |
+
r"Not merely [^;.!?]+[;,]\s*it'?s\s*",
|
| 329 |
+
re.IGNORECASE
|
| 330 |
+
), ""),
|
| 331 |
+
# "Not just X, it's Y" -> "Y"
|
| 332 |
+
(re.compile(
|
| 333 |
+
r"not just [^,;.!?]+,\s*it'?s\s*",
|
| 334 |
+
re.IGNORECASE
|
| 335 |
+
), ""),
|
| 336 |
+
]
|
| 337 |
+
|
| 338 |
+
# Superficial -ing tails at end of sentences
|
| 339 |
+
# "...contributing to the growth of X." -> remove the tail
|
| 340 |
+
_ING_TAIL_PATTERNS: list[tuple[re.Pattern, str]] = [
|
| 341 |
+
(re.compile(
|
| 342 |
+
r',\s*(?:highlighting|underscoring|emphasizing|showcasing|reflecting'
|
| 343 |
+
r'|symbolizing|fostering|contributing to|demonstrating)[^.!?]*[.!?]',
|
| 344 |
+
re.IGNORECASE
|
| 345 |
+
), "."),
|
| 346 |
+
(re.compile(
|
| 347 |
+
r'\s+(?:highlighting|underscoring|emphasizing|showcasing|reflecting'
|
| 348 |
+
r'|symbolizing|fostering)[^.!?]*[.!?]$',
|
| 349 |
+
re.IGNORECASE | re.MULTILINE
|
| 350 |
+
), "."),
|
| 351 |
+
]
|
| 352 |
+
|
| 353 |
+
# Generic positive conclusions to replace with plain endings
|
| 354 |
+
_GENERIC_CONCLUSION_PATTERNS: list[tuple[re.Pattern, str]] = [
|
| 355 |
+
(re.compile(
|
| 356 |
+
r'(?:the future looks? bright|exciting times? (?:lie|await|ahead)|'
|
| 357 |
+
r'(?:get|start) (?:started|going) today[!.]?|'
|
| 358 |
+
r'(?:your|the) (?:users?|audience|readers?)[^.!?]*will appreciate[^.!?]*[.!?])',
|
| 359 |
+
re.IGNORECASE
|
| 360 |
+
), ""),
|
| 361 |
+
# "X is not optional; it is survival" / "X is not just nice; it's necessary"
|
| 362 |
+
(re.compile(
|
| 363 |
+
r'\w[\w\s]+ is (?:not just [\w\s]+;?\s*it(?:\'s| is)|no longer optional)',
|
| 364 |
+
re.IGNORECASE
|
| 365 |
+
), ""),
|
| 366 |
+
]
|
| 367 |
+
|
| 368 |
+
def _eliminate_ai_patterns(self, text: str) -> str:
|
| 369 |
+
"""Remove Wikipedia-documented AI writing patterns from text.
|
| 370 |
+
|
| 371 |
+
Applies rule-based fixes for:
|
| 372 |
+
- Copula avoidance ("serves as" -> "is")
|
| 373 |
+
- Filler phrases ("in order to" -> "to")
|
| 374 |
+
- Superficial -ing tails (sentences ending with "...highlighting X")
|
| 375 |
+
- Negative parallelisms ("It's not just X; it's Y")
|
| 376 |
+
"""
|
| 377 |
+
fixes = 0
|
| 378 |
+
|
| 379 |
+
# Copula avoidance
|
| 380 |
+
for pattern, replacement in self._COPULA_PATTERNS:
|
| 381 |
+
new_text = pattern.sub(replacement, text)
|
| 382 |
+
if new_text != text:
|
| 383 |
+
fixes += 1
|
| 384 |
+
text = new_text
|
| 385 |
+
|
| 386 |
+
# Filler phrases
|
| 387 |
+
for pattern, replacement in self._FILLER_PATTERNS:
|
| 388 |
+
new_text = pattern.sub(replacement, text)
|
| 389 |
+
if new_text != text:
|
| 390 |
+
fixes += 1
|
| 391 |
+
text = new_text
|
| 392 |
+
|
| 393 |
+
# -ing tails
|
| 394 |
+
for pattern, replacement in self._ING_TAIL_PATTERNS:
|
| 395 |
+
new_text = pattern.sub(replacement, text)
|
| 396 |
+
if new_text != text:
|
| 397 |
+
fixes += 1
|
| 398 |
+
text = new_text
|
| 399 |
+
|
| 400 |
+
# Negative parallelisms (careful -- only apply if the pattern is clear)
|
| 401 |
+
for pattern, replacement in self._NEG_PARALLEL_PATTERNS:
|
| 402 |
+
new_text = pattern.sub(replacement, text)
|
| 403 |
+
if new_text != text:
|
| 404 |
+
# Capitalize whatever follows
|
| 405 |
+
fixes += 1
|
| 406 |
+
text = new_text
|
| 407 |
+
|
| 408 |
+
# Generic positive conclusions -- just strip the offending sentence
|
| 409 |
+
for pattern, replacement in self._GENERIC_CONCLUSION_PATTERNS:
|
| 410 |
+
new_text = pattern.sub(replacement, text)
|
| 411 |
+
if new_text != text:
|
| 412 |
+
fixes += 1
|
| 413 |
+
text = new_text
|
| 414 |
+
|
| 415 |
+
# Clean up any double spaces or leading/trailing spaces on lines
|
| 416 |
+
text = re.sub(r' +', ' ', text)
|
| 417 |
+
text = re.sub(r'^ +', '', text, flags=re.MULTILINE)
|
| 418 |
+
text = re.sub(r'\n{3,}', '\n\n', text)
|
| 419 |
+
|
| 420 |
+
if fixes > 0:
|
| 421 |
+
logger.info("AI pattern elimination: fixed %d pattern(s)", fixes)
|
| 422 |
+
|
| 423 |
+
return text
|
| 424 |
+
|
| 425 |
+
# ------------------------------------------------------------------
|
| 426 |
+
# Step 1: Strip AI formatting
|
| 427 |
+
# ------------------------------------------------------------------
|
| 428 |
+
|
| 429 |
+
def _strip_ai_formatting(self, text: str) -> str:
|
| 430 |
+
"""Remove AI formatting artifacts."""
|
| 431 |
+
# Markdown
|
| 432 |
+
text = re.sub(r'\*\*\*(.+?)\*\*\*', r'\1', text)
|
| 433 |
+
text = re.sub(r'\*\*(.+?)\*\*', r'\1', text)
|
| 434 |
+
text = re.sub(r'\*(.+?)\*', r'\1', text)
|
| 435 |
+
text = re.sub(r'__(.+?)__', r'\1', text)
|
| 436 |
+
text = re.sub(r'_(.+?)_', r'\1', text)
|
| 437 |
+
text = re.sub(r'^#{1,6}\s+', '', text, flags=re.MULTILINE)
|
| 438 |
+
|
| 439 |
+
# Unicode formatting characters
|
| 440 |
+
for char, replacements in _FORMAT_REPLACEMENTS:
|
| 441 |
+
while char in text:
|
| 442 |
+
replacement = random.choice(replacements)
|
| 443 |
+
text = text.replace(char, replacement, 1)
|
| 444 |
+
|
| 445 |
+
# Clean up spacing
|
| 446 |
+
text = re.sub(r' +', ' ', text)
|
| 447 |
+
text = re.sub(r' ([,.])', r'\1', text)
|
| 448 |
+
|
| 449 |
+
return text
|
| 450 |
+
|
| 451 |
+
# ------------------------------------------------------------------
|
| 452 |
+
# Step 2: Remove AI-style paragraph openers
|
| 453 |
+
# ------------------------------------------------------------------
|
| 454 |
+
|
| 455 |
+
def _remove_ai_openers(self, text: str) -> str:
|
| 456 |
+
"""Strip conversational hooks that LLMs add to paragraph starts.
|
| 457 |
+
|
| 458 |
+
Patterns like "First off,", "Another trick is", "How about X?",
|
| 459 |
+
"Now let's talk about" are classic AI rewrite tells.
|
| 460 |
+
"""
|
| 461 |
+
paragraphs = text.split('\n')
|
| 462 |
+
result = []
|
| 463 |
+
removals = 0
|
| 464 |
+
|
| 465 |
+
for para in paragraphs:
|
| 466 |
+
stripped = para.strip()
|
| 467 |
+
if not stripped:
|
| 468 |
+
result.append(para)
|
| 469 |
+
continue
|
| 470 |
+
|
| 471 |
+
modified = stripped
|
| 472 |
+
for pattern, replacement in _AI_OPENERS:
|
| 473 |
+
new_text = pattern.sub(replacement, modified)
|
| 474 |
+
if new_text != modified:
|
| 475 |
+
# Capitalize the first letter after removal
|
| 476 |
+
new_text = new_text.lstrip()
|
| 477 |
+
if new_text and new_text[0].islower():
|
| 478 |
+
new_text = new_text[0].upper() + new_text[1:]
|
| 479 |
+
modified = new_text
|
| 480 |
+
removals += 1
|
| 481 |
+
break # Only remove one opener per paragraph
|
| 482 |
+
|
| 483 |
+
result.append(modified)
|
| 484 |
+
|
| 485 |
+
if removals > 0:
|
| 486 |
+
logger.info("Removed %d AI-style paragraph openers", removals)
|
| 487 |
+
|
| 488 |
+
return '\n'.join(result)
|
| 489 |
+
|
| 490 |
+
# ------------------------------------------------------------------
|
| 491 |
+
# Step 3: Global AI vocabulary replacement
|
| 492 |
+
# ------------------------------------------------------------------
|
| 493 |
+
|
| 494 |
+
def _replace_global_ai_words(self, text: str) -> str:
|
| 495 |
+
"""Replace ALL AI vocabulary the LLM generated."""
|
| 496 |
+
replacements_made = 0
|
| 497 |
+
text_lower = text.lower()
|
| 498 |
+
|
| 499 |
+
for pattern, replacements, original_word in self._ai_patterns:
|
| 500 |
+
matches = list(pattern.finditer(text))
|
| 501 |
+
if not matches:
|
| 502 |
+
continue
|
| 503 |
+
|
| 504 |
+
safe_replacements = [
|
| 505 |
+
r for r in replacements if r.lower() not in text_lower
|
| 506 |
+
]
|
| 507 |
+
if not safe_replacements:
|
| 508 |
+
safe_replacements = replacements
|
| 509 |
+
|
| 510 |
+
for match in reversed(matches):
|
| 511 |
+
# Skip if part of a proper name / tool name
|
| 512 |
+
if self._is_part_of_proper_name(text, match):
|
| 513 |
+
continue
|
| 514 |
+
|
| 515 |
+
original = match.group(0)
|
| 516 |
+
replacement = random.choice(safe_replacements)
|
| 517 |
+
if original[0].isupper():
|
| 518 |
+
replacement = replacement[0].upper() + replacement[1:]
|
| 519 |
+
if original.isupper() and len(original) > 1:
|
| 520 |
+
replacement = replacement.upper()
|
| 521 |
+
text = text[:match.start()] + replacement + text[match.end():]
|
| 522 |
+
replacements_made += 1
|
| 523 |
+
|
| 524 |
+
if replacements_made > 0:
|
| 525 |
+
logger.info("Replaced %d AI vocabulary words", replacements_made)
|
| 526 |
+
|
| 527 |
+
return text
|
| 528 |
+
|
| 529 |
+
# ------------------------------------------------------------------
|
| 530 |
+
# Step 4: Random word substitution
|
| 531 |
+
# ------------------------------------------------------------------
|
| 532 |
+
|
| 533 |
+
def _substitute_words(self, text: str) -> str:
|
| 534 |
+
"""Replace a fraction of common words with less predictable alternatives."""
|
| 535 |
+
replacements_made = 0
|
| 536 |
+
max_replacements = max(2, int(len(text.split()) * self.intensity))
|
| 537 |
+
|
| 538 |
+
shuffled = list(self._sub_patterns)
|
| 539 |
+
random.shuffle(shuffled)
|
| 540 |
+
|
| 541 |
+
for pattern, replacements in shuffled:
|
| 542 |
+
if replacements_made >= max_replacements:
|
| 543 |
+
break
|
| 544 |
+
|
| 545 |
+
matches = list(pattern.finditer(text))
|
| 546 |
+
if not matches:
|
| 547 |
+
continue
|
| 548 |
+
|
| 549 |
+
match = random.choice(matches)
|
| 550 |
+
original = match.group(0)
|
| 551 |
+
|
| 552 |
+
# Skip if inside a heading/numbered line
|
| 553 |
+
line_start = text.rfind('\n', 0, match.start()) + 1
|
| 554 |
+
line_prefix = text[line_start:match.start()].strip()
|
| 555 |
+
if re.match(r'^\d+\.?\s*$', line_prefix):
|
| 556 |
+
continue
|
| 557 |
+
|
| 558 |
+
# Skip if part of a proper name / tool name
|
| 559 |
+
if self._is_part_of_proper_name(text, match):
|
| 560 |
+
continue
|
| 561 |
+
|
| 562 |
+
replacement = random.choice(replacements)
|
| 563 |
+
if original[0].isupper():
|
| 564 |
+
replacement = replacement[0].upper() + replacement[1:]
|
| 565 |
+
|
| 566 |
+
text = text[:match.start()] + replacement + text[match.end():]
|
| 567 |
+
replacements_made += 1
|
| 568 |
+
|
| 569 |
+
if replacements_made > 0:
|
| 570 |
+
logger.debug("Random word substitutions: %d", replacements_made)
|
| 571 |
+
|
| 572 |
+
return text
|
| 573 |
+
|
| 574 |
+
# ------------------------------------------------------------------
|
| 575 |
+
# Helper: Proper name detection
|
| 576 |
+
# ------------------------------------------------------------------
|
| 577 |
+
|
| 578 |
+
@staticmethod
|
| 579 |
+
def _is_part_of_proper_name(text: str, match: re.Match) -> bool:
|
| 580 |
+
"""Check if a match is part of a proper name or tool name.
|
| 581 |
+
|
| 582 |
+
Skips replacement if:
|
| 583 |
+
- Preceded by a hyphen (e.g. WP-Optimize)
|
| 584 |
+
- Followed by a hyphen (e.g. Advanced-something)
|
| 585 |
+
- Adjacent word is capitalized (e.g. "Advanced Database Cleaner")
|
| 586 |
+
- Inside a quoted string
|
| 587 |
+
"""
|
| 588 |
+
start = match.start()
|
| 589 |
+
end = match.end()
|
| 590 |
+
|
| 591 |
+
# Check for hyphen before or after
|
| 592 |
+
if start > 0 and text[start - 1] == '-':
|
| 593 |
+
return True
|
| 594 |
+
if end < len(text) and text[end] == '-':
|
| 595 |
+
return True
|
| 596 |
+
|
| 597 |
+
# Check if the next word is capitalized (proper compound name)
|
| 598 |
+
after = text[end:end + 20].lstrip()
|
| 599 |
+
if after and after[0].isupper():
|
| 600 |
+
# Next word starts with uppercase => likely a proper name
|
| 601 |
+
return True
|
| 602 |
+
|
| 603 |
+
# Check if previous word is capitalized and not start of sentence
|
| 604 |
+
before_text = text[max(0, start - 30):start].rstrip()
|
| 605 |
+
if before_text:
|
| 606 |
+
prev_words = before_text.split()
|
| 607 |
+
if prev_words:
|
| 608 |
+
prev_word = prev_words[-1]
|
| 609 |
+
# If prev word is capitalized and not after sentence-ending punct
|
| 610 |
+
if (
|
| 611 |
+
prev_word[0].isupper()
|
| 612 |
+
and not prev_word[-1] in '.!?'
|
| 613 |
+
and not prev_word.endswith(',')
|
| 614 |
+
):
|
| 615 |
+
return True
|
| 616 |
+
|
| 617 |
+
return False
|
| 618 |
+
|
| 619 |
+
# ------------------------------------------------------------------
|
| 620 |
+
# Step 5: Contraction variation
|
| 621 |
+
# ------------------------------------------------------------------
|
| 622 |
+
|
| 623 |
+
_EXPANSION_MAP: dict[str, str] = {
|
| 624 |
+
"it's": "it is",
|
| 625 |
+
"that's": "that is",
|
| 626 |
+
"there's": "there is",
|
| 627 |
+
"here's": "here is",
|
| 628 |
+
"what's": "what is",
|
| 629 |
+
"who's": "who is",
|
| 630 |
+
"he's": "he is",
|
| 631 |
+
"she's": "she is",
|
| 632 |
+
"don't": "do not",
|
| 633 |
+
"doesn't": "does not",
|
| 634 |
+
"didn't": "did not",
|
| 635 |
+
"won't": "will not",
|
| 636 |
+
"can't": "cannot",
|
| 637 |
+
"shouldn't": "should not",
|
| 638 |
+
"wouldn't": "would not",
|
| 639 |
+
"isn't": "is not",
|
| 640 |
+
"aren't": "are not",
|
| 641 |
+
"wasn't": "was not",
|
| 642 |
+
"weren't": "were not",
|
| 643 |
+
"hasn't": "has not",
|
| 644 |
+
"haven't": "have not",
|
| 645 |
+
}
|
| 646 |
+
|
| 647 |
+
def _vary_contractions(self, text: str) -> str:
|
| 648 |
+
"""Randomly expand some contractions for natural inconsistency.
|
| 649 |
+
|
| 650 |
+
Real humans are inconsistent: "don't" in one sentence,
|
| 651 |
+
"do not" in the next. This mimics that pattern.
|
| 652 |
+
"""
|
| 653 |
+
expansions_done = 0
|
| 654 |
+
max_expansions = random.randint(2, 4)
|
| 655 |
+
|
| 656 |
+
items = list(self._EXPANSION_MAP.items())
|
| 657 |
+
random.shuffle(items)
|
| 658 |
+
|
| 659 |
+
for contraction, expansion in items:
|
| 660 |
+
if expansions_done >= max_expansions:
|
| 661 |
+
break
|
| 662 |
+
|
| 663 |
+
pattern = re.compile(re.escape(contraction), re.IGNORECASE)
|
| 664 |
+
matches = list(pattern.finditer(text))
|
| 665 |
+
if not matches:
|
| 666 |
+
continue
|
| 667 |
+
|
| 668 |
+
if random.random() < 0.35:
|
| 669 |
+
match = random.choice(matches)
|
| 670 |
+
original = match.group(0)
|
| 671 |
+
replacement = expansion
|
| 672 |
+
if original[0].isupper():
|
| 673 |
+
replacement = replacement[0].upper() + replacement[1:]
|
| 674 |
+
text = text[:match.start()] + replacement + text[match.end():]
|
| 675 |
+
expansions_done += 1
|
| 676 |
+
|
| 677 |
+
return text
|
app/core/pipeline.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
HumanizationPipeline -- wires Stage 1, 2, and 3 together.
|
| 3 |
+
|
| 4 |
+
Provides a single ``process()`` entry point that:
|
| 5 |
+
1. Runs Stage 1 (TextAnalyzer) -- local analysis, produces instructions.
|
| 6 |
+
2. Runs Stage 2 (LLMRewriter) -- single async LLM call with instructions.
|
| 7 |
+
3. Runs Stage 3 (PostValidator) -- local validation and micro-corrections.
|
| 8 |
+
|
| 9 |
+
Includes per-stage timing and comprehensive error handling with fallbacks.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import logging
|
| 15 |
+
import time
|
| 16 |
+
from typing import Any
|
| 17 |
+
|
| 18 |
+
from app.core.analyzer import TextAnalyzer
|
| 19 |
+
from app.core.llm_rewriter import LLMRewriter, RewriteResult
|
| 20 |
+
from app.core.post_validator import PostValidator
|
| 21 |
+
from app.core.prompt_manager import PromptManager
|
| 22 |
+
|
| 23 |
+
logger = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class HumanizationPipeline:
|
| 27 |
+
"""Main pipeline orchestrator.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
analyzer: Stage 1 TextAnalyzer.
|
| 31 |
+
rewriter: Stage 2 LLMRewriter.
|
| 32 |
+
post_validator: Stage 3 PostValidator.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
def __init__(
|
| 36 |
+
self,
|
| 37 |
+
analyzer: TextAnalyzer,
|
| 38 |
+
rewriter: LLMRewriter,
|
| 39 |
+
post_validator: PostValidator,
|
| 40 |
+
) -> None:
|
| 41 |
+
self.analyzer = analyzer
|
| 42 |
+
self.rewriter = rewriter
|
| 43 |
+
self.post_validator = post_validator
|
| 44 |
+
|
| 45 |
+
# ------------------------------------------------------------------
|
| 46 |
+
# Public API
|
| 47 |
+
# ------------------------------------------------------------------
|
| 48 |
+
|
| 49 |
+
async def process(
|
| 50 |
+
self,
|
| 51 |
+
text: str,
|
| 52 |
+
mode: str = "standard",
|
| 53 |
+
) -> dict[str, Any]:
|
| 54 |
+
"""Run the full 3-stage humanization pipeline.
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
text: The AI-generated input text.
|
| 58 |
+
mode: 'standard' or 'thorough'.
|
| 59 |
+
|
| 60 |
+
Returns:
|
| 61 |
+
Dict with:
|
| 62 |
+
- success: bool
|
| 63 |
+
- output_text: str (rewritten text, or original on failure)
|
| 64 |
+
- analysis: dict (Stage 1 result)
|
| 65 |
+
- stats: dict (processing statistics)
|
| 66 |
+
- error: str (empty on success)
|
| 67 |
+
"""
|
| 68 |
+
t_total = time.perf_counter()
|
| 69 |
+
|
| 70 |
+
# ---- Stage 1: Analysis (local, no API) ----
|
| 71 |
+
analysis_result, stage1_ms = self._run_stage1(text)
|
| 72 |
+
|
| 73 |
+
# ---- Stage 2: LLM Rewrite (single API call) ----
|
| 74 |
+
rewrite_result = await self._run_stage2(text, analysis_result)
|
| 75 |
+
|
| 76 |
+
# ---- Stage 3: Post-validation (local) ----
|
| 77 |
+
output_text = rewrite_result.output_text
|
| 78 |
+
validation, stage3_ms = self._run_stage3(
|
| 79 |
+
text, output_text, analysis_result, mode
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
# ---- Assemble final response ----
|
| 83 |
+
total_ms = round((time.perf_counter() - t_total) * 1000, 1)
|
| 84 |
+
|
| 85 |
+
stats = validation.get("stats", {})
|
| 86 |
+
stats["processing_time_ms"] = total_ms
|
| 87 |
+
stats["stage1_time_ms"] = stage1_ms
|
| 88 |
+
stats["stage2_time_ms"] = rewrite_result.stage2_time_ms
|
| 89 |
+
stats["prompt_variant_used"] = rewrite_result.variant_used
|
| 90 |
+
stats["llm_used"] = rewrite_result.llm_used
|
| 91 |
+
|
| 92 |
+
return {
|
| 93 |
+
"success": rewrite_result.success,
|
| 94 |
+
"output_text": validation.get("output_text", output_text),
|
| 95 |
+
"analysis": analysis_result,
|
| 96 |
+
"stats": stats,
|
| 97 |
+
"error": rewrite_result.error,
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
# ------------------------------------------------------------------
|
| 101 |
+
# Stage runners with error isolation
|
| 102 |
+
# ------------------------------------------------------------------
|
| 103 |
+
|
| 104 |
+
def _run_stage1(self, text: str) -> tuple[dict[str, Any], float]:
|
| 105 |
+
"""Run Stage 1 analysis. Returns (analysis_result, elapsed_ms)."""
|
| 106 |
+
t0 = time.perf_counter()
|
| 107 |
+
try:
|
| 108 |
+
result = self.analyzer.analyze(text)
|
| 109 |
+
elapsed = round((time.perf_counter() - t0) * 1000, 1)
|
| 110 |
+
logger.info("Stage 1 complete in %.1f ms", elapsed)
|
| 111 |
+
return result, elapsed
|
| 112 |
+
except Exception as exc:
|
| 113 |
+
elapsed = round((time.perf_counter() - t0) * 1000, 1)
|
| 114 |
+
logger.error("Stage 1 failed: %s. Using fallback generic analysis.", exc)
|
| 115 |
+
return self._fallback_analysis(), elapsed
|
| 116 |
+
|
| 117 |
+
async def _run_stage2(
|
| 118 |
+
self, text: str, analysis_result: dict[str, Any]
|
| 119 |
+
) -> RewriteResult:
|
| 120 |
+
"""Run Stage 2 LLM rewrite. Returns RewriteResult."""
|
| 121 |
+
try:
|
| 122 |
+
return await self.rewriter.rewrite(text, analysis_result)
|
| 123 |
+
except Exception as exc:
|
| 124 |
+
logger.error("Stage 2 unexpected error: %s. Returning original.", exc)
|
| 125 |
+
return RewriteResult(
|
| 126 |
+
output_text=text,
|
| 127 |
+
success=False,
|
| 128 |
+
error=str(exc),
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
def _run_stage3(
|
| 132 |
+
self,
|
| 133 |
+
original_text: str,
|
| 134 |
+
rewritten_text: str,
|
| 135 |
+
analysis_result: dict[str, Any],
|
| 136 |
+
mode: str,
|
| 137 |
+
) -> tuple[dict[str, Any], float]:
|
| 138 |
+
"""Run Stage 3 post-validation. Returns (result, elapsed_ms)."""
|
| 139 |
+
t0 = time.perf_counter()
|
| 140 |
+
try:
|
| 141 |
+
result = self.post_validator.validate(
|
| 142 |
+
original_text, rewritten_text, analysis_result, mode
|
| 143 |
+
)
|
| 144 |
+
elapsed = round((time.perf_counter() - t0) * 1000, 1)
|
| 145 |
+
logger.info("Stage 3 complete in %.1f ms", elapsed)
|
| 146 |
+
return result, elapsed
|
| 147 |
+
except Exception as exc:
|
| 148 |
+
elapsed = round((time.perf_counter() - t0) * 1000, 1)
|
| 149 |
+
logger.error("Stage 3 failed: %s. Returning Stage 2 output as-is.", exc)
|
| 150 |
+
return {"output_text": rewritten_text, "stats": {}}, elapsed
|
| 151 |
+
|
| 152 |
+
# ------------------------------------------------------------------
|
| 153 |
+
# Fallback analysis (when Stage 1 crashes)
|
| 154 |
+
# ------------------------------------------------------------------
|
| 155 |
+
|
| 156 |
+
@staticmethod
|
| 157 |
+
def _fallback_analysis() -> dict[str, Any]:
|
| 158 |
+
"""Return a minimal analysis that tells the LLM to do a basic rewrite."""
|
| 159 |
+
return {
|
| 160 |
+
"summary": {
|
| 161 |
+
"total_sentences": 0,
|
| 162 |
+
"high_risk_sentences": 0,
|
| 163 |
+
"medium_risk_sentences": 0,
|
| 164 |
+
"low_risk_sentences": 0,
|
| 165 |
+
"burstiness_cv": 0.0,
|
| 166 |
+
"burstiness_rating": "unknown",
|
| 167 |
+
"ai_vocabulary_count": 0,
|
| 168 |
+
"transition_flags": 0,
|
| 169 |
+
"opening_pattern_flags": 0,
|
| 170 |
+
"overall_risk": "unknown",
|
| 171 |
+
"analysis_time_ms": 0.0,
|
| 172 |
+
},
|
| 173 |
+
"instructions": [
|
| 174 |
+
{
|
| 175 |
+
"type": "general",
|
| 176 |
+
"sentence_index": None,
|
| 177 |
+
"severity": "medium",
|
| 178 |
+
"instruction": (
|
| 179 |
+
"Rewrite this text as a university student polishing their "
|
| 180 |
+
"essay. Make it sound natural and human. Vary sentence length, "
|
| 181 |
+
"use occasional contractions, and avoid overly formal language."
|
| 182 |
+
),
|
| 183 |
+
}
|
| 184 |
+
],
|
| 185 |
+
"banned_words": [],
|
| 186 |
+
"sentence_perplexities": [],
|
| 187 |
+
}
|
app/core/post_validator.py
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Post Validator -- Stage 3 of the humanization pipeline.
|
| 3 |
+
|
| 4 |
+
All checks run locally (no API calls):
|
| 5 |
+
3a. Length validation & smart trimming
|
| 6 |
+
3b. Banned word auto-replacement
|
| 7 |
+
3c. Optional perplexity re-scoring (thorough mode)
|
| 8 |
+
3d. Grammar checking (language_tool_python) + NER preservation
|
| 9 |
+
3e. Stats aggregation
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import json
|
| 15 |
+
import logging
|
| 16 |
+
import random
|
| 17 |
+
import re
|
| 18 |
+
import statistics
|
| 19 |
+
import time
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
from typing import Any, TYPE_CHECKING
|
| 22 |
+
|
| 23 |
+
from app.core.perturbation import TextPerturber
|
| 24 |
+
from app.utils.text_utils import (
|
| 25 |
+
count_words,
|
| 26 |
+
split_sentences,
|
| 27 |
+
calculate_burstiness,
|
| 28 |
+
calculate_expansion_percentage,
|
| 29 |
+
sentence_word_counts,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
if TYPE_CHECKING:
|
| 33 |
+
from app.core.perplexity_scorer import PerplexityScorer
|
| 34 |
+
|
| 35 |
+
logger = logging.getLogger(__name__)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class PostValidator:
|
| 39 |
+
"""Stage 3 post-validation and micro-corrections.
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
nlp: Loaded spaCy model (for NER, sentence splitting).
|
| 43 |
+
perplexity_scorer: Loaded PerplexityScorer (for thorough mode re-scoring).
|
| 44 |
+
language_tool: Loaded language_tool_python.LanguageTool instance.
|
| 45 |
+
vocab_path: Path to ai_vocabulary.json (for auto-replacement suggestions).
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
def __init__(
|
| 49 |
+
self,
|
| 50 |
+
nlp: Any = None,
|
| 51 |
+
perplexity_scorer: "PerplexityScorer | None" = None,
|
| 52 |
+
language_tool: Any = None,
|
| 53 |
+
vocab_path: str = "app/data/ai_vocabulary.json",
|
| 54 |
+
) -> None:
|
| 55 |
+
self.nlp = nlp
|
| 56 |
+
self.perplexity_scorer = perplexity_scorer
|
| 57 |
+
self.language_tool = language_tool
|
| 58 |
+
self._perturber = TextPerturber(intensity=0.12, filler_rate=0.05)
|
| 59 |
+
self._vocab: dict[str, Any] = {}
|
| 60 |
+
self._load_vocab(vocab_path)
|
| 61 |
+
|
| 62 |
+
def _load_vocab(self, vocab_path: str) -> None:
|
| 63 |
+
"""Load AI vocabulary with suggestions for auto-replacement."""
|
| 64 |
+
path = Path(vocab_path)
|
| 65 |
+
if not path.exists():
|
| 66 |
+
alt = Path(__file__).parent.parent / "data" / "ai_vocabulary.json"
|
| 67 |
+
path = alt if alt.exists() else path
|
| 68 |
+
if path.exists():
|
| 69 |
+
try:
|
| 70 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 71 |
+
self._vocab = json.load(f)
|
| 72 |
+
except Exception as exc:
|
| 73 |
+
logger.warning("Failed to load vocabulary for post-validation: %s", exc)
|
| 74 |
+
|
| 75 |
+
# ------------------------------------------------------------------
|
| 76 |
+
# Public API
|
| 77 |
+
# ------------------------------------------------------------------
|
| 78 |
+
|
| 79 |
+
def validate(
|
| 80 |
+
self,
|
| 81 |
+
original_text: str,
|
| 82 |
+
rewritten_text: str,
|
| 83 |
+
analysis_result: dict[str, Any],
|
| 84 |
+
mode: str = "standard",
|
| 85 |
+
) -> dict[str, Any]:
|
| 86 |
+
"""Run all post-validation checks and return corrected text + stats.
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
original_text: The original input text.
|
| 90 |
+
rewritten_text: Stage 2 LLM output.
|
| 91 |
+
analysis_result: Stage 1 AnalysisResult dict.
|
| 92 |
+
mode: 'standard' or 'thorough'.
|
| 93 |
+
|
| 94 |
+
Returns:
|
| 95 |
+
Dict with 'output_text' and 'stats'.
|
| 96 |
+
"""
|
| 97 |
+
t0 = time.perf_counter()
|
| 98 |
+
|
| 99 |
+
text = rewritten_text
|
| 100 |
+
banned_words = analysis_result.get("banned_words", [])
|
| 101 |
+
|
| 102 |
+
# 3a. Length validation
|
| 103 |
+
text = self._validate_length(text, original_text)
|
| 104 |
+
|
| 105 |
+
# 3b. Banned word auto-replacement
|
| 106 |
+
text, words_found, words_fixed = self._fix_banned_words(text, banned_words)
|
| 107 |
+
|
| 108 |
+
# 3b2. Perturbation -- break AI statistical fingerprint
|
| 109 |
+
text = self._perturber.perturb(text)
|
| 110 |
+
|
| 111 |
+
# 3d. Grammar check
|
| 112 |
+
grammar_fixes = 0
|
| 113 |
+
if self.language_tool:
|
| 114 |
+
text, grammar_fixes = self._check_grammar(text)
|
| 115 |
+
|
| 116 |
+
# 3d. NER preservation check
|
| 117 |
+
ner_warnings = self._check_ner_preservation(original_text, text)
|
| 118 |
+
|
| 119 |
+
# 3c. Perplexity re-scoring (thorough mode only)
|
| 120 |
+
output_avg_ppl = None
|
| 121 |
+
if mode == "thorough" and self.perplexity_scorer:
|
| 122 |
+
output_avg_ppl = self._rescore_perplexity(text)
|
| 123 |
+
|
| 124 |
+
# 3e. Stats
|
| 125 |
+
input_wc = count_words(original_text)
|
| 126 |
+
output_wc = count_words(text)
|
| 127 |
+
expansion = calculate_expansion_percentage(input_wc, output_wc)
|
| 128 |
+
|
| 129 |
+
# Input perplexity stats from analysis
|
| 130 |
+
ppl_data = analysis_result.get("sentence_perplexities", [])
|
| 131 |
+
input_ppls = [s["mean_ppl"] for s in ppl_data if "mean_ppl" in s]
|
| 132 |
+
input_avg_ppl = round(statistics.mean(input_ppls), 1) if input_ppls else None
|
| 133 |
+
|
| 134 |
+
# Output burstiness
|
| 135 |
+
out_sentences = split_sentences(text, nlp=self.nlp)
|
| 136 |
+
out_wcs = sentence_word_counts(out_sentences)
|
| 137 |
+
out_burst = calculate_burstiness(out_wcs)
|
| 138 |
+
|
| 139 |
+
# Input burstiness from analysis
|
| 140 |
+
input_cv = analysis_result.get("summary", {}).get("burstiness_cv", None)
|
| 141 |
+
|
| 142 |
+
elapsed = round((time.perf_counter() - t0) * 1000, 1)
|
| 143 |
+
|
| 144 |
+
stats = {
|
| 145 |
+
"input_word_count": input_wc,
|
| 146 |
+
"output_word_count": output_wc,
|
| 147 |
+
"expansion_percentage": expansion,
|
| 148 |
+
"input_avg_perplexity": input_avg_ppl,
|
| 149 |
+
"output_avg_perplexity": output_avg_ppl,
|
| 150 |
+
"input_burstiness_cv": input_cv,
|
| 151 |
+
"output_burstiness_cv": round(out_burst["cv"], 4) if out_burst else None,
|
| 152 |
+
"banned_words_found_in_output": words_found,
|
| 153 |
+
"banned_words_auto_fixed": words_fixed,
|
| 154 |
+
"instructions_generated": len(analysis_result.get("instructions", [])),
|
| 155 |
+
"high_risk_sentences": analysis_result.get("summary", {}).get("high_risk_sentences", 0),
|
| 156 |
+
"grammar_fixes": grammar_fixes,
|
| 157 |
+
"ner_warnings": ner_warnings,
|
| 158 |
+
"stage3_time_ms": elapsed,
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
return {"output_text": text, "stats": stats}
|
| 162 |
+
|
| 163 |
+
# ------------------------------------------------------------------
|
| 164 |
+
# 3a. Length validation
|
| 165 |
+
# ------------------------------------------------------------------
|
| 166 |
+
|
| 167 |
+
def _validate_length(self, text: str, original_text: str) -> str:
|
| 168 |
+
"""Trim output if expansion exceeds 40%."""
|
| 169 |
+
input_wc = count_words(original_text)
|
| 170 |
+
output_wc = count_words(text)
|
| 171 |
+
|
| 172 |
+
if input_wc == 0:
|
| 173 |
+
return text
|
| 174 |
+
|
| 175 |
+
expansion = (output_wc - input_wc) / input_wc * 100
|
| 176 |
+
if expansion <= 40.0:
|
| 177 |
+
return text
|
| 178 |
+
|
| 179 |
+
# Over 40%: trim sentences from the end until within budget.
|
| 180 |
+
target_wc = int(input_wc * 1.35)
|
| 181 |
+
sentences = split_sentences(text, nlp=self.nlp)
|
| 182 |
+
trimmed = []
|
| 183 |
+
wc_so_far = 0
|
| 184 |
+
for sent in sentences:
|
| 185 |
+
sent_wc = count_words(sent)
|
| 186 |
+
if wc_so_far + sent_wc > target_wc and trimmed:
|
| 187 |
+
break
|
| 188 |
+
trimmed.append(sent)
|
| 189 |
+
wc_so_far += sent_wc
|
| 190 |
+
|
| 191 |
+
result = " ".join(trimmed)
|
| 192 |
+
logger.info(
|
| 193 |
+
"Length trimmed: %d -> %d words (target %d)",
|
| 194 |
+
output_wc, count_words(result), target_wc,
|
| 195 |
+
)
|
| 196 |
+
return result
|
| 197 |
+
|
| 198 |
+
# ------------------------------------------------------------------
|
| 199 |
+
# 3b. Banned word auto-replacement
|
| 200 |
+
# ------------------------------------------------------------------
|
| 201 |
+
|
| 202 |
+
def _fix_banned_words(
|
| 203 |
+
self, text: str, banned_words: list[str]
|
| 204 |
+
) -> tuple[str, list[str], int]:
|
| 205 |
+
"""Find and replace banned words using vocabulary suggestions.
|
| 206 |
+
|
| 207 |
+
Skips words that are part of proper names or tool names.
|
| 208 |
+
|
| 209 |
+
Returns:
|
| 210 |
+
(fixed_text, list_of_found_words, count_of_fixes).
|
| 211 |
+
"""
|
| 212 |
+
found: list[str] = []
|
| 213 |
+
fix_count = 0
|
| 214 |
+
|
| 215 |
+
# Sort banned words longest-first to handle phrases before single words.
|
| 216 |
+
for word in sorted(banned_words, key=len, reverse=True):
|
| 217 |
+
pattern = re.compile(r'\b' + re.escape(word) + r'\b', re.IGNORECASE)
|
| 218 |
+
matches = list(pattern.finditer(text))
|
| 219 |
+
if not matches:
|
| 220 |
+
continue
|
| 221 |
+
|
| 222 |
+
found.append(word)
|
| 223 |
+
replacement = self._get_replacement(word)
|
| 224 |
+
if not replacement:
|
| 225 |
+
continue
|
| 226 |
+
|
| 227 |
+
# Replace matches that are NOT part of proper names (go backwards)
|
| 228 |
+
for match in reversed(matches):
|
| 229 |
+
if self._is_part_of_proper_name(text, match):
|
| 230 |
+
continue
|
| 231 |
+
original = match.group(0)
|
| 232 |
+
rep = replacement
|
| 233 |
+
if original[0].isupper():
|
| 234 |
+
rep = rep[0].upper() + rep[1:]
|
| 235 |
+
text = text[:match.start()] + rep + text[match.end():]
|
| 236 |
+
fix_count += 1
|
| 237 |
+
|
| 238 |
+
if fix_count > 0:
|
| 239 |
+
logger.debug("Auto-replaced banned word '%s' -> '%s'", word, replacement)
|
| 240 |
+
|
| 241 |
+
return text, found, fix_count
|
| 242 |
+
|
| 243 |
+
@staticmethod
|
| 244 |
+
def _is_part_of_proper_name(text: str, match: re.Match) -> bool:
|
| 245 |
+
"""Check if a match is part of a proper name / tool name."""
|
| 246 |
+
start = match.start()
|
| 247 |
+
end = match.end()
|
| 248 |
+
|
| 249 |
+
# Hyphen before or after
|
| 250 |
+
if start > 0 and text[start - 1] == '-':
|
| 251 |
+
return True
|
| 252 |
+
if end < len(text) and text[end] == '-':
|
| 253 |
+
return True
|
| 254 |
+
|
| 255 |
+
# Next word is capitalized => likely a proper compound name
|
| 256 |
+
after = text[end:end + 20].lstrip()
|
| 257 |
+
if after and after[0].isupper():
|
| 258 |
+
return True
|
| 259 |
+
|
| 260 |
+
# Previous word is capitalized (and not after punctuation)
|
| 261 |
+
before_text = text[max(0, start - 30):start].rstrip()
|
| 262 |
+
if before_text:
|
| 263 |
+
prev_words = before_text.split()
|
| 264 |
+
if prev_words:
|
| 265 |
+
prev_word = prev_words[-1]
|
| 266 |
+
if (
|
| 267 |
+
prev_word[0].isupper()
|
| 268 |
+
and prev_word[-1] not in '.!?'
|
| 269 |
+
and not prev_word.endswith(',')
|
| 270 |
+
):
|
| 271 |
+
return True
|
| 272 |
+
|
| 273 |
+
return False
|
| 274 |
+
|
| 275 |
+
def _get_replacement(self, word: str) -> str | None:
|
| 276 |
+
"""Look up a replacement for a banned word from the vocabulary DB."""
|
| 277 |
+
word_lower = word.lower()
|
| 278 |
+
|
| 279 |
+
# Check single_words
|
| 280 |
+
single = self._vocab.get("single_words", {})
|
| 281 |
+
entry = single.get(word_lower)
|
| 282 |
+
if entry:
|
| 283 |
+
suggestions = entry.get("suggestions", [])
|
| 284 |
+
if suggestions:
|
| 285 |
+
return random.choice(suggestions)
|
| 286 |
+
|
| 287 |
+
# Check phrases
|
| 288 |
+
phrases = self._vocab.get("phrases", {})
|
| 289 |
+
entry = phrases.get(word_lower)
|
| 290 |
+
if entry:
|
| 291 |
+
suggestions = entry.get("suggestions", [])
|
| 292 |
+
if suggestions:
|
| 293 |
+
return random.choice(suggestions)
|
| 294 |
+
|
| 295 |
+
return None
|
| 296 |
+
|
| 297 |
+
# ------------------------------------------------------------------
|
| 298 |
+
# 3c. Perplexity re-scoring (thorough mode)
|
| 299 |
+
# ------------------------------------------------------------------
|
| 300 |
+
|
| 301 |
+
def _rescore_perplexity(self, text: str) -> float | None:
|
| 302 |
+
"""Re-score the output text's perplexity. Returns average or None."""
|
| 303 |
+
if not self.perplexity_scorer:
|
| 304 |
+
return None
|
| 305 |
+
try:
|
| 306 |
+
sentences = split_sentences(text, nlp=self.nlp)
|
| 307 |
+
results = self.perplexity_scorer.score_sentences(sentences)
|
| 308 |
+
ppls = [r.mean_perplexity for r in results]
|
| 309 |
+
return round(statistics.mean(ppls), 1) if ppls else None
|
| 310 |
+
except Exception as exc:
|
| 311 |
+
logger.warning("Perplexity re-scoring failed: %s", exc)
|
| 312 |
+
return None
|
| 313 |
+
|
| 314 |
+
# ------------------------------------------------------------------
|
| 315 |
+
# 3d. Grammar check + NER preservation
|
| 316 |
+
# ------------------------------------------------------------------
|
| 317 |
+
|
| 318 |
+
def _check_grammar(self, text: str) -> tuple[str, int]:
|
| 319 |
+
"""Run language_tool_python grammar check and apply fixes.
|
| 320 |
+
|
| 321 |
+
Returns:
|
| 322 |
+
(corrected_text, number_of_fixes).
|
| 323 |
+
"""
|
| 324 |
+
try:
|
| 325 |
+
matches = self.language_tool.check(text)
|
| 326 |
+
if not matches:
|
| 327 |
+
return text, 0
|
| 328 |
+
# Apply corrections (language_tool_python utility).
|
| 329 |
+
import language_tool_python
|
| 330 |
+
corrected = language_tool_python.utils.correct(text, matches)
|
| 331 |
+
return corrected, len(matches)
|
| 332 |
+
except Exception as exc:
|
| 333 |
+
logger.warning("Grammar check failed: %s", exc)
|
| 334 |
+
return text, 0
|
| 335 |
+
|
| 336 |
+
def _check_ner_preservation(self, original: str, rewritten: str) -> list[str]:
|
| 337 |
+
"""Check that named entities from the original are preserved.
|
| 338 |
+
|
| 339 |
+
Returns list of warning strings for any missing entities.
|
| 340 |
+
"""
|
| 341 |
+
if not self.nlp:
|
| 342 |
+
return []
|
| 343 |
+
|
| 344 |
+
try:
|
| 345 |
+
orig_doc = self.nlp(original)
|
| 346 |
+
new_doc = self.nlp(rewritten)
|
| 347 |
+
|
| 348 |
+
orig_ents = {ent.text.lower() for ent in orig_doc.ents}
|
| 349 |
+
new_ents = {ent.text.lower() for ent in new_doc.ents}
|
| 350 |
+
|
| 351 |
+
missing = orig_ents - new_ents
|
| 352 |
+
warnings = []
|
| 353 |
+
for ent in missing:
|
| 354 |
+
# Only warn about significant entities (skip single-letter matches).
|
| 355 |
+
if len(ent) > 2:
|
| 356 |
+
warnings.append(f"Named entity '{ent}' from original not found in output")
|
| 357 |
+
|
| 358 |
+
if warnings:
|
| 359 |
+
logger.warning("NER preservation issues: %s", warnings)
|
| 360 |
+
return warnings
|
| 361 |
+
except Exception as exc:
|
| 362 |
+
logger.warning("NER check failed: %s", exc)
|
| 363 |
+
return []
|
app/core/prompt_manager.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Prompt Manager -- builds the full LLM prompt from a variant + Stage 1 analysis.
|
| 3 |
+
|
| 4 |
+
KEY STRATEGY: "Write from notes" instead of "rewrite this text".
|
| 5 |
+
|
| 6 |
+
Presenting key points as notes and asking the model to write fresh changes
|
| 7 |
+
the generation task type. This produces a different statistical distribution
|
| 8 |
+
than asking the same model to paraphrase — which Originality.ai v3.0 is
|
| 9 |
+
specifically trained to detect.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import logging
|
| 15 |
+
import random
|
| 16 |
+
import re
|
| 17 |
+
from typing import Any
|
| 18 |
+
|
| 19 |
+
from app.prompts.variants import CORE_RULES, VARIANTS
|
| 20 |
+
from app.utils.text_utils import count_words
|
| 21 |
+
|
| 22 |
+
logger = logging.getLogger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class PromptManager:
|
| 26 |
+
"""Manages prompt variant rotation and prompt construction."""
|
| 27 |
+
|
| 28 |
+
def __init__(self) -> None:
|
| 29 |
+
self._last_idx: int = -1
|
| 30 |
+
|
| 31 |
+
def build_prompt(
|
| 32 |
+
self,
|
| 33 |
+
original_text: str,
|
| 34 |
+
analysis_result: dict[str, Any],
|
| 35 |
+
) -> tuple[str, str, str]:
|
| 36 |
+
"""Build the full prompt for the LLM.
|
| 37 |
+
|
| 38 |
+
Returns:
|
| 39 |
+
Tuple of (system_prompt, user_content, variant_id).
|
| 40 |
+
"""
|
| 41 |
+
variant = self._pick_variant()
|
| 42 |
+
word_count = count_words(original_text)
|
| 43 |
+
max_words = int(word_count * 1.35)
|
| 44 |
+
hard_max = int(word_count * 1.40)
|
| 45 |
+
|
| 46 |
+
rules = CORE_RULES.format(
|
| 47 |
+
word_count=word_count,
|
| 48 |
+
max_words=max_words,
|
| 49 |
+
hard_max=hard_max,
|
| 50 |
+
)
|
| 51 |
+
system_prompt = (
|
| 52 |
+
f"{variant['role']}\n\n"
|
| 53 |
+
f"{rules}\n"
|
| 54 |
+
f"{variant['micro']}"
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
# Build user content using "notes from source" framing
|
| 58 |
+
notes = self._extract_notes(original_text)
|
| 59 |
+
analysis_text = self.format_analysis_for_llm(analysis_result)
|
| 60 |
+
banned_words = analysis_result.get("banned_words", [])
|
| 61 |
+
banned_str = ", ".join(banned_words) if banned_words else "(none)"
|
| 62 |
+
|
| 63 |
+
user_content = (
|
| 64 |
+
f"{analysis_text}\n\n"
|
| 65 |
+
f"WORDS TO AVOID in your output: {banned_str}\n\n"
|
| 66 |
+
f"SOURCE NOTES:\n"
|
| 67 |
+
f"{notes}\n\n"
|
| 68 |
+
f"CONTENT RULES:\n"
|
| 69 |
+
f"- Cover EVERY numbered section and heading shown above, in the same order\n"
|
| 70 |
+
f"- Every tool name, plugin name, number, and technical term must appear\n"
|
| 71 |
+
f"- Do NOT add new sections or substitute different topics\n"
|
| 72 |
+
f"- Write each section fresh -- different sentence structure and phrasing\n\n"
|
| 73 |
+
f"Write ONLY the article text. No preamble, no commentary, no meta-text."
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
logger.info("Using prompt variant: %s", variant["id"])
|
| 77 |
+
return system_prompt, user_content, variant["id"]
|
| 78 |
+
|
| 79 |
+
@staticmethod
|
| 80 |
+
def _extract_notes(text: str) -> str:
|
| 81 |
+
"""Extract key points from the original text as structured notes.
|
| 82 |
+
|
| 83 |
+
Presents the source material as "notes to write from" rather than
|
| 84 |
+
"text to rewrite." This changes the model's generation framing.
|
| 85 |
+
|
| 86 |
+
Preserves:
|
| 87 |
+
- Section structure (numbered items, headings)
|
| 88 |
+
- All facts, names, numbers, technical terms
|
| 89 |
+
- The logical organization of ideas
|
| 90 |
+
|
| 91 |
+
Strips:
|
| 92 |
+
- Flowery phrasing and AI vocabulary
|
| 93 |
+
- Significance inflation sentences
|
| 94 |
+
- Generic conclusion language
|
| 95 |
+
"""
|
| 96 |
+
lines = text.strip().split('\n')
|
| 97 |
+
notes_lines = []
|
| 98 |
+
|
| 99 |
+
for line in lines:
|
| 100 |
+
stripped = line.strip()
|
| 101 |
+
if not stripped:
|
| 102 |
+
notes_lines.append('')
|
| 103 |
+
continue
|
| 104 |
+
|
| 105 |
+
# Keep headings and numbered items as structural markers
|
| 106 |
+
if re.match(r'^(\d+\.|\d+\.\d+\.?|#{1,3})', stripped):
|
| 107 |
+
notes_lines.append(stripped)
|
| 108 |
+
continue
|
| 109 |
+
|
| 110 |
+
# Strip significance inflation phrases but keep the core content
|
| 111 |
+
stripped = re.sub(
|
| 112 |
+
r'\b(marks? a pivotal|is a testament to|fundamentally transformed?|'
|
| 113 |
+
r'undoubtedly one of the most|represents? a (?:significant|major) shift|'
|
| 114 |
+
r'has (?:profound|significant) implications|is reshaping|'
|
| 115 |
+
r'has revolutionized?|stands? as a reminder)\b',
|
| 116 |
+
'', stripped, flags=re.IGNORECASE
|
| 117 |
+
)
|
| 118 |
+
# Strip filler openers
|
| 119 |
+
stripped = re.sub(
|
| 120 |
+
r'^(In today\'?s rapidly evolving|In the ever-evolving|'
|
| 121 |
+
r'It is (widely|commonly|generally) (known|recognized|understood) that|'
|
| 122 |
+
r'It goes without saying that|It is important to note that)\s*',
|
| 123 |
+
'', stripped, flags=re.IGNORECASE
|
| 124 |
+
)
|
| 125 |
+
stripped = stripped.strip()
|
| 126 |
+
if stripped:
|
| 127 |
+
notes_lines.append(stripped)
|
| 128 |
+
|
| 129 |
+
return '\n'.join(notes_lines)
|
| 130 |
+
|
| 131 |
+
@staticmethod
|
| 132 |
+
def format_analysis_for_llm(analysis_result: dict[str, Any]) -> str:
|
| 133 |
+
"""Convert Stage 1 analysis into writing guidance."""
|
| 134 |
+
summary = analysis_result.get("summary", {})
|
| 135 |
+
total = summary.get("total_sentences", 0)
|
| 136 |
+
high = summary.get("high_risk_sentences", 0)
|
| 137 |
+
ai_vocab = summary.get("ai_vocabulary_count", 0)
|
| 138 |
+
burst_cv = summary.get("burstiness_cv", 0)
|
| 139 |
+
burst_rating = summary.get("burstiness_rating", "unknown")
|
| 140 |
+
|
| 141 |
+
lines = ["WRITING GUIDANCE:\n"]
|
| 142 |
+
|
| 143 |
+
if high > 0:
|
| 144 |
+
lines.append(
|
| 145 |
+
f"- {high} of {total} sentences in the source are highly predictable "
|
| 146 |
+
f"(standard AI phrasing). Write with more varied, less expected phrasing."
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
if ai_vocab > 0:
|
| 150 |
+
lines.append(
|
| 151 |
+
f"- {ai_vocab} AI vocabulary words found in source. Your output must "
|
| 152 |
+
f"avoid these and use simpler, more direct alternatives."
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
if burst_rating in ("high_uniformity", "moderate_uniformity"):
|
| 156 |
+
lines.append(
|
| 157 |
+
f"- Source has very uniform sentence lengths (CV: {burst_cv:.2f}). "
|
| 158 |
+
f"Mix short (4-8 word) and long (22-35 word) sentences throughout."
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
lines.append(
|
| 162 |
+
"\nWrite fresh from the notes above. Different words, same information."
|
| 163 |
+
)
|
| 164 |
+
return "\n".join(lines)
|
| 165 |
+
|
| 166 |
+
def _pick_variant(self) -> dict[str, str]:
|
| 167 |
+
"""Pick a random variant, ensuring no consecutive repeats."""
|
| 168 |
+
if len(VARIANTS) <= 1:
|
| 169 |
+
self._last_idx = 0
|
| 170 |
+
return VARIANTS[0]
|
| 171 |
+
while True:
|
| 172 |
+
idx = random.randint(0, len(VARIANTS) - 1)
|
| 173 |
+
if idx != self._last_idx:
|
| 174 |
+
break
|
| 175 |
+
self._last_idx = idx
|
| 176 |
+
return VARIANTS[idx]
|
app/main.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
"""
|
| 2 |
-
Humanization Engine
|
| 3 |
|
| 4 |
Models are loaded once at startup via the lifespan context manager
|
| 5 |
and shared across all async requests.
|
|
@@ -21,7 +21,7 @@ from app.config import get_settings
|
|
| 21 |
logger = logging.getLogger(__name__)
|
| 22 |
|
| 23 |
# ---------------------------------------------------------------------------
|
| 24 |
-
# Application-level state
|
| 25 |
# ---------------------------------------------------------------------------
|
| 26 |
|
| 27 |
_start_time: float = 0.0
|
|
@@ -36,13 +36,14 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
|
| 36 |
settings = get_settings()
|
| 37 |
_start_time = time.time()
|
| 38 |
|
| 39 |
-
logger.info("Starting Humanization Engine
|
| 40 |
|
| 41 |
# ---- 1. spaCy ----
|
|
|
|
| 42 |
try:
|
| 43 |
import spacy # type: ignore
|
| 44 |
|
| 45 |
-
logger.info("Loading spaCy model '%s'
|
| 46 |
nlp = spacy.load(settings.spacy_model)
|
| 47 |
app.state.nlp = nlp
|
| 48 |
logger.info("spaCy loaded.")
|
|
@@ -51,10 +52,11 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
|
| 51 |
app.state.nlp = None
|
| 52 |
|
| 53 |
# ---- 2. Qwen2.5-0.5B perplexity scorer ----
|
|
|
|
| 54 |
try:
|
| 55 |
from app.core.perplexity_scorer import PerplexityScorer
|
| 56 |
|
| 57 |
-
logger.info("Loading Qwen2.5-0.5B perplexity scorer (~1.1 GB RAM)
|
| 58 |
scorer = PerplexityScorer(model_id=settings.qwen_model_id)
|
| 59 |
app.state.perplexity_scorer = scorer
|
| 60 |
logger.info("Qwen2.5-0.5B loaded.")
|
|
@@ -62,22 +64,12 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
|
| 62 |
logger.error("Failed to load perplexity scorer: %s", exc)
|
| 63 |
app.state.perplexity_scorer = None
|
| 64 |
|
| 65 |
-
# ---- 3.
|
| 66 |
-
|
| 67 |
-
from app.core.analyzers.vocabulary import VocabularyAnalyzer
|
| 68 |
-
|
| 69 |
-
vocab_analyzer = VocabularyAnalyzer(vocab_path=settings.ai_vocabulary_path)
|
| 70 |
-
app.state.vocab_analyzer = vocab_analyzer
|
| 71 |
-
logger.info("AI vocabulary database loaded.")
|
| 72 |
-
except Exception as exc:
|
| 73 |
-
logger.error("Failed to load vocabulary database: %s", exc)
|
| 74 |
-
app.state.vocab_analyzer = None
|
| 75 |
-
|
| 76 |
-
# ---- 4. language_tool_python ----
|
| 77 |
try:
|
| 78 |
import language_tool_python # type: ignore
|
| 79 |
|
| 80 |
-
logger.info("Initialising LanguageTool
|
| 81 |
language_tool = language_tool_python.LanguageTool("en-US")
|
| 82 |
app.state.language_tool = language_tool
|
| 83 |
logger.info("LanguageTool ready.")
|
|
@@ -85,26 +77,97 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
|
| 85 |
logger.error("Failed to initialise LanguageTool: %s", exc)
|
| 86 |
app.state.language_tool = None
|
| 87 |
|
| 88 |
-
# ----
|
| 89 |
-
if
|
| 90 |
try:
|
| 91 |
-
logger.info("Warming up Qwen2.5-0.5B
|
| 92 |
-
|
| 93 |
logger.info("Qwen2.5-0.5B warm-up complete.")
|
| 94 |
except Exception as exc:
|
| 95 |
logger.warning("Warm-up inference failed: %s", exc)
|
| 96 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
_models_loaded = True
|
| 98 |
logger.info("Humanization Engine ready. Startup complete.")
|
| 99 |
|
| 100 |
yield # Application runs here
|
| 101 |
|
| 102 |
# ---- Shutdown: release resources ----
|
| 103 |
-
logger.info("Shutting down
|
| 104 |
-
if
|
| 105 |
-
del
|
| 106 |
-
if
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
| 108 |
logger.info("Shutdown complete.")
|
| 109 |
|
| 110 |
|
|
@@ -124,14 +187,14 @@ def create_app() -> FastAPI:
|
|
| 124 |
application = FastAPI(
|
| 125 |
title="Humanization Engine",
|
| 126 |
description=(
|
| 127 |
-
"Analysis-Guided LLM Rewrite
|
| 128 |
"preserving academic quality."
|
| 129 |
),
|
| 130 |
version="1.0.0",
|
| 131 |
lifespan=lifespan,
|
| 132 |
)
|
| 133 |
|
| 134 |
-
# CORS
|
| 135 |
application.add_middleware(
|
| 136 |
CORSMiddleware,
|
| 137 |
allow_origins=["*"],
|
|
|
|
| 1 |
"""
|
| 2 |
+
Humanization Engine -- FastAPI application entry point.
|
| 3 |
|
| 4 |
Models are loaded once at startup via the lifespan context manager
|
| 5 |
and shared across all async requests.
|
|
|
|
| 21 |
logger = logging.getLogger(__name__)
|
| 22 |
|
| 23 |
# ---------------------------------------------------------------------------
|
| 24 |
+
# Application-level state -- models loaded once, shared across requests
|
| 25 |
# ---------------------------------------------------------------------------
|
| 26 |
|
| 27 |
_start_time: float = 0.0
|
|
|
|
| 36 |
settings = get_settings()
|
| 37 |
_start_time = time.time()
|
| 38 |
|
| 39 |
+
logger.info("Starting Humanization Engine ...")
|
| 40 |
|
| 41 |
# ---- 1. spaCy ----
|
| 42 |
+
nlp = None
|
| 43 |
try:
|
| 44 |
import spacy # type: ignore
|
| 45 |
|
| 46 |
+
logger.info("Loading spaCy model '%s' ...", settings.spacy_model)
|
| 47 |
nlp = spacy.load(settings.spacy_model)
|
| 48 |
app.state.nlp = nlp
|
| 49 |
logger.info("spaCy loaded.")
|
|
|
|
| 52 |
app.state.nlp = None
|
| 53 |
|
| 54 |
# ---- 2. Qwen2.5-0.5B perplexity scorer ----
|
| 55 |
+
scorer = None
|
| 56 |
try:
|
| 57 |
from app.core.perplexity_scorer import PerplexityScorer
|
| 58 |
|
| 59 |
+
logger.info("Loading Qwen2.5-0.5B perplexity scorer (~1.1 GB RAM) ...")
|
| 60 |
scorer = PerplexityScorer(model_id=settings.qwen_model_id)
|
| 61 |
app.state.perplexity_scorer = scorer
|
| 62 |
logger.info("Qwen2.5-0.5B loaded.")
|
|
|
|
| 64 |
logger.error("Failed to load perplexity scorer: %s", exc)
|
| 65 |
app.state.perplexity_scorer = None
|
| 66 |
|
| 67 |
+
# ---- 3. language_tool_python ----
|
| 68 |
+
language_tool = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
try:
|
| 70 |
import language_tool_python # type: ignore
|
| 71 |
|
| 72 |
+
logger.info("Initialising LanguageTool ...")
|
| 73 |
language_tool = language_tool_python.LanguageTool("en-US")
|
| 74 |
app.state.language_tool = language_tool
|
| 75 |
logger.info("LanguageTool ready.")
|
|
|
|
| 77 |
logger.error("Failed to initialise LanguageTool: %s", exc)
|
| 78 |
app.state.language_tool = None
|
| 79 |
|
| 80 |
+
# ---- 4. Warm up Qwen2.5 with a dummy inference ----
|
| 81 |
+
if scorer is not None:
|
| 82 |
try:
|
| 83 |
+
logger.info("Warming up Qwen2.5-0.5B ...")
|
| 84 |
+
scorer.score_sentence("This is a warm-up sentence.")
|
| 85 |
logger.info("Qwen2.5-0.5B warm-up complete.")
|
| 86 |
except Exception as exc:
|
| 87 |
logger.warning("Warm-up inference failed: %s", exc)
|
| 88 |
|
| 89 |
+
# ---- 5. Build Stage 1 TextAnalyzer ----
|
| 90 |
+
analyzer = None
|
| 91 |
+
try:
|
| 92 |
+
from app.core.analyzer import TextAnalyzer
|
| 93 |
+
|
| 94 |
+
analyzer = TextAnalyzer(
|
| 95 |
+
nlp=nlp,
|
| 96 |
+
perplexity_scorer=scorer,
|
| 97 |
+
vocab_path=settings.ai_vocabulary_path,
|
| 98 |
+
transition_path=settings.transition_words_path,
|
| 99 |
+
heuristic_path=settings.heuristic_patterns_path,
|
| 100 |
+
)
|
| 101 |
+
app.state.analyzer = analyzer
|
| 102 |
+
logger.info("TextAnalyzer (Stage 1) ready.")
|
| 103 |
+
except Exception as exc:
|
| 104 |
+
logger.error("Failed to create TextAnalyzer: %s", exc)
|
| 105 |
+
app.state.analyzer = None
|
| 106 |
+
|
| 107 |
+
# ---- 6. Build Stage 2 LLMRewriter ----
|
| 108 |
+
rewriter = None
|
| 109 |
+
try:
|
| 110 |
+
from app.core.prompt_manager import PromptManager
|
| 111 |
+
from app.core.llm_rewriter import LLMRewriter
|
| 112 |
+
|
| 113 |
+
prompt_manager = PromptManager()
|
| 114 |
+
rewriter = LLMRewriter(prompt_manager=prompt_manager)
|
| 115 |
+
app.state.rewriter = rewriter
|
| 116 |
+
logger.info("LLMRewriter (Stage 2) ready.")
|
| 117 |
+
except Exception as exc:
|
| 118 |
+
logger.error("Failed to create LLMRewriter: %s", exc)
|
| 119 |
+
app.state.rewriter = None
|
| 120 |
+
|
| 121 |
+
# ---- 7. Build Stage 3 PostValidator ----
|
| 122 |
+
post_validator = None
|
| 123 |
+
try:
|
| 124 |
+
from app.core.post_validator import PostValidator
|
| 125 |
+
|
| 126 |
+
post_validator = PostValidator(
|
| 127 |
+
nlp=nlp,
|
| 128 |
+
perplexity_scorer=scorer,
|
| 129 |
+
language_tool=language_tool,
|
| 130 |
+
vocab_path=settings.ai_vocabulary_path,
|
| 131 |
+
)
|
| 132 |
+
app.state.post_validator = post_validator
|
| 133 |
+
logger.info("PostValidator (Stage 3) ready.")
|
| 134 |
+
except Exception as exc:
|
| 135 |
+
logger.error("Failed to create PostValidator: %s", exc)
|
| 136 |
+
app.state.post_validator = None
|
| 137 |
+
|
| 138 |
+
# ---- 8. Wire up the full pipeline ----
|
| 139 |
+
try:
|
| 140 |
+
from app.core.pipeline import HumanizationPipeline
|
| 141 |
+
|
| 142 |
+
if analyzer and rewriter and post_validator:
|
| 143 |
+
pipeline = HumanizationPipeline(
|
| 144 |
+
analyzer=analyzer,
|
| 145 |
+
rewriter=rewriter,
|
| 146 |
+
post_validator=post_validator,
|
| 147 |
+
)
|
| 148 |
+
app.state.pipeline = pipeline
|
| 149 |
+
logger.info("HumanizationPipeline wired and ready.")
|
| 150 |
+
else:
|
| 151 |
+
app.state.pipeline = None
|
| 152 |
+
logger.warning("Pipeline not created: one or more stages missing.")
|
| 153 |
+
except Exception as exc:
|
| 154 |
+
logger.error("Failed to create pipeline: %s", exc)
|
| 155 |
+
app.state.pipeline = None
|
| 156 |
+
|
| 157 |
_models_loaded = True
|
| 158 |
logger.info("Humanization Engine ready. Startup complete.")
|
| 159 |
|
| 160 |
yield # Application runs here
|
| 161 |
|
| 162 |
# ---- Shutdown: release resources ----
|
| 163 |
+
logger.info("Shutting down ...")
|
| 164 |
+
if scorer:
|
| 165 |
+
del scorer
|
| 166 |
+
if language_tool:
|
| 167 |
+
try:
|
| 168 |
+
language_tool.close()
|
| 169 |
+
except Exception:
|
| 170 |
+
pass
|
| 171 |
logger.info("Shutdown complete.")
|
| 172 |
|
| 173 |
|
|
|
|
| 187 |
application = FastAPI(
|
| 188 |
title="Humanization Engine",
|
| 189 |
description=(
|
| 190 |
+
"Analysis-Guided LLM Rewrite -- bypasses AI detection while "
|
| 191 |
"preserving academic quality."
|
| 192 |
),
|
| 193 |
version="1.0.0",
|
| 194 |
lifespan=lifespan,
|
| 195 |
)
|
| 196 |
|
| 197 |
+
# CORS -- allow all origins for development
|
| 198 |
application.add_middleware(
|
| 199 |
CORSMiddleware,
|
| 200 |
allow_origins=["*"],
|
app/prompts/variants.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Prompt variants for Stage 2.
|
| 3 |
+
|
| 4 |
+
KEY INSIGHT: Asking an LLM to "rewrite" text produces a known statistical
|
| 5 |
+
fingerprint that Originality.ai v3.0 is specifically trained to detect.
|
| 6 |
+
|
| 7 |
+
Instead: present key points extracted from the source and ask the model to
|
| 8 |
+
WRITE A FRESH PIECE from those notes. This changes the generation task from
|
| 9 |
+
"paraphrase" to "write" — a fundamentally different token distribution.
|
| 10 |
+
|
| 11 |
+
The role/voice is varied across 8 variants to increase token diversity.
|
| 12 |
+
All variants share the same structural and anti-AI-pattern rules.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
# ---------------------------------------------------------------------------
|
| 18 |
+
# Core rules -- shared across all variants
|
| 19 |
+
# ---------------------------------------------------------------------------
|
| 20 |
+
|
| 21 |
+
CORE_RULES: str = """\
|
| 22 |
+
You have been given notes and key points from an article on this topic.
|
| 23 |
+
Write a NEW piece covering these points. Do NOT copy the original phrasing.
|
| 24 |
+
Write as if you are the author, explaining these ideas in your own words for the first time.
|
| 25 |
+
|
| 26 |
+
FORMAT:
|
| 27 |
+
- Keep the same document structure: if the notes show numbered sections, keep them
|
| 28 |
+
- Keep section headings (you may rephrase them)
|
| 29 |
+
- Write in plain text: no markdown bold (**), italic (*), or heading (#) markers
|
| 30 |
+
- No em-dashes. Use commas or periods instead
|
| 31 |
+
- Target length: {word_count} to {max_words} words. Hard ceiling: {hard_max} words
|
| 32 |
+
|
| 33 |
+
WHAT TO AVOID (these are AI detection signals -- violating them means the text is flagged):
|
| 34 |
+
|
| 35 |
+
Grammar/structure signals:
|
| 36 |
+
- "serves as", "stands as", "functions as", "acts as" -- just say "is" or "are"
|
| 37 |
+
- "It's not just X; it's Y" / "Not just about X, it's about Y" -- state the point directly
|
| 38 |
+
- Sentences ending with "...highlighting X" "...underscoring Y" "...reflecting Z"
|
| 39 |
+
"...fostering" "...contributing to" -- cut the tail or make it a separate sentence
|
| 40 |
+
- "In order to" -- say "to"
|
| 41 |
+
- "Due to the fact that" -- say "because"
|
| 42 |
+
- "At its core" / "First and foremost" / "It goes without saying" / "It is worth noting" -- delete
|
| 43 |
+
- "has the potential to" -- say "can"
|
| 44 |
+
- "has the ability to" -- say "can"
|
| 45 |
+
|
| 46 |
+
Content signals:
|
| 47 |
+
- Significance inflation: "marks a pivotal moment", "is a testament to",
|
| 48 |
+
"fundamentally transformed", "undoubtedly one of the most", "is reshaping",
|
| 49 |
+
"represents a shift" -- say what it actually does instead
|
| 50 |
+
- Generic positive endings: "the future looks bright", "exciting times ahead",
|
| 51 |
+
"get started today", "will appreciate the difference" -- end with a plain fact
|
| 52 |
+
- Vague attributions: "experts say", "studies show", "research indicates" -- name
|
| 53 |
+
the specific source or remove the claim
|
| 54 |
+
- Rule of three for abstract things: "innovation, inspiration, and insights" -- either
|
| 55 |
+
use 2 items or make all 3 concrete
|
| 56 |
+
|
| 57 |
+
Vocabulary (never use these words):
|
| 58 |
+
additionally, moreover, furthermore, align, leverage, utilize, enhance, foster,
|
| 59 |
+
streamline, empower, bolster, mitigate, encompass, underscore, spearhead,
|
| 60 |
+
revolutionize, elevate, cultivate, seamless, robust, comprehensive, pivotal,
|
| 61 |
+
transformative, unprecedented, multifaceted, intricate, indispensable, noteworthy,
|
| 62 |
+
burgeoning, overarching, significantly, dramatically, essentially, predominantly,
|
| 63 |
+
fundamentally, landscape (when abstract), paradigm, synergy, stakeholders,
|
| 64 |
+
tapestry, testament, interplay
|
| 65 |
+
|
| 66 |
+
HOW TO WRITE:
|
| 67 |
+
- Mix sentence lengths unevenly: some under 6 words, some over 25, not a pattern
|
| 68 |
+
- Use contractions sometimes, not always: "don't" in one sentence, "do not" elsewhere
|
| 69 |
+
- Use "is" and "are" freely -- they are fine
|
| 70 |
+
- Have a mild opinion occasionally: "this works well" or "this part is a bit annoying"
|
| 71 |
+
- Some sentences can be plain and unremarkable. Not every sentence needs to be interesting
|
| 72 |
+
- Leave rough edges. Perfect polish is an AI signal
|
| 73 |
+
- Preserve all facts: names, numbers, tool names, URLs, technical terms
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
# ---------------------------------------------------------------------------
|
| 77 |
+
# Variants -- different voice framings to vary statistical distribution
|
| 78 |
+
# ---------------------------------------------------------------------------
|
| 79 |
+
|
| 80 |
+
VARIANTS: list[dict[str, str]] = [
|
| 81 |
+
{
|
| 82 |
+
"id": "variant_1",
|
| 83 |
+
"role": (
|
| 84 |
+
"You are a blogger who writes about this topic because you actually use "
|
| 85 |
+
"it. You write plainly and directly. You say 'is' when something is something. "
|
| 86 |
+
"You don't dress things up. When something has a limitation, you mention it."
|
| 87 |
+
),
|
| 88 |
+
"micro": (
|
| 89 |
+
"Write as if explaining this to someone who asked you about it. "
|
| 90 |
+
"Start some sentences with 'But' or 'And'. "
|
| 91 |
+
"Use 'you' and 'your' when addressing the reader. "
|
| 92 |
+
"Let one sentence be slightly blunt or direct. "
|
| 93 |
+
"The final sentence should be a plain observation, not a call to action."
|
| 94 |
+
),
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
"id": "variant_2",
|
| 98 |
+
"role": (
|
| 99 |
+
"You are a person who reads about this topic and writes up what you "
|
| 100 |
+
"learned. Your writing is clear but not polished. You use everyday words. "
|
| 101 |
+
"You sometimes use slightly unusual phrasing -- not wrong, just not the "
|
| 102 |
+
"obvious choice."
|
| 103 |
+
),
|
| 104 |
+
"micro": (
|
| 105 |
+
"Use at least one word or phrase that's slightly unexpected but correct "
|
| 106 |
+
"(e.g. 'fix up' instead of 'improve', 'handy' instead of 'useful'). "
|
| 107 |
+
"One sentence should have a clause that's slightly clunky -- a real person "
|
| 108 |
+
"would have written it that way without editing. "
|
| 109 |
+
"End on a factual note, not an inspirational one."
|
| 110 |
+
),
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
"id": "variant_3",
|
| 114 |
+
"role": (
|
| 115 |
+
"You write about technical topics for a general audience. Your goal is "
|
| 116 |
+
"clarity, not style. You use short sentences when the point is simple. "
|
| 117 |
+
"You use longer sentences when the idea needs context. You don't repeat "
|
| 118 |
+
"vocabulary unnecessarily -- if the best word is the same word, use it twice."
|
| 119 |
+
),
|
| 120 |
+
"micro": (
|
| 121 |
+
"Vary sentence length deliberately: one sentence under 5 words, one over 30. "
|
| 122 |
+
"Do NOT use a synonym just to avoid repetition -- repeat the word if it's clearest. "
|
| 123 |
+
"Use one parenthetical aside (like this) where it fits. "
|
| 124 |
+
"Check every sentence ending -- no -ing tails."
|
| 125 |
+
),
|
| 126 |
+
},
|
| 127 |
+
{
|
| 128 |
+
"id": "variant_4",
|
| 129 |
+
"role": (
|
| 130 |
+
"You write with a conversational but not chatty tone. You explain things "
|
| 131 |
+
"step by step. You're comfortable saying 'basically' or 'pretty much' "
|
| 132 |
+
"when it fits. You don't try to impress -- you try to be useful."
|
| 133 |
+
),
|
| 134 |
+
"micro": (
|
| 135 |
+
"Use 'basically' or 'pretty much' once where it fits naturally. "
|
| 136 |
+
"Use 'also' or 'and' instead of 'additionally' or 'furthermore'. "
|
| 137 |
+
"Start the final section with a simple declarative sentence. "
|
| 138 |
+
"Avoid any sentence that sounds like it belongs in a brochure."
|
| 139 |
+
),
|
| 140 |
+
},
|
| 141 |
+
{
|
| 142 |
+
"id": "variant_5",
|
| 143 |
+
"role": (
|
| 144 |
+
"You write like someone who knows this topic from actually working with it. "
|
| 145 |
+
"You have preferences. Some things work better than others in your experience. "
|
| 146 |
+
"You say so. Your writing is grounded -- you mention specific things, not "
|
| 147 |
+
"abstract categories."
|
| 148 |
+
),
|
| 149 |
+
"micro": (
|
| 150 |
+
"Include one specific preference or mild opinion ('X works better than Y "
|
| 151 |
+
"for most cases' or 'this part is a bit more complex than it needs to be'). "
|
| 152 |
+
"Reference the concrete items by name, not by category. "
|
| 153 |
+
"Write the conclusion as a real closing thought, not a summary of the article."
|
| 154 |
+
),
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"id": "variant_6",
|
| 158 |
+
"role": (
|
| 159 |
+
"You write in a slightly informal professional tone. You mix registers: "
|
| 160 |
+
"a formal sentence followed by a casual one is fine. You don't worry about "
|
| 161 |
+
"consistency of tone. Real writing mixes registers. You use simple words "
|
| 162 |
+
"where they fit, technical terms where they're needed."
|
| 163 |
+
),
|
| 164 |
+
"micro": (
|
| 165 |
+
"Follow at least one formal-sounding sentence with something casual. "
|
| 166 |
+
"Use one informal word in a paragraph that otherwise reads more formally. "
|
| 167 |
+
"Vary your sentence openers -- don't start multiple sentences with 'The'. "
|
| 168 |
+
"No sentence should end with 'as well.' Use 'too' instead."
|
| 169 |
+
),
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"id": "variant_7",
|
| 173 |
+
"role": (
|
| 174 |
+
"You are explaining this topic as if you are writing notes that will become "
|
| 175 |
+
"a draft. You're not in polishing mode. You just want the ideas on the page "
|
| 176 |
+
"clearly. Some sentences come out better than others. That's okay."
|
| 177 |
+
),
|
| 178 |
+
"micro": (
|
| 179 |
+
"Include one sentence that's a bit longer than ideal -- real drafts have them. "
|
| 180 |
+
"Use one question (rhetorical or otherwise) if it fits naturally. "
|
| 181 |
+
"Repeat a key term where repeating it is clearer than using a synonym. "
|
| 182 |
+
"The final paragraph should feel like a real closing, not a motivational poster."
|
| 183 |
+
),
|
| 184 |
+
},
|
| 185 |
+
{
|
| 186 |
+
"id": "variant_8",
|
| 187 |
+
"role": (
|
| 188 |
+
"You are a careful writer who finds AI-sounding text annoying. You actively "
|
| 189 |
+
"avoid the patterns AI produces. You use simple constructions. You say what "
|
| 190 |
+
"you mean without decoration. If something is good, you say it's good. "
|
| 191 |
+
"If something is complicated, you say it's complicated."
|
| 192 |
+
),
|
| 193 |
+
"micro": (
|
| 194 |
+
"Check every sentence: does it use 'is' or 'are' where it could? "
|
| 195 |
+
"Does it end cleanly without an -ing tail? Does it avoid significance inflation? "
|
| 196 |
+
"Replace any sentence that sounds like it's trying to sound important. "
|
| 197 |
+
"End on a plain, specific note. Not a conclusion -- just the last thing to say."
|
| 198 |
+
),
|
| 199 |
+
},
|
| 200 |
+
]
|
testing_texts.txt
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
1
|
| 2 |
+
|
| 3 |
+
7 Easy Ways to Make Your WordPress Site Load Lightning Fast in 2025
|
| 4 |
+
|
| 5 |
+
Let’s be real — a slow WordPress site is a dead site. In 2025, people expect instant loading, and Google demands it. If your site takes more than 3 seconds to load, you’re losing traffic, rankings, and sales.
|
| 6 |
+
But don’t panic. You don’t need to be a developer to fix it. Here are 7 powerful (and beginner-friendly) ways to speed up your WordPress site today.
|
| 7 |
+
1. Use a Lightweight Theme
|
| 8 |
+
Bloated themes = slow pages. Switch to fast, optimized themes like Astra, GeneratePress, or Blocksy. These are built for speed, especially when paired with Gutenberg or Elementor.
|
| 9 |
+
2. Install a Caching Plugin
|
| 10 |
+
Caching is a must. It stores static versions of your pages, so they load faster for repeat visitors. Try LiteSpeed Cache, WP Rocket (paid), or W3 Total Cache. Set it and forget it.
|
| 11 |
+
3. Serve Images in WebP
|
| 12 |
+
Old-school JPGs are heavy. Switch to WebP format for faster loading and better Google PageSpeed scores. Use plugins like ShortPixel, Imagify, or WebP Express to convert and serve images automatically.
|
| 13 |
+
4. Lazy Load Images & Videos
|
| 14 |
+
Why load offscreen content? Enable lazy loading to load images and videos only when users scroll to them. WordPress 5.5+ has built-in lazy loading — just make sure your theme or plugin isn’t disabling it.
|
| 15 |
+
5. Use a CDN (Content Delivery Network)
|
| 16 |
+
A CDN like Cloudflare, BunnyCDN, or Jetpack CDN can cut load times by up to 50%, especially for global visitors. They serve your site’s static content from servers closest to your users.
|
| 17 |
+
6. Limit Plugins and Clean Up Your Database
|
| 18 |
+
More plugins = more load. Only keep what you really need. Then clean up old post revisions, spam comments, and transient data using WP-Optimize or Advanced Database Cleaner.
|
| 19 |
+
7. Enable GZIP or Brotli Compression
|
| 20 |
+
Your server should compress files before sending them. If you’re using LiteSpeed, Nginx, or even Apache, you can enable Brotli (better) or GZIP via your hosting panel or a plugin like Enable GZIP Compression.
|
| 21 |
+
Final Word
|
| 22 |
+
Speed isn’t optional anymore — it’s survival. These 7 WordPress-friendly tips are easy to implement and can dramatically improve your load times, SEO scores, and user experience.
|
| 23 |
+
Start today. Your users — and Google — will notice.
|
| 24 |
+
|
| 25 |
+
2
|
| 26 |
+
|
| 27 |
+
Why iPhone Is the Best Smartphone in the World — And Why Android Can’t Compete
|
| 28 |
+
In the ever-evolving world of smartphones, one question remains timeless: which is better — iPhone or Android? While Android manufacturers have made progress over the years, the iPhone continues to dominate as the gold standard of mobile devices. In this article, we explore why the iPhone stands above the rest and remains the best smartphone in the world.
|
| 29 |
+
1. Seamless Ecosystem Integration
|
| 30 |
+
The iPhone is not just a phone — it’s part of a seamless Apple ecosystem. With features like AirDrop, iCloud, Handoff, and Universal Clipboard, users can move between their iPhone, MacBook, iPad, and Apple Watch effortlessly. Android simply cannot match the level of integration and fluidity across devices that Apple offers.
|
| 31 |
+
2. Superior Software Optimization
|
| 32 |
+
Apple controls both the hardware and software, allowing them to optimize iOS specifically for the iPhone’s internals. This means faster updates, better performance, and longer device longevity. Android phones, fragmented across countless manufacturers and custom UIs, often lag behind in updates and overall consistency.
|
| 33 |
+
3. Unmatched Security and Privacy
|
| 34 |
+
Apple places user privacy at the forefront. With features like App Tracking Transparency, Face ID encryption, and regular security updates, iPhones offer a level of protection that Android devices struggle to replicate. While Android is open-source, that openness comes at a cost — fragmentation, inconsistent security patches, and a higher attack surface.
|
| 35 |
+
4. Better Long-Term Value
|
| 36 |
+
iPhones retain their value longer than Android phones. It’s common to see iPhones being resold for strong prices even 3–4 years after release. They also receive iOS updates for 5+ years, making them a better investment. Most Android phones stop receiving major updates after 2–3 years.
|
| 37 |
+
5. Premium Build Quality and Design
|
| 38 |
+
Apple is known for its attention to detail, premium materials, and iconic minimalist design. Every iPhone is carefully engineered to provide a luxurious, consistent experience. Many Android phones vary greatly in build quality — from excellent to poor — depending on the brand and price tier.
|
| 39 |
+
6. The App Store Advantage
|
| 40 |
+
Developers often prioritize iOS due to higher user spending and better monetization options. As a result, many apps launch first on iOS, and some stay exclusive. The App Store is also more tightly curated, which reduces the number of low-quality or malicious apps.
|
| 41 |
+
7. Customer Support and Reliability
|
| 42 |
+
Apple offers world-class customer service through Apple Stores, certified service centers, and live chat. The reliability of both software and hardware, combined with excellent after-sales support, creates a worry-free experience. With Android, support varies widely between brands and regions.
|
| 43 |
+
8. Consistent Experience Across Devices
|
| 44 |
+
Whether you buy an iPhone 13 or iPhone 15 Pro Max, the user experience is consistent. This is not the case with Android, where software, features, and performance vary drastically between brands and even within product lines.
|
| 45 |
+
Conclusion: iPhone Sets the Standard
|
| 46 |
+
While Android phones have their strengths, the iPhone consistently leads in performance, reliability, privacy, and user satisfaction. Its seamless ecosystem, long-term value, and premium design make it the best smartphone in the world — not just today, but for years to come.
|
| 47 |
+
For those who want the most refined, secure, and long-lasting mobile experience, the choice is clear: choose iPhone.
|
| 48 |
+
|
| 49 |
+
3
|
| 50 |
+
|
| 51 |
+
PHP’s Final Curtain Call: 2025
|
| 52 |
+
In 2025 the global developer community finally agrees that PHP, once the undisputed king of server-side scripting, has slipped into irreversible decline. The language that powered countless blogs, forums, and shops for decades now survives mostly in dusty shared hosting plans and forgotten corporate intranets.
|
| 53 |
+
Modern teams chasing performance, scalability, and cloud-native workflows overwhelmingly select JavaScript, Rust, Go, or Python. These ecosystems deliver stronger tooling, richer type safety, and container images that boot in milliseconds. Meanwhile PHP’s update cadence, backward-compatibility baggage, and thread-per-request architecture feel increasingly archaic beside event-driven microservices.
|
| 54 |
+
Frameworks like Laravel and Symfony tried to modernize the stack, yet their maintainers are migrating experimental branches to Node.js and Bun. Recruiters label remaining PHP vacancies as “legacy refactor” roles. University curricula quietly drop the language, replacing it with full-stack TypeScript modules that better match industry demand.
|
| 55 |
+
Hosting providers accelerate the exodus. Popular platforms announce end-of-life dates for mod_php, urging customers to export data and adopt serverless functions. Security vendors predict a surge in unpatched PHP exploits after December, when community-driven support finally ceases.
|
| 56 |
+
Even WordPress, the stalwart that once single-handedly justified PHP’s footprint, now promotes an official headless edition compiled to WASM and served by Deno. Theme authors follow suit, rewriting templates in JSX to tap modern build pipelines.
|
| 57 |
+
Historians will remember PHP for democratizing web publishing in the 2000s. Yet technology marches forward. By every measurable metric—jobs, packages, performance, mindshare—2025 marks the moment PHP passes quietly into maintenance-only status, its vibrant era complete.
|
| 58 |
+
|
| 59 |
+
Frontend Programming: Crafting the Face of the Web
|
| 60 |
+
Introduction
|
| 61 |
+
In today’s digital age, websites and applications are the face of countless businesses, services, and personal projects. At the forefront of this virtual presence lies frontend programming, a discipline that blends design, functionality, and user experience to create engaging and interactive interfaces. This essay explores the nature of frontend programming, its core technologies, the evolving ecosystem, its challenges, and its critical role in modern software development.
|
| 62 |
+
|
| 63 |
+
1. What Is Frontend Programming?
|
| 64 |
+
Frontend programming refers to the development of the client-side of web applications—the part that users see and interact with directly in their web browsers. It involves converting design files and concepts into code that functions seamlessly across different devices and platforms.
|
| 65 |
+
The primary goal of frontend development is to ensure that user interfaces (UIs) are intuitive, responsive, visually appealing, and accessible. This includes everything from the layout and typography to interactive elements like buttons, forms, and animations.
|
| 66 |
+
|
| 67 |
+
2. Core Technologies of Frontend Development
|
| 68 |
+
2.1 HTML (HyperText Markup Language)
|
| 69 |
+
HTML provides the basic structure of a webpage. It defines elements like headings, paragraphs, links, images, and more. Without HTML, there would be no content to display.
|
| 70 |
+
2.2 CSS (Cascading Style Sheets)
|
| 71 |
+
CSS handles the visual styling of HTML elements. It allows developers to control the color, size, layout, and spacing of content. Advanced features like Flexbox, Grid, media queries, and animations enable responsive and modern designs.
|
| 72 |
+
2.3 JavaScript
|
| 73 |
+
JavaScript is the programming language of the web. It brings interactivity to websites—allowing for form validation, dynamic content updates, animations, and asynchronous communication with servers (via APIs). Frameworks and libraries like React, Vue, and Angular are built on top of JavaScript to streamline development.
|
| 74 |
+
|
| 75 |
+
4
|
| 76 |
+
|
| 77 |
+
3. The Rise of Frontend Frameworks and Libraries
|
| 78 |
+
3.1 React.js
|
| 79 |
+
Created by Facebook, React is a component-based library that revolutionized frontend development. It introduced concepts like the virtual DOM, hooks, and reusable components, making it easier to build scalable UIs.
|
| 80 |
+
3.2 Vue.js
|
| 81 |
+
Vue is a progressive framework that is simple to get started with but powerful enough for complex applications. Its syntax is clean, and it offers two-way data binding, making it a favorite among many developers.
|
| 82 |
+
3.3 Angular
|
| 83 |
+
Developed by Google, Angular is a comprehensive framework that comes with tools for building full-featured single-page applications (SPAs). It uses TypeScript, a strongly typed superset of JavaScript, to help write maintainable and scalable code.
|
| 84 |
+
Conclusion
|
| 85 |
+
Frontend programming is far more than just making websites look good. It requires a solid understanding of design principles, programming logic, performance tuning, and accessibility standards. As the digital world continues to expand, the demand for skilled frontend developers remains high.
|
| 86 |
+
By mastering both foundational technologies and modern tools, frontend developers can craft rich, engaging, and meaningful user experiences that define how people interact with the web. In a world where the first impression is often digital, frontend programming is not just valuable—it is essential.
|
| 87 |
+
|
| 88 |
+
5
|
| 89 |
+
|
| 90 |
+
The Importance of Self-Reflection
|
| 91 |
+
Self-reflection is a powerful tool that allows individuals to assess their actions, emotions, and thoughts. It’s the process of looking inward, understanding one’s motivations, and recognizing patterns in behavior. Though it may seem like a simple practice, the benefits of self-reflection are profound, offering us the opportunity to grow and improve as individuals.
|
| 92 |
+
One of the primary advantages of self-reflection is the ability to learn from past experiences. By taking time to reflect on our decisions, we can identify what worked well and what didn’t. This helps us avoid repeating mistakes and develop more effective strategies for the future. It’s like having a mirror for our actions, which gives us clarity and insight into our decision-making processes.
|
| 93 |
+
Self-reflection also plays a crucial role in emotional regulation. It enables us to understand why we react in certain ways to stress, joy, or conflict. By understanding the triggers behind our emotions, we can manage them more effectively, leading to healthier relationships and improved mental well-being. When we take a step back and think about our emotions, we can prevent impulsive reactions and choose more measured responses.
|
| 94 |
+
Furthermore, self-reflection encourages personal growth. It pushes us to question our beliefs, values, and goals. Are we living authentically? Are we on the path we want to be on? Regular self-reflection helps us align our actions with our core values, leading to a more fulfilling life. It reminds us that growth is a continuous process, not a one-time event.
|
| 95 |
+
In conclusion, self-reflection is an essential practice for personal development. It helps us learn from our past, understand our emotions, and align our actions with our values. By making self-reflection a habit, we can live more intentionally and lead a life of growth and fulfillment.
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
6
|
| 99 |
+
|
| 100 |
+
In the modern digital landscape, the importance of technology cannot be overstated. Technology plays a vital role in everyday life, business, communication, education, and global development. As artificial intelligence continues to grow, it is transforming industries and creating new opportunities. From healthcare to finance, from transportation to entertainment, AI is being implemented in diverse fields. The applications of AI are vast and include automation, data analysis, pattern recognition, and decision-making support.
|
| 101 |
+
Furthermore, machine learning, a subfield of AI, enables systems to learn from data and improve performance over time. This means that algorithms become more accurate and efficient. Natural language processing, another branch of AI, allows machines to understand and generate human language. This is particularly useful for chatbots, virtual assistants, and translation services.
|
| 102 |
+
In conclusion, the future of technology is deeply intertwined with artificial intelligence. As advancements continue, society must adapt to these changes. Innovation, progress, and digital transformation will shape the world of tomorrow. Embracing technology is not just an option—it is a necessity. With AI at the forefront, we can expect continued growth, enhanced productivity, and a smarter, more connected global society.
|
| 103 |
+
|
| 104 |
+
7
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
Is WordPress Still Alive in 2025?
|
| 108 |
+
In 2025, many people are asking the same question: Is WordPress still relevant? The short answer is yes — and here’s why.
|
| 109 |
+
WordPress has remained one of the most popular content management systems in the world for over two decades. With its open-source foundation, extensive plugin ecosystem, and customizable themes, WordPress continues to be the go-to solution for bloggers, small businesses, and even large corporations. Despite the rise of no-code website builders and headless CMS options, WordPress maintains a strong and dedicated user base.
|
| 110 |
+
One of the key reasons for its longevity is flexibility. Whether you want a blog, an online store, a portfolio, or a membership site, WordPress can handle it. Tools like WooCommerce, Elementor, and Yoast SEO make it easy to extend functionality without deep coding knowledge.
|
| 111 |
+
In addition, the WordPress community is still thriving. Thousands of developers, designers, and content creators continue to build themes, plugins, and tutorials. The WordPress ecosystem is not just surviving — it’s evolving.
|
| 112 |
+
Security and performance have also improved significantly. With regular updates, support for PHP 8+, and improved core stability, WordPress websites are faster and more secure than ever before.
|
| 113 |
+
In conclusion, WordPress is very much alive in 2025. It may not always be the trendiest platform, but it’s one of the most stable, versatile, and reliable tools for building a presence on the web. If anything, its adaptability ensures that it remains relevant — year after year.
|
| 114 |
+
|
| 115 |
+
8
|
| 116 |
+
|
| 117 |
+
Web3: The Future of a Decentralized Internet
|
| 118 |
+
Introduction
|
| 119 |
+
The internet has dramatically evolved since its inception. From the static web pages of Web1 to the interactive platforms of Web2, each phase has shaped how individuals interact, create, and communicate online. Now, the world is witnessing the emergence of Web3, a decentralized and user-owned iteration of the internet powered by blockchain technology. This essay will explore what Web3 is, how it differs from its predecessors, its potential benefits and challenges, and its broader implications for the future of technology and society.
|
| 120 |
+
|
| 121 |
+
1. Understanding the Evolution: From Web1 to Web3
|
| 122 |
+
1.1 Web1: The Read-Only Web
|
| 123 |
+
In the early days of the internet, Web1 (roughly from 1990 to 2004) was primarily read-only. Websites were static, offering information without much user interaction. Users were consumers of content created by a few developers and organizations. There was minimal user-generated content, and interactivity was limited to basic forms like email or guestbooks.
|
| 124 |
+
1.2 Web2: The Read-Write Web
|
| 125 |
+
Web2, emerging in the mid-2000s, introduced dynamic and interactive platforms like Facebook, YouTube, and Twitter. Users could not only consume content but also create and share their own through blogs, social media, and video platforms. However, Web2 is dominated by centralized corporations that control user data, monetize content, and often influence the digital narrative.
|
| 126 |
+
1.3 Web3: The Read-Write-Own Web
|
| 127 |
+
Web3 represents a paradigm shift toward a decentralized, user-centric internet. Built on blockchain technology, it allows individuals to truly own their data, digital identities, and even assets. Smart contracts, decentralized applications (dApps), cryptocurrencies, and non-fungible tokens (NFTs) are some of the key innovations driving this new phase.
|
| 128 |
+
|
| 129 |
+
2. Core Principles and Technologies Behind Web3
|
| 130 |
+
2.1 Decentralization
|
| 131 |
+
Unlike Web2, where a few tech giants manage vast amounts of information, Web3 distributes data across a network of computers (nodes). No single entity has overarching control. This structure reduces censorship risks and gives users greater autonomy over their digital lives.
|
| 132 |
+
2.2 Blockchain and Smart Contracts
|
| 133 |
+
Blockchain is the foundational technology of Web3, acting as a transparent, immutable ledger for recording transactions and data. Smart contracts—self-executing agreements with the terms directly written into code—automate processes and remove the need for centralized intermediaries.
|
| 134 |
+
2.3 Cryptocurrencies and Tokens
|
| 135 |
+
Digital currencies like Bitcoin and Ethereum facilitate peer-to-peer transactions without banks. Tokens can represent ownership, voting rights, or access to certain services in decentralized ecosystems, empowering users to participate directly in governance and development.
|
| 136 |
+
2.4 Self-Sovereign Identity
|
| 137 |
+
In Web3, individuals manage their own identities through cryptographic keys, eliminating the need to rely on third-party services like Google or Facebook for authentication. This gives users enhanced privacy and security over their personal information.
|
| 138 |
+
|
| 139 |
+
Conclusion
|
| 140 |
+
Web3 is more than just a technological upgrade; it is a philosophical shift toward a more open, equitable, and user-controlled internet. While it promises enhanced privacy, empowerment, and innovation, it also faces significant challenges related to scalability, regulation, usability, and environmental sustainability. As developers, policymakers, and users navigate this new landscape, the choices they make will determine whether Web3 fulfills its revolutionary potential or becomes another iteration of centralized control in disguise. Regardless of its ultimate form, Web3 represents a bold and necessary exploration into the next chapter of the digital age—a chapter where ownership, freedom, and community could finally take center stage.
|
| 141 |
+
|
| 142 |
+
9
|
| 143 |
+
|
| 144 |
+
The Internet: Transforming the Modern World
|
| 145 |
+
Introduction
|
| 146 |
+
The Internet is undoubtedly one of the most revolutionary inventions in human history. From its early beginnings as a military research project to its current status as a global communication and information network, the Internet has fundamentally transformed how people live, work, learn, and interact. Today, billions of people rely on it for communication, commerce, education, entertainment, and more. This essay explores the history, impact, uses, challenges, and future of the Internet in shaping our world.
|
| 147 |
+
|
| 148 |
+
1. Origins and Evolution of the Internet
|
| 149 |
+
The Internet’s story began in the late 1960s with ARPANET (Advanced Research Projects Agency Network), a U.S. government project that connected four computers across universities to share data. Its goal was to build a decentralized communication system that could withstand disruptions, particularly in times of war.
|
| 150 |
+
Throughout the 1970s and 1980s, ARPANET evolved, giving rise to protocols such as TCP/IP—the foundation of modern internet communication. By the early 1990s, the World Wide Web (WWW), developed by Tim Berners-Lee, brought a user-friendly interface to the Internet, making it accessible to the public. The creation of web browsers like Netscape and Internet Explorer accelerated the Internet's expansion into homes and businesses.
|
| 151 |
+
|
| 152 |
+
2. The Internet in Daily Life
|
| 153 |
+
2.1 Communication
|
| 154 |
+
Perhaps the most profound impact of the Internet has been in the realm of communication. Emails, instant messaging, and video calls have replaced traditional letters and landline phones. Platforms such as WhatsApp, Zoom, and social media networks have enabled people to connect in real-time across vast distances, fostering global relationships.
|
| 155 |
+
2.2 Education
|
| 156 |
+
The Internet has democratized learning. Online platforms like Coursera, Khan Academy, edX, and YouTube offer courses and tutorials on nearly every topic imaginable. During the COVID-19 pandemic, it played a critical role in enabling remote learning for millions of students worldwide.
|
| 157 |
+
2.3 Entertainment
|
| 158 |
+
Streaming services such as Netflix, Spotify, and YouTube have redefined entertainment. People no longer rely on physical media or scheduled television programming. Instead, content is available on-demand, personalized, and accessible from virtually any device.
|
| 159 |
+
2.4 Commerce and Business
|
| 160 |
+
The Internet has given rise to e-commerce—a booming industry where goods and services are bought and sold online. Platforms like Amazon, Alibaba, and Shopify allow even small businesses to reach global markets. Digital payment systems and online banking have streamlined financial transactions, making commerce faster and more convenient.
|
| 161 |
+
|
| 162 |
+
3. Social and Cultural Impact
|
| 163 |
+
3.1 Social Media and Connectivity
|
| 164 |
+
Social media has revolutionized how individuals share experiences and ideas. Platforms like Facebook, Instagram, Twitter, and TikTok have become central to cultural exchange and news dissemination. They empower users to voice opinions, organize movements, and influence change.
|
| 165 |
+
3.2 Cultural Exchange
|
| 166 |
+
Through the Internet, people are exposed to diverse cultures, languages, and lifestyles. It fosters understanding and tolerance by allowing individuals to experience content from different parts of the world, often in real time.
|
| 167 |
+
3.3 News and Information Access
|
| 168 |
+
Traditional newspapers and television are now complemented—and often replaced—by online news outlets, blogs, and citizen journalism. While this increases access to information, it also raises concerns about misinformation and media bias.
|
| 169 |
+
|
| 170 |
+
Conclusion
|
| 171 |
+
The Internet is far more than a tool—it is the backbone of modern civilization. It has redefined how people interact, learn, work, shop, and express themselves. While it brings immense benefits, it also introduces serious challenges that society must confront with thoughtful policies and responsible usage.
|
| 172 |
+
As we move into an increasingly digital future, the focus must be on making the Internet safe, inclusive, and equitable. With innovation and ethical stewardship, the Internet will continue to be a force for connection, empowerment, and transformation in the decades to come.
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
10
|
| 178 |
+
|
| 179 |
+
The Impact of Technology on Human Relationships
|
| 180 |
+
In the 21st century, technology has transformed nearly every aspect of our lives. From the way we work to how we communicate, technological advancements have reshaped our society. While technology has undoubtedly brought many benefits, one of the most significant changes it has brought about is its impact on human relationships. In some ways, technology has enhanced our connections, but in others, it has introduced new challenges that affect the depth and quality of our relationships.
|
| 181 |
+
One of the most positive contributions of technology is its ability to bring people together, regardless of distance. With the advent of video calling apps like Zoom, Skype, and FaceTime, people can now interact with loved ones across the globe in real-time. This has been especially important during the COVID-19 pandemic, when many families and friends were forced to stay apart. Technology has made it possible to maintain long-distance relationships, stay connected with family members, and even meet new people from different cultures and backgrounds. Social media platforms like Facebook, Instagram, and Twitter also allow individuals to share experiences and stay updated on each other’s lives.
|
| 182 |
+
However, despite these advancements, technology has also introduced challenges that can weaken personal connections. One of the most significant drawbacks is the rise of superficial relationships. With the constant stream of online communication, it’s easy to substitute face-to-face interactions with texting or commenting on social media posts. While this form of communication is convenient, it often lacks the emotional depth and intimacy of in-person conversations. People may feel more connected to others through digital platforms, but in reality, they might experience a sense of isolation or loneliness. The ability to share a photo or status update does not equate to the kind of meaningful interaction that occurs when people engage with each other in person.
|
| 183 |
+
Furthermore, technology can lead to a sense of distraction. With the constant barrage of notifications from our smartphones, many people find it difficult to be present in the moment. This has led to the phenomenon of “phubbing”, where individuals prioritize their phones over the people they are physically with. As a result, people often feel undervalued or ignored in social settings, leading to a breakdown in communication and connection.
|
| 184 |
+
In conclusion, while technology has the potential to strengthen human relationships by making communication more accessible, it also brings challenges that can undermine the quality of these connections. The key to maintaining meaningful relationships in the digital age lies in finding a balance between online and offline interactions. By using technology to enhance our relationships rather than replace them, we can ensure that our connections remain genuine and fulfilling.
|