# Humanization Engine — Build Progress & Context > **For new conversations:** Read this file + `PROJECT_INSTRUCTIONS.md` before doing anything. > The project root is `d:\Workspace\humanization-engine\`. > Global Python 3.13 is used — NO venv, packages installed system-wide. --- ## What This Project Is A production-ready web app that rewrites AI-generated text to bypass AI detectors (primarily Originality.ai). Architecture: **Analysis-Guided LLM Rewrite** (3-stage pipeline). NOT a wrapper around any third-party humanizer. --- ## Architecture: 3-Stage Pipeline ``` Input AI Text │ ▼ STAGE 1: ANALYSIS ENGINE ← Local, <300ms, NO API cost, does NOT modify text - Analyzes text using 7 sub-analyzers + Qwen2.5-0.5B - Produces structured JSON instruction set (AnalysisResult) │ ▼ STAGE 2: GUIDED LLM REWRITE ← Single API call (Claude Sonnet primary, GPT-4o-mini fallback) - Receives ORIGINAL text (unchanged) + Stage 1 instruction set - LLM changes ONLY what is flagged, keeps everything else as-is │ ▼ STAGE 3: POST-VALIDATION ← Local, <200ms, NO API cost - Checks length, auto-fixes banned words, grammar check - Returns output + full stats │ ▼ Output Text ``` **Critical rule:** Stage 1 NEVER modifies the text. Stage 2 always gets the original text. --- ## Environment | Item | Value | |------|-------| | Python | 3.13.7 (global, no venv) | | Python path | `C:\Users\User\AppData\Local\Programs\Python\Python313\python.exe` | | torch | 2.10.0+cpu | | transformers | 5.2.0 | | spaCy | 3.8.11 + `en_core_web_sm` model installed | | pydantic | 2.12.5 | | pydantic-settings | 2.13.0 | | accelerate | 1.12.0 | | Qwen2.5-0.5B cache | `C:\Users\User\.cache\huggingface\hub\models--Qwen--Qwen2.5-0.5B` | **Packages NOT yet installed (needed for later steps):** - `fastapi`, `uvicorn`, `httpx` — needed for Step 8 (API layer) - `language-tool-python` — needed for Step 6 (grammar checking in Stage 3) --- ## .env Configuration Located at `d:\Workspace\humanization-engine\.env`: ``` ANTHROPIC_API_KEY=sk-ant-your-key-here ← placeholder, needs real key OPENAI_API_KEY=sk-proj-5oQdbwo... ← real key already set PRIMARY_LLM=openai ← using GPT-4o-mini as primary MAX_INPUT_WORDS=5000 MIN_INPUT_WORDS=50 MAX_EXPANSION_PERCENT=40 LLM_TIMEOUT_SECONDS=8 WORKERS=1 PORT=8000 LOG_LEVEL=INFO ``` --- ## Complete File Tree (what exists right now) ``` humanization-engine/ ├── app/ │ ├── __init__.py │ ├── main.py ✅ FastAPI app + lifespan (loads spaCy + Qwen2.5) │ ├── config.py ✅ All settings via pydantic-settings │ ├── api/ │ │ ├── __init__.py │ │ ├── models.py ✅ Pydantic request/response models │ │ └── routes.py ✅ SKELETON ONLY — routes to be added in Step 8 │ ├── core/ │ │ ├── __init__.py │ │ ├── analyzer.py ✅ TextAnalyzer — main Stage 1 orchestrator │ │ ├── perplexity_scorer.py ✅ Qwen2.5-0.5B wrapper — HAS KNOWN BUG (see below) │ │ ├── analyzers/ │ │ │ ├── __init__.py │ │ │ ├── perplexity.py ✅ PerplexityAnalyzer (heuristic pre-filter + Qwen2.5) │ │ │ ├── burstiness.py ✅ BurstinessAnalyzer (sentence-length CV) │ │ │ ├── vocabulary.py ✅ VocabularyAnalyzer (loads ai_vocabulary.json) │ │ │ ├── transitions.py ✅ TransitionAnalyzer (loads transition_words.json) │ │ │ ├── openings.py ✅ OpeningPatternAnalyzer │ │ │ ├── structure.py ✅ StructuralAnalyzer (paragraph-level) │ │ │ └── informality.py ✅ InformalityAnalyzer (contractions + hedging) │ │ ├── pipeline.py ❌ NOT BUILT (Step 7) │ │ ├── llm_rewriter.py ❌ NOT BUILT (Step 5) │ │ ├── prompt_manager.py ❌ NOT BUILT (Step 5) │ │ └── post_validator.py ❌ NOT BUILT (Step 6) │ ├── prompts/ │ │ ├── __init__.py │ │ └── variants.py ❌ NOT BUILT (Step 5) │ ├── data/ │ │ ├── ai_vocabulary.json ✅ 149 words + 72 phrases with severity + suggestions │ │ ├── transition_words.json ✅ 128 entries (starters, connectors, formulaic openers) │ │ └── heuristic_patterns.json ✅ 79 starters, 113 vocab triggers, 66 phrase patterns │ └── utils/ │ ├── __init__.py │ ├── text_utils.py ✅ count_words, split_sentences, calculate_burstiness, etc. │ └── token_utils.py ✅ count_tokens, calculate_max_tokens ├── frontend/ │ └── .gitkeep ❌ NOT BUILT (Step 9) ├── tests/ │ ├── __init__.py │ └── test_analyzers/ │ └── __init__.py ❌ Test files NOT BUILT (Step 11) ├── verify_stage1.py ✅ Test script for Stage 1 (no Qwen2.5 needed) ├── test_ppl.py ✅ Test script for perplexity scorer timing ├── PROJECT_INSTRUCTIONS.md ✅ Full project spec ├── PROGRESS.md ✅ This file ├── requirements.txt ✅ ├── .env ✅ (has real OpenAI key) ├── .env.example ✅ ├── Dockerfile ❌ NOT BUILT (Step 10) └── docker-compose.yml ❌ NOT BUILT (Step 10) ``` --- ## ✅ COMPLETED STEPS ### Step 1: Project Setup — DONE All package directories, `__init__.py` files, `config.py`, `models.py`, `main.py`, `requirements.txt`, `.env.example`. ### Step 2: Utility Functions — DONE `text_utils.py`, `token_utils.py`, `perplexity_scorer.py` (has known bug — see below). ### Steps 3 & 4: Stage 1 Analyzers + Data Files — DONE All 7 sub-analyzers + `analyzer.py` orchestrator + all 3 data JSON files. --- ## 🔴 MUST FIX BEFORE CONTINUING — perplexity_scorer.py bug **File:** `app/core/perplexity_scorer.py` **Problem 1 — Span detection is catastrophically slow:** The `score_sentence()` method calls `_find_low_perplexity_spans()` by default. That method runs a sliding-window with ~16 forward passes per sentence → adds 750–1100ms per sentence. Single forward pass (what we actually need) = 100–120ms. Spans = 10× slower, not needed for Stage 2. **Fix:** In `score_sentence()` around line 114, change: ```python # CURRENT (broken - always runs spans): def score_sentence(self, sentence: str, sentence_index: int = 0) -> SentencePerplexityResult: mean_ppl = self._compute_mean_perplexity(sentence) classification = self._classify(mean_ppl) low_spans = self._find_low_perplexity_spans(sentence) # ← DELETE/DISABLE THIS # FIXED (spans off by default): def score_sentence(self, sentence: str, sentence_index: int = 0, compute_spans: bool = False) -> SentencePerplexityResult: mean_ppl = self._compute_mean_perplexity(sentence) classification = self._classify(mean_ppl) low_spans = self._find_low_perplexity_spans(sentence) if compute_spans else [] ``` **Problem 2 — Deprecated argument (transformers 5.x warning):** ```python # CURRENT: self.model = AutoModelForCausalLM.from_pretrained( model_id, torch_dtype=torch.float32, # ← deprecated in transformers 5.x device_map="cpu", ) # FIXED: self.model = AutoModelForCausalLM.from_pretrained( model_id, dtype=torch.float32, # ← correct for transformers 5.x device_map="cpu", ) ``` **After fix:** ~100–120ms per sentence. For 1K words (~15 sentences), pre-filter passes ~8 sentences → ~850ms total perplexity scoring time. --- ## Stage 1 Verification Results (already tested) Run `python verify_stage1.py` from project root to verify Stage 1 (no Qwen2.5 needed). | Sample | Words | Sentences | Time | Banned Words | Instructions | Burstiness CV | |--------|-------|-----------|------|-------------|--------------|--------------| | Healthcare | 63 | 4 | 24ms | 14 | 17 | 0.290 (high_uniformity) | | Climate | 69 | 4 | 17ms | 3 | 7 | 0.219 (high_uniformity) | | Education | 63 | 4 | 16ms | 7 | 10 | 0.159 (high_uniformity) | All targets met. Transitions correctly flagged (Furthermore, Consequently, Moreover, However). Target is <300ms — we're 10–15× faster even without optimization. **Note:** `overall_risk` shows "low" when `perplexity_scorer=None` because sentence risk classification is all `low_risk` without Qwen2.5. This is expected and correct — fix the scorer bug then test with Qwen2.5 to get accurate risk levels. --- ## ❌ REMAINING STEPS (pick up from here) ### Step 5: Stage 2 — Guided LLM Rewriter ← NEXT TO BUILD Three files to create: **`app/prompts/variants.py`** - 8–10 system prompt variants (different role framing, emphasis, tone guidance) - Core rules identical across all variants (follow instructions, don't exceed 135% length, no banned words) - Variants differ in: role ("student revising draft" vs "confident undergrad"), tone guidance, micro-instructions **`app/core/prompt_manager.py`** - `PromptManager` class - Stores all variants, rotates randomly, never uses same variant twice in a row - `format_analysis_for_llm(analysis_result, original_text)` → converts JSON instructions to human-readable text block for the prompt - Logs which variant was used per request **`app/core/llm_rewriter.py`** - `LLMRewriter` class (async) - `async def rewrite(text, analysis_result, mode) -> RewriteResult` - Primary: `claude-sonnet-4-20250514` via Anthropic API (httpx) - Fallback: `gpt-4o-mini` via OpenAI API (httpx) - Dynamic `max_tokens` = `input_word_count * 1.4 * 1.5` - Hard 8-second timeout - If both fail → return original text with error flag ### Step 6: Stage 3 — Post Validator **`app/core/post_validator.py`** - `PostValidator` class - Length check: if output > 140% of input → trim elaborations - Banned word check: if any banned words remain → regex-replace with first suggestion from vocab DB - Grammar check: `language_tool_python` (needs `pip install language-tool-python`) - NER preservation: compare named entities in input vs output using spaCy - Optional perplexity re-scoring (thorough mode only): re-score output with Qwen2.5, compare to input - Returns full `stats` dict (word counts, perplexity before/after, banned words fixed, timing, etc.) ### Step 7: Pipeline Orchestrator **`app/core/pipeline.py`** - `HumanizationPipeline` class - `async def run(text, mode) -> PipelineResult` - Wires Stage 1 → Stage 2 → Stage 3 - Times each stage - Error handling: Stage 1 fail → generic prompt; Stage 2 primary fail → fallback LLM; Stage 2 both fail → return original - Accepts `nlp`, `perplexity_scorer`, `vocab_analyzer`, `language_tool` injected at init (shared from app startup) ### Step 8: API Layer **`app/api/routes.py`** (replace the skeleton) - `POST /humanize` — main endpoint, calls pipeline - `POST /analyze` — debug endpoint, returns Stage 1 only (no LLM call) - `GET /health` — returns status + uptime + `models_loaded` - CORS already configured in `main.py` - Add simple in-memory rate limiting (e.g. 20 req/min per IP) - Input validation: word count between `MIN_INPUT_WORDS` and `MAX_INPUT_WORDS` Also update `app/main.py` to: - Create `TextAnalyzer` and `HumanizationPipeline` in lifespan and store on `app.state` - Pass shared models (nlp, scorer, vocab) to both ### Step 9: Frontend **`frontend/index.html`** — Single file, plain HTML + CSS + JS, no framework - Dark theme - Left/top: text input with word counter - Right/bottom: output with copy button - "Humanize" button + Standard/Thorough mode toggle - Loading spinner during processing - Stats panel after processing: word counts, expansion %, perplexity before/after, CV before/after, instructions generated, timing breakdown, LLM used, banned words auto-fixed - "Show Analysis" toggle → shows raw Stage 1 JSON - Serve from FastAPI as static files ### Step 10: Docker **`Dockerfile`** ```dockerfile FROM python:3.11-slim RUN apt-get update && apt-get install -y build-essential WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt RUN python -c "from transformers import AutoModelForCausalLM, AutoTokenizer; AutoModelForCausalLM.from_pretrained('Qwen/Qwen2.5-0.5B'); AutoTokenizer.from_pretrained('Qwen/Qwen2.5-0.5B')" RUN python -m spacy download en_core_web_sm COPY . . CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"] ``` **`docker-compose.yml`** — mounts `.env`, exposes port 8000 ### Step 11: Testing & Tuning Test files in `tests/`: - `test_analyzer.py` — full TextAnalyzer with sample inputs - `test_analyzers/test_burstiness.py`, `test_vocabulary.py`, `test_transitions.py`, `test_openings.py`, `test_structure.py`, `test_informality.py`, `test_perplexity.py` - `test_llm_rewriter.py` — mock LLM responses - `test_post_validator.py` - `test_pipeline.py` — end-to-end with mocked LLM - `test_api.py` — FastAPI test client --- ## How to Run / Test ### Test Stage 1 (no Qwen2.5, fast) ```bash cd d:\Workspace\humanization-engine python verify_stage1.py ``` ### Test perplexity scorer (Qwen2.5) ```bash cd d:\Workspace\humanization-engine python test_ppl.py ``` Note: apply the two fixes in `perplexity_scorer.py` first (span detection + dtype arg). ### Run the full app (once Steps 5–8 are done) ```bash cd d:\Workspace\humanization-engine uvicorn app.main:app --port 8000 --reload ``` --- ## Key Design Decisions to Preserve 1. **`TextAnalyzer` is stateless per-call** — injected with shared `nlp` and `perplexity_scorer` at init, safe for async reuse. 2. **All data files resolve paths relative to `__file__`** so they work regardless of working directory. 3. **Pre-filter before Qwen2.5** — always run heuristic_prefilter first, only score flagged sentences. 4. **Stage 2 prompt must include** both the human-readable instructions block AND the banned_words list AND the original text — in that exact order. 5. **`max_tokens` is dynamic** — calculated as `input_word_count * 1.4 * 1.5`, never hardcoded. 6. **Stage 3 is non-blocking** — if it fails, return Stage 2 output with an error flag. Never crash the request. 7. **LLM model IDs**: primary = `claude-sonnet-4-20250514`, fallback = `gpt-4o-mini`.