# HUMANIZATION ENGINE — Full Project Context & Build Instructions ## Architecture C: Analysis-Guided LLM Rewrite ## ROLE You are building a production-ready web application called the **Humanization Engine**. You are the sole developer. Read this entire document carefully before writing any code. Ask clarifying questions if anything is ambiguous. Do not skip steps or take shortcuts. --- ## PROJECT GOAL Build a web-based system that takes AI-generated text as input and automatically rewrites it so that it **bypasses AI detection tools** (primarily Originality.ai) while maintaining high quality. This is NOT a wrapper around any third-party humanizer API. This is our own architecture. --- ## SUCCESS CRITERIA The output text must: - Be flagged as **"Human"** by Originality.ai in most cases (target >85% pass rate) - Maintain high academic quality suitable for university students - Have strong grammar and natural readability - Stay within **30–40% length increase** of the original (NEVER 2x longer) - Be confirmed as well-written by any major LLM (GPT, Claude, Gemini) - Process 1,000 words in **under 10 seconds** - Support approximately **500 users per 30 minutes** (~17 concurrent requests/min) --- ## CRITICAL ARCHITECTURAL INSIGHT — READ THIS FIRST AI detectors like Originality.ai work by analyzing **token-level probability distributions**. They check whether a language model would have predicted the tokens in the text with high confidence. If yes → flagged as AI. The fundamental problem with most humanizers is: ``` AI text → LLM rewrites it → Output is STILL LLM-generated → Still gets detected ``` An LLM rewriting AI text produces NEW LLM-generated tokens. Those tokens carry the LLM's statistical fingerprint. You're using an LLM to try to not sound like an LLM — it doesn't work well. **Our solution: Architecture C — Analysis-Guided Rewrite** Instead of transforming text in a preprocessing step (which the LLM would then overwrite), we use local analysis to BUILD A DETAILED INSTRUCTION SET that tells the LLM EXACTLY what to change and what to leave alone. This way: 1. The LLM makes **targeted changes** (only to flagged portions), not a full rewrite 2. Untouched portions retain original structure — no new LLM fingerprint on those parts 3. Stage 1's analysis **directly controls** the output rather than being overwritten 4. Fewer total tokens are LLM-generated = weaker AI signal overall --- ## CORE ARCHITECTURE — 3-Stage Pipeline ``` Input AI Text │ ▼ ┌──────────────────────────────────────────────────┐ │ STAGE 1: ANALYSIS ENGINE │ │ (Analyzes text, generates specific instructions)│ │ Local, <300ms, no API cost │ │ This stage does NOT modify the text. │ │ It produces a structured instruction set. │ └──────────────────┬───────────────────────────────┘ │ ├── Original text (unchanged) ├── Structured instruction set (JSON) │ ▼ ┌──────────────────────────────────────────────────┐ │ STAGE 2: GUIDED LLM REWRITE │ │ (Receives original text + instructions) │ │ Single API call, ~3-6 seconds │ │ LLM follows the instructions precisely, │ │ changing ONLY what is flagged. │ └──────────────────┬───────────────────────────────┘ │ ▼ ┌──────────────────────────────────────────────────┐ │ STAGE 3: POST-VALIDATION & MICRO-CORRECTIONS │ │ Local, <200ms, no API cost │ │ Verifies quality, length, and that the LLM │ │ actually followed the instructions. │ └──────────────────┬───────────────────────────────┘ │ ▼ Output Text ``` --- ## STAGE 1: ANALYSIS ENGINE (CRITICAL — 60% of success depends on this) ### PURPOSE Analyze the input AI text and generate a **structured instruction set** (JSON) that tells the LLM exactly what to change, why, and how. This stage does NOT modify the text itself. ### WHAT TO BUILD Create a Python class `TextAnalyzer` with the following analysis sub-components: #### 1a. Perplexity Analysis (Qwen2.5-0.5B) - Load **Qwen2.5-0.5B** (`Qwen/Qwen2.5-0.5B`) at application startup - Use `torch_dtype=torch.float32` for CPU deployment - Use `device_map="cpu"` explicitly - Wrap all inference in `@torch.no_grad()` to save memory - RAM usage: ~1.1GB - **Speed optimization — sentence-level filtering:** 1. First run a fast heuristic pre-filter (<10ms) to flag sentences that LOOK AI-like: - Starts with common transition words (Furthermore, Moreover, Additionally, Consequently, etc.) - Length is within ±3 words of the average sentence length (too uniform) - Contains 2+ words from a known AI-vocabulary list - Contains common AI phrase patterns ("it is important to note", "plays a crucial role", etc.) 2. Only send the flagged sentences (~50-60% of total) through Qwen2.5 for actual perplexity scoring 3. This brings scoring time from ~400-700ms down to ~200-350ms for 1K words - For each scored sentence, output: ```json { "sentence_index": 2, "sentence_text": "Through the implementation of sophisticated...", "mean_perplexity": 22.4, "classification": "high_risk", // "high_risk" | "medium_risk" | "low_risk" "low_perplexity_spans": [ {"tokens": "implementation of sophisticated", "perplexity": 8.3} ] } ``` - Classification thresholds (tune these based on testing): - `high_risk`: mean perplexity < 30 (very predictable — needs major restructuring) - `medium_risk`: mean perplexity 30-60 (somewhat predictable — needs targeted changes) - `low_risk`: mean perplexity > 60 (already human-like — minimal or no changes) #### 1b. Burstiness Analysis - Parse text using **spaCy** (`en_core_web_sm`) - Calculate sentence lengths (word counts) for every sentence - Calculate: - Mean sentence length - Standard deviation of sentence lengths - Coefficient of variation (CV = std/mean) - Min and max sentence length - Flag uniformity problems: - If CV < 0.3 → "high_uniformity" (AI text typically has CV 0.15-0.30) - If CV 0.3-0.45 → "moderate_uniformity" - If CV > 0.45 → "acceptable" (human text typically has CV 0.4-0.6+) - For uniform text, generate specific instructions: ```json { "type": "burstiness", "severity": "high_uniformity", "current_cv": 0.22, "target_cv": "0.45-0.60", "instructions": [ {"sentence_index": 3, "action": "shorten", "detail": "Make this much shorter (8-10 words). Currently 19 words, similar to adjacent sentences."}, {"sentence_index": 5, "action": "lengthen", "detail": "Expand this slightly or merge with sentence 6 to create one longer complex sentence."}, {"sentence_index": 7, "action": "split", "detail": "Split into two sentences at the clause boundary after 'however'."} ] } ``` #### 1c. Vocabulary Analysis - Build and load a comprehensive **AI-vocabulary database** (JSON file) containing 80-100+ words/phrases that AI text overuses. Organized as: ```json { "single_words": { "furthermore": {"severity": "high", "suggestions": ["Beyond this", "What's more", "On top of that", "Adding to this", "[remove transition entirely]"]}, "moreover": {"severity": "high", "suggestions": ["Also worth noting", "In addition", "Alongside this", "[remove transition entirely]"]}, "additionally": {"severity": "high", "suggestions": ["Another point is", "It's also true that", "Equally", "[restructure without transition]"]}, "consequently": {"severity": "high", "suggestions": ["As a result", "This means", "Because of this", "[restructure as cause-effect]"]}, "significantly": {"severity": "medium", "suggestions": ["Notably", "To a large degree", "In meaningful ways", "Quite a bit"]}, "demonstrates": {"severity": "medium", "suggestions": ["Shows", "Points to", "Makes clear", "Highlights"]}, "utilize": {"severity": "high", "suggestions": ["Use", "Make use of", "Draw on", "Rely on"]}, "implement": {"severity": "medium", "suggestions": ["Put in place", "Roll out", "Carry out", "Set up"]}, "comprehensive": {"severity": "medium", "suggestions": ["Thorough", "Wide-ranging", "In-depth", "Detailed"]}, "facilitate": {"severity": "high", "suggestions": ["Help", "Support", "Make possible", "Enable"]}, "leverage": {"severity": "high", "suggestions": ["Use", "Take advantage of", "Build on", "Tap into"]}, "robust": {"severity": "high", "suggestions": ["Strong", "Solid", "Reliable", "Sturdy"]}, "paradigm": {"severity": "high", "suggestions": ["Model", "Framework", "Approach", "Way of thinking"]}, "unprecedented": {"severity": "high", "suggestions": ["Never seen before", "Rare", "Unusual", "Exceptional"]}, "transformative": {"severity": "high", "suggestions": ["Game-changing", "Major", "Powerful", "Meaningful"]}, "optimize": {"severity": "medium", "suggestions": ["Improve", "Fine-tune", "Make better", "Refine"]}, "streamline": {"severity": "high", "suggestions": ["Simplify", "Speed up", "Clean up", "Make easier"]}, "innovative": {"severity": "medium", "suggestions": ["Creative", "New", "Fresh", "Original"]}, "crucial": {"severity": "medium", "suggestions": ["Key", "Central", "Vital", "Essential"]}, "delve": {"severity": "high", "suggestions": ["Explore", "Look into", "Dig into", "Examine"]}, "multifaceted": {"severity": "high", "suggestions": ["Complex", "Layered", "Varied", "Many-sided"]}, "underscore": {"severity": "medium", "suggestions": ["Highlight", "Stress", "Emphasize", "Point out"]}, "overarching": {"severity": "high", "suggestions": ["Main", "Broad", "Central", "Guiding"]}, "spearheaded": {"severity": "high", "suggestions": ["Led", "Drove", "Pushed forward", "Championed"]}, "encompass": {"severity": "medium", "suggestions": ["Include", "Cover", "Take in", "Span"]}, "pivotal": {"severity": "high", "suggestions": ["Key", "Important", "Critical", "Central"]}, "landscape": {"severity": "high", "suggestions": ["Field", "Area", "Scene", "World"]}, "realm": {"severity": "high", "suggestions": ["Area", "Field", "Domain", "World"]}, "embark": {"severity": "high", "suggestions": ["Start", "Begin", "Set out on", "Take on"]}, "foster": {"severity": "medium", "suggestions": ["Encourage", "Support", "Build", "Grow"]}, "navigate": {"severity": "medium", "suggestions": ["Work through", "Handle", "Deal with", "Manage"]}, "tapestry": {"severity": "high", "suggestions": ["Mix", "Blend", "Collection", "Web"]}, "testament": {"severity": "high", "suggestions": ["Proof", "Evidence", "Sign", "Example"]}, "endeavor": {"severity": "high", "suggestions": ["Effort", "Attempt", "Project", "Work"]}, "commendable": {"severity": "medium", "suggestions": ["Impressive", "Worthy", "Praiseworthy", "Admirable"]}, "intricate": {"severity": "medium", "suggestions": ["Complex", "Detailed", "Complicated", "Involved"]}, "noteworthy": {"severity": "medium", "suggestions": ["Worth noting", "Important", "Interesting", "Significant"]}, "myriad": {"severity": "high", "suggestions": ["Many", "Countless", "A wide range of", "Numerous"]}, "aforementioned": {"severity": "high", "suggestions": ["These", "Those", "The ones mentioned", "[use specific reference]"]}, "paramount": {"severity": "high", "suggestions": ["Critical", "Most important", "Top priority", "Essential"]}, "adept": {"severity": "medium", "suggestions": ["Skilled", "Good at", "Capable", "Proficient"]}, "burgeoning": {"severity": "high", "suggestions": ["Growing", "Expanding", "Rising", "Booming"]} }, "phrases": { "it is important to note": {"severity": "high", "suggestions": ["Worth highlighting", "A key detail here", "One thing that stands out"]}, "in today's world": {"severity": "high", "suggestions": ["These days", "Right now", "Currently", "[remove entirely]"]}, "in the realm of": {"severity": "high", "suggestions": ["In", "Within", "When it comes to", "[simplify]"]}, "plays a crucial role": {"severity": "high", "suggestions": ["Matters a lot", "Is central to", "Is key in", "Drives"]}, "it is worth noting": {"severity": "high", "suggestions": ["Notably", "Interestingly", "One thing to keep in mind"]}, "a wide range of": {"severity": "medium", "suggestions": ["Many", "Various", "Different kinds of", "All sorts of"]}, "in order to": {"severity": "medium", "suggestions": ["To", "So that", "For", "[simplify]"]}, "due to the fact that": {"severity": "high", "suggestions": ["Because", "Since", "As", "Given that"]}, "at the end of the day": {"severity": "high", "suggestions": ["Ultimately", "In the end", "When it comes down to it"]}, "on the other hand": {"severity": "medium", "suggestions": ["Then again", "But", "That said", "At the same time"]}, "in light of": {"severity": "medium", "suggestions": ["Given", "Considering", "Because of", "With"]}, "it goes without saying": {"severity": "high", "suggestions": ["Obviously", "Clearly", "Of course", "[remove entirely]"]}, "serves as a": {"severity": "medium", "suggestions": ["Acts as", "Works as", "Functions as", "Is"]}, "in conclusion": {"severity": "high", "suggestions": ["To sum up", "Taken together", "All things considered", "Looking at the bigger picture"]}, "as a result": {"severity": "medium", "suggestions": ["So", "This means", "Because of this", "That's why"]}, "in addition to": {"severity": "medium", "suggestions": ["Besides", "Along with", "On top of", "Apart from"]}, "has the potential to": {"severity": "medium", "suggestions": ["Could", "Might", "Can", "Is able to"]}, "there is no doubt that": {"severity": "high", "suggestions": ["Clearly", "Without question", "It's clear that", "[state directly]"]}, "this highlights the": {"severity": "medium", "suggestions": ["This shows", "This points to", "This makes clear"]}, "the fact that": {"severity": "medium", "suggestions": ["That", "[remove — often unnecessary]", "How"]}, "in terms of": {"severity": "medium", "suggestions": ["For", "Regarding", "When it comes to", "With"]}, "lends credence to": {"severity": "high", "suggestions": ["Supports", "Backs up", "Strengthens", "Adds weight to"]}, "is imperative that": {"severity": "high", "suggestions": ["We must", "It's critical to", "We need to", "Has to"]} } } ``` IMPORTANT: The above is a STARTING POINT. Build this out to at least **80-100 entries across single_words and phrases combined**. Include more entries beyond what's listed here. Cover common academic AI vocabulary thoroughly. - Scan the input text for all matches - For each match, output: ```json { "type": "vocabulary", "word_or_phrase": "furthermore", "sentence_index": 2, "position_in_sentence": "start", "severity": "high", "suggestions": ["Beyond this", "What's more", "[remove transition]"] } ``` #### 1d. Transition Pattern Analysis - Detect how each sentence/paragraph begins - Flag problematic patterns: - Sentence starts with a common transition word (Furthermore, Moreover, Additionally, However, Consequently, Nevertheless, etc.) - Multiple consecutive sentences start the same way (e.g., "The... The... The...") - Paragraph openings follow a predictable pattern - For each flag, generate: ```json { "type": "transition", "sentence_index": 0, "current_opening": "Furthermore,", "instruction": "Remove this transition entirely and restructure the sentence to flow from the previous one. Or replace with a less formulaic connector." } ``` #### 1e. Sentence Opening Pattern Analysis - Track the first 1-3 words of every sentence - Detect repetitive patterns: - 3+ sentences starting with "The" - 2+ sentences starting with the same word within a paragraph - Overly formulaic openings ("This is", "It is", "There are") - For each pattern, generate: ```json { "type": "sentence_opening", "affected_sentences": [2, 4, 6], "pattern": "All start with 'The'", "instruction": "Vary the openings. Consider starting sentence 4 with an adverbial phrase, and sentence 6 with the object or a dependent clause." } ``` #### 1f. Structural Analysis - Count sentences per paragraph - Check if paragraphs are too uniform in length - Check if the overall argument follows an overly predictable structure (claim → evidence → conclusion repeating) - Generate structural suggestions: ```json { "type": "structural", "instruction": "Paragraphs 2 and 3 are both exactly 4 sentences. Consider merging the last sentence of paragraph 2 into paragraph 3, or splitting paragraph 3 after sentence 2." } ``` #### 1g. Informality Injection Points - Identify places where a human student would naturally use: - Contractions ("don't" vs "do not", "it's" vs "it is") - First person ("I would argue", "In my reading of this") - Hedging language ("arguably", "to some extent", "it seems") - Slightly casual phrasing - Target ~10-15% of opportunities for contraction injection - Generate: ```json { "type": "informality", "sentence_index": 4, "instruction": "Change 'do not' to 'don't' — natural contraction point.", } ``` ```json { "type": "informality", "sentence_index": 7, "instruction": "This is a good place to add a brief personal hedge like 'I would argue that' or 'In my view' at the start." } ``` ### COMBINED OUTPUT FORMAT Stage 1 must produce a single JSON object called `AnalysisResult`: ```json { "summary": { "total_sentences": 12, "high_risk_sentences": 4, "medium_risk_sentences": 5, "low_risk_sentences": 3, "burstiness_cv": 0.22, "burstiness_rating": "high_uniformity", "ai_vocabulary_count": 8, "transition_flags": 3, "opening_pattern_flags": 2, "overall_risk": "high" // "high" | "medium" | "low" }, "instructions": [ // ALL instructions from all sub-analyzers, sorted by sentence_index // Each instruction has: type, sentence_index, severity, instruction text { "type": "perplexity", "sentence_index": 0, "severity": "high", "instruction": "This sentence has very low perplexity (22.4). Restructure it significantly — change the sentence structure, not just individual words." }, { "type": "vocabulary", "sentence_index": 0, "severity": "high", "instruction": "Replace 'Furthermore' at the start. Use 'Beyond this', or remove the transition entirely." }, { "type": "burstiness", "sentence_index": 2, "severity": "medium", "instruction": "Shorten this sentence to 8-10 words. It's currently 19 words, same as adjacent sentences." }, // ... more instructions ], "banned_words": ["furthermore", "moreover", "utilize", "facilitate", ...], // List of all AI-vocabulary words found in the text that the LLM must avoid "sentence_perplexities": [ {"index": 0, "text": "Furthermore, artificial...", "mean_ppl": 22.4, "risk": "high"}, {"index": 1, "text": "The implementation...", "mean_ppl": 31.2, "risk": "medium"}, // ... ] } ``` ### IMPLEMENTATION REQUIREMENTS FOR STAGE 1 - Must complete in **under 300ms** for 1,000 words - Must use **NO API calls** — everything runs locally - Load spaCy and Qwen2.5 models at application startup (not per request) - The analysis must be **deterministic** for the same input (no randomness in analysis — randomness comes from prompt rotation in Stage 2) - Write comprehensive unit tests for each sub-analyzer - Every function must have docstrings and type hints --- ## STAGE 2: GUIDED LLM REWRITE ### PURPOSE Receive the original text AND Stage 1's structured instruction set, then perform a single guided rewrite that follows the instructions precisely. The LLM should change ONLY what the instructions specify and keep everything else as close to the original as possible. ### LLM SELECTION - Primary: **Anthropic Claude Sonnet** (`claude-sonnet-4-20250514`) - Fallback: **OpenAI GPT-4o-mini** (`gpt-4o-mini`) - Do NOT use reasoning models (o1, o3) — too slow, too expensive - Do NOT use small/cheap models (GPT-3.5) — quality too low ### PROMPT ENGINEERING Create a **prompt manager** class that: - Stores **at least 8-10 system prompt variants** — rotate randomly per request - Each variant instructs the same core behavior but with different phrasing and emphasis - NEVER use the same prompt for consecutive requests - Log which variant was used per request (for future optimization) ### SYSTEM PROMPT STRUCTURE Every prompt variant must follow this structure: ``` [ROLE DEFINITION] You are a university student revising your own essay draft. You write confidently and naturally. You're not rewriting someone else's work — this is YOUR essay and you're improving it based on feedback. [CORE RULES - these are NON-NEGOTIABLE in every variant] 1. Follow EVERY instruction in the ANALYSIS section below. These are specific changes you must make. 2. For sentences NOT mentioned in the instructions, keep them as close to the original wording as possible. Only make minimal changes for flow. 3. NEVER use any word from the BANNED WORDS list. 4. Preserve ALL factual content, arguments, and meaning exactly. 5. STRICT LENGTH: Output must be between 100% and 135% of the input word count. Input is approximately {word_count} words. Your output MUST be {word_count} to {max_words} words. Do NOT exceed {hard_max} words under any circumstances. 6. Do NOT add new examples, elaborations, or content not in the original. 7. Do NOT add meta-commentary ("In this essay", "As discussed above"). 8. Write naturally — use occasional contractions, vary your rhythm, be direct. [ANALYSIS - Stage 1's instruction set goes here] {analysis_json} [BANNED WORDS - never use these] {banned_words_list} [ORIGINAL TEXT TO REVISE] {original_text} [OUTPUT] Write ONLY the revised text. No explanations, no commentary, no preamble. ``` ### PROMPT VARIANT DIFFERENTIATION Each of the 8-10 variants should differ in: - **Role framing**: "university student revising your draft" vs "thoughtful student polishing your assignment" vs "confident undergrad cleaning up your paper" - **Emphasis priorities**: One variant emphasizes naturalness, another emphasizes directness, another emphasizes varying rhythm - **Tone guidance**: "Write like you're confident about your arguments" vs "Write like you genuinely care about this topic" vs "Write like you're explaining this to a smart friend" - **Specific micro-instructions**: "Occasionally start a sentence with 'But' or 'And'" vs "Feel free to use a rhetorical question once if it fits" vs "If you make a strong claim, follow it with a brief personal qualifier" The CORE RULES must be identical across all variants. Only the framing and emphasis differ. ### HOW TO FORMAT STAGE 1 INSTRUCTIONS FOR THE LLM Convert the Stage 1 JSON into human-readable instructions grouped by sentence: ``` ANALYSIS — Changes Required: SENTENCE 1: "Furthermore, artificial intelligence has demonstrated remarkable capabilities..." - ❌ Remove transition "Furthermore" — use a natural connector or remove entirely - ❌ "demonstrated" and "remarkable" and "capabilities" are flagged AI words — replace them - ⚠️ This sentence has very low perplexity (22.4) — restructure it significantly SENTENCE 2: "The implementation of sophisticated algorithms enables..." - ❌ "implementation", "sophisticated" are flagged AI words — use simpler alternatives - ⚠️ Moderate perplexity (31.2) — make some changes but doesn't need full restructuring SENTENCE 3: "Additionally, these systems facilitate proactive intervention strategies." - ❌ Remove transition "Additionally" - ❌ "facilitate" is a flagged AI word — replace it - 📏 SHORTEN this sentence to 8-10 words (currently 8 — similar to sentence 2, need variation) OVERALL: - 📏 Sentences are too uniform in length (CV: 0.22). Vary significantly. - Use contractions in sentences 2 and 5 where natural - Consider adding "I think" or "I would argue" before the claim in sentence 4 BANNED WORDS (never use these): furthermore, moreover, additionally, demonstrate, remarkable, sophisticated, facilitate, unprecedented, comprehensive, paradigm, ... ``` ### LLM CALL CONFIGURATION ```python # For Claude Sonnet { "model": "claude-sonnet-4-20250514", "max_tokens": calculated_dynamically, # input_word_count * 1.4 * 1.5 (tokens ratio + buffer) "temperature": 0.85, # Higher than default for variation "top_p": 0.9, } # For GPT-4o-mini (fallback) { "model": "gpt-4o-mini", "max_tokens": calculated_dynamically, "temperature": 0.85, "top_p": 0.9, } ``` ### CRITICAL CONSTRAINTS - **Only ONE LLM call per request.** No multi-pass. No chain-of-thought. No retry loops. - Dynamic `max_tokens`: `input_word_count * 1.4 * 1.5` (expansion allowance × token ratio) - If LLM call fails or times out, return original text with a warning (since Stage 1 doesn't modify text in Architecture C, there's no partially-humanized fallback) - If primary LLM fails, try fallback LLM before returning error --- ## STAGE 3: POST-VALIDATION & MICRO-CORRECTIONS ### PURPOSE Verify the output quality, check that the LLM followed instructions, and make final corrections. No API calls. ### WHAT TO BUILD #### 3a. Length Validation & Enforcement - Count output word count vs input word count - Calculate expansion percentage - If expansion exceeds 40%: - Identify and remove any elaborations or examples not in the original (compare against original sentences using basic similarity scoring) - Trim redundant phrases - If still too long, truncate from the end of the least essential paragraph - If output is shorter than 90% of input, flag as warning #### 3b. Instruction Compliance Check - Check if banned words appear in the output - If any banned words found, apply simple regex-based replacement using suggestions from the vocabulary database - This is a LOCAL fix — no API call needed - Log which banned words the LLM failed to avoid (useful for prompt tuning) - Check if flagged transitions were actually removed - These are lightweight string-matching checks #### 3c. Perplexity Re-scoring (Optional but Recommended) - Run the output through the same Qwen2.5 perplexity scorer from Stage 1 - Compare the perplexity distribution of input vs output - If output still has too many low-perplexity sentences, apply local synonym substitutions to the worst offenders: - Look up the lowest-perplexity tokens - Check if they have entries in the synonym bank - Replace with a random suggestion - This is a lightweight local fix, no API needed - This step is optional because it adds ~200ms. Can be skipped in "fast mode" or enabled in "thorough mode" #### 3d. Quality Checks - Run grammar check using `language_tool_python` - Fix any obvious grammar errors - Verify key named entities are preserved (compare NER between input and output using spaCy) - Verify no content was hallucinated (all proper nouns in output should exist in input) #### 3e. Final Statistics Return alongside the output: ```json { "output_text": "...", "stats": { "input_word_count": 1000, "output_word_count": 1250, "expansion_percentage": 25.0, "input_avg_perplexity": 28.5, "output_avg_perplexity": 52.3, "input_burstiness_cv": 0.22, "output_burstiness_cv": 0.48, "banned_words_found_in_output": ["demonstrate"], "banned_words_auto_fixed": 1, "instructions_generated": 14, "high_risk_sentences": 4, "processing_time_ms": 4500, "stage1_time_ms": 180, "stage2_time_ms": 4100, "stage3_time_ms": 150, "prompt_variant_used": "variant_3", "llm_used": "claude-sonnet" } } ``` --- ## BACKEND ARCHITECTURE ### Tech Stack - **Python 3.11+** - **FastAPI** (async) - **uvicorn** with workers (1-2 workers due to model memory) - **httpx** (async HTTP client for LLM API calls) - **spaCy** (`en_core_web_sm`) - **transformers** (Qwen2.5-0.5B for perplexity scoring — load once at startup, ~1.1GB RAM) - **language_tool_python** (grammar checking) - **Docker** for deployment ### Project Structure ``` humanization-engine/ ├── app/ │ ├── main.py # FastAPI app, lifespan events, CORS │ ├── config.py # All configuration, environment variables │ ├── api/ │ │ ├── routes.py # API endpoints │ │ └── models.py # Pydantic request/response models │ ├── core/ │ │ ├── pipeline.py # Main orchestrator (Stage 1 → 2 → 3) │ │ ├── analyzer.py # STAGE 1 — Main TextAnalyzer class │ │ ├── analyzers/ │ │ │ ├── perplexity.py # Qwen2.5 perplexity scoring + heuristic pre-filter │ │ │ ├── burstiness.py # Sentence length uniformity analysis │ │ │ ├── vocabulary.py # AI vocabulary detection │ │ │ ├── transitions.py # Transition pattern detection │ │ │ ├── openings.py # Sentence opening pattern detection │ │ │ ├── structure.py # Paragraph/structural analysis │ │ │ └── informality.py # Informality injection point detection │ │ ├── llm_rewriter.py # STAGE 2 — Guided LLM rewrite │ │ ├── prompt_manager.py # Prompt variant storage and rotation │ │ ├── post_validator.py # STAGE 3 — Validation & corrections │ │ └── perplexity_scorer.py # Qwen2.5 model wrapper (shared between stages) │ ├── prompts/ │ │ └── variants.py # All 8-10 prompt template variants │ ├── data/ │ │ ├── ai_vocabulary.json # AI-overused words/phrases with suggestions │ │ ├── transition_words.json # Transition words/phrases to flag │ │ └── heuristic_patterns.json # Patterns for the pre-filter │ └── utils/ │ ├── text_utils.py # Word counting, sentence splitting, etc. │ └── token_utils.py # Token counting, max_tokens calculation ├── frontend/ │ └── index.html # Simple single-page frontend ├── tests/ │ ├── test_analyzer.py # Tests for Stage 1 │ ├── test_analyzers/ # Tests for each individual analyzer │ │ ├── test_perplexity.py │ │ ├── test_burstiness.py │ │ ├── test_vocabulary.py │ │ ├── test_transitions.py │ │ ├── test_openings.py │ │ ├── test_structure.py │ │ └── test_informality.py │ ├── test_llm_rewriter.py │ ├── test_post_validator.py │ ├── test_pipeline.py │ └── test_api.py ├── Dockerfile ├── docker-compose.yml ├── requirements.txt ├── .env.example └── README.md ``` ### API Endpoints #### POST /humanize Main endpoint. ``` Request: { "text": "string (required, 50-5000 words)", "mode": "standard" | "thorough" (optional, default "standard") // "thorough" enables Stage 3 perplexity re-scoring } Response: { "success": true, "output_text": "string", "stats": { ... } // as defined in Stage 3e } Error Response: { "success": false, "error": "string", "code": "INPUT_TOO_SHORT" | "INPUT_TOO_LONG" | "LLM_TIMEOUT" | "PROCESSING_ERROR" } ``` #### POST /analyze Debug/testing endpoint — returns ONLY the Stage 1 analysis without calling the LLM. Useful for testing and tuning the analyzer. ``` Request: { "text": "string" } Response: { "success": true, "analysis": { ... } // The full AnalysisResult JSON from Stage 1 } ``` #### GET /health ``` Response: { "status": "healthy", "models_loaded": true, "uptime_seconds": 3600 } ``` ### Startup / Lifespan Events Using FastAPI's lifespan context manager: 1. Load spaCy model (`en_core_web_sm`) into memory 2. Load Qwen2.5-0.5B model and tokenizer into memory (~1.1GB RAM, `torch_dtype=torch.float32`, `device_map="cpu"`) 3. Load AI vocabulary database, transition words, heuristic patterns into memory 4. Initialize language_tool_python 5. Warm up Qwen2.5 with a dummy inference (first inference is always slower) 6. Log successful initialization with memory usage ### Error Handling - All stages must have try/except blocks - If Stage 1 fails: log error, send text to LLM with a generic instruction set (basic "rewrite as student" prompt without specific analysis) - If Stage 2 primary LLM fails: try fallback LLM - If both LLMs fail: return original text with error flag - If Stage 3 fails: log error, return Stage 2 output without validation - Never return a 500 error to the user — always return gracefully degraded output ### Environment Variables ``` ANTHROPIC_API_KEY=sk-ant-... OPENAI_API_KEY=sk-... PRIMARY_LLM=claude # "claude" or "openai" MAX_INPUT_WORDS=5000 MIN_INPUT_WORDS=50 MAX_EXPANSION_PERCENT=40 LLM_TIMEOUT_SECONDS=8 WORKERS=1 PORT=8000 LOG_LEVEL=INFO THOROUGH_MODE_DEFAULT=false # Enable Stage 3 perplexity re-scoring by default ``` --- ## FRONTEND Build a simple, clean single-page frontend in **plain HTML + CSS + JavaScript** (no framework needed). ### Requirements: - Clean, modern dark-themed UI - Large text input area (left side or top) - "Humanize" button with mode toggle (Standard / Thorough) - Output text area (right side or bottom) - Loading spinner during processing - Display stats after processing: - Word counts (input/output) - Expansion percentage - Perplexity improvement (input avg → output avg) - Burstiness improvement (input CV → output CV) - Number of instructions generated - Processing time breakdown (Stage 1 / Stage 2 / Stage 3) - Which LLM was used - Banned words that were auto-fixed - Copy-to-clipboard button for output - Character/word count on input area - Error messages displayed cleanly - Mobile responsive - **"Show Analysis" toggle** — allows user to see the raw Stage 1 analysis JSON (useful for debugging and client demos) - Serve from FastAPI as a static file --- ## PERFORMANCE REQUIREMENTS - 1,000 words must complete end-to-end in **under 10 seconds** - Stage 1 (Analysis): under 300ms - Stage 2 (LLM call): under 7 seconds - Stage 3 (Validation): under 200ms (under 400ms in thorough mode with perplexity re-scoring) - System must handle 17 concurrent requests per minute - Use async/await throughout - Pre-load all models at startup ## COST REQUIREMENTS - Target under **$1 per 100,000 words** processed - Enforce strict `max_tokens` on every LLM call - Never make more than 1 LLM call per request - Use cost-efficient models (Sonnet, GPT-4o-mini) --- ## DOCKER DEPLOYMENT ```dockerfile FROM python:3.11-slim RUN apt-get update && apt-get install -y \ build-essential \ && rm -rf /var/lib/apt/lists/* WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt # Pre-download Qwen2.5-0.5B during build (avoids 1GB download on every container start) RUN python -c "from transformers import AutoModelForCausalLM, AutoTokenizer; \ AutoModelForCausalLM.from_pretrained('Qwen/Qwen2.5-0.5B'); \ AutoTokenizer.from_pretrained('Qwen/Qwen2.5-0.5B')" # Pre-download spaCy model RUN python -m spacy download en_core_web_sm COPY . . # Single worker due to model memory (~1.1GB per worker) CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"] ``` **Critical note on workers:** With Qwen2.5-0.5B loaded, each worker uses ~1.1GB RAM. On a 4GB server, use `--workers 1` and rely on async for concurrency. On 8GB+ server, you can use `--workers 2`. **Memory optimization — share models across async requests:** ```python from contextlib import asynccontextmanager perplexity_scorer = None nlp = None @asynccontextmanager async def lifespan(app: FastAPI): global perplexity_scorer, nlp perplexity_scorer = PerplexityScorer() # Qwen2.5-0.5B, ~1.1GB nlp = spacy.load("en_core_web_sm") # ~50MB yield del perplexity_scorer, nlp app = FastAPI(lifespan=lifespan) ``` --- ## BUILD ORDER (Follow this sequence strictly) ### Step 1: Project Setup - Initialize project structure exactly as defined above - Create requirements.txt with all dependencies: ``` fastapi>=0.104.0 uvicorn>=0.24.0 httpx>=0.25.0 torch>=2.1.0 transformers>=4.36.0 accelerate>=0.25.0 spacy>=3.7.0 language-tool-python>=2.7.0 python-dotenv>=1.0.0 pydantic>=2.5.0 ``` - Create .env.example - Create config.py with all settings loaded from environment variables - Create Pydantic models for request/response in models.py ### Step 2: Utility Functions - Build text_utils.py: - `count_words(text: str) -> int` - `split_sentences(text: str) -> list[str]` (use spaCy) - `calculate_burstiness(sentence_lengths: list[int]) -> dict` (mean, std, CV) - `calculate_expansion_percentage(input_count: int, output_count: int) -> float` - Build token_utils.py: - `count_tokens(text: str, model: str) -> int` (approximate — use word_count * 1.4) - `calculate_max_tokens(input_word_count: int, max_expansion: float) -> int` - Build perplexity_scorer.py: - `PerplexityScorer` class with Qwen2.5-0.5B - `score_text(text: str) -> PerplexityResult` - `score_sentence(sentence: str) -> SentencePerplexityResult` - `score_sentences(sentences: list[str]) -> list[SentencePerplexityResult]` - Include the heuristic pre-filter as a method ### Step 3: Stage 1 — Individual Analyzers Build each analyzer in `app/core/analyzers/` one at a time: 1. `perplexity.py` — PerplexityAnalyzer 2. `burstiness.py` — BurstinessAnalyzer 3. `vocabulary.py` — VocabularyAnalyzer (loads ai_vocabulary.json) 4. `transitions.py` — TransitionAnalyzer 5. `openings.py` — OpeningPatternAnalyzer 6. `structure.py` — StructuralAnalyzer 7. `informality.py` — InformalityAnalyzer Each analyzer must: - Accept text (and optionally parsed spaCy doc) as input - Return a list of instruction dicts following the format specified in Stage 1 - Have its own unit test file - Complete in under 50ms individually (except perplexity which gets 200ms) Then build `analyzer.py` — the main `TextAnalyzer` class that: - Runs all sub-analyzers - Combines their outputs into the unified `AnalysisResult` format - Sorts instructions by sentence_index - Compiles the banned_words list - Generates the summary ### Step 4: Data Files - Create `ai_vocabulary.json` with 80-100+ entries (use the structure defined in section 1c, expand significantly beyond the examples given) - Create `transition_words.json` with all common academic transitions - Create `heuristic_patterns.json` with patterns for the perplexity pre-filter ### Step 5: Stage 2 — Guided LLM Rewriter - Build `prompt_manager.py`: - Store 8-10 prompt variants - Random rotation with no consecutive repeats - Method to format Stage 1 analysis into human-readable instructions for the LLM - Logging of which variant was used - Build `llm_rewriter.py`: - Async LLM calling with httpx - Support for Claude Sonnet (primary) and GPT-4o-mini (fallback) - Dynamic max_tokens calculation - Timeout handling (8 seconds) - Fallback logic: Claude → OpenAI → return original with error - Response parsing and cleaning ### Step 6: Stage 3 — Post Validator - Build `post_validator.py`: - Length validation and smart trimming - Banned word checking and auto-replacement - Grammar checking with language_tool_python - Entity preservation checking (NER comparison) - Optional perplexity re-scoring (thorough mode) - Stats aggregation ### Step 7: Pipeline Orchestrator - Build `pipeline.py`: - Wire all 3 stages together - Add timing measurements for each stage - Add comprehensive error handling with fallback logic - Support for "standard" and "thorough" modes ### Step 8: API Layer - Build FastAPI endpoints in routes.py: - POST /humanize - POST /analyze (debug endpoint) - GET /health - Add CORS middleware (allow all origins for development) - Add input validation (min/max word count) - Add request logging - Add simple in-memory rate limiting ### Step 9: Frontend - Build index.html with all features specified above - Clean, dark-themed design - Connect to API endpoints - Test end-to-end ### Step 10: Docker - Create Dockerfile as specified - Create docker-compose.yml - Test containerized deployment ### Step 11: Testing & Tuning - Write and run all unit tests - Test with sample AI-generated texts (use the examples provided below) - Test the /analyze endpoint to verify Stage 1 generates sensible instructions - Measure processing times per stage - Verify expansion percentages stay under 40% - Test error handling (LLM timeout, invalid input, etc.) --- ## SAMPLE TEST INPUTS **Test Input 1 (Healthcare):** "Artificial intelligence has fundamentally transformed the landscape of modern healthcare. Through the implementation of sophisticated machine learning algorithms, medical professionals can now diagnose diseases with unprecedented accuracy. Furthermore, AI-powered systems have demonstrated remarkable capabilities in predicting patient outcomes, enabling proactive intervention strategies. The integration of these technologies into clinical workflows represents a significant paradigm shift in how healthcare services are delivered and optimized." **Test Input 2 (Climate):** "Climate change poses an existential threat to global ecosystems and human civilization. The scientific consensus overwhelmingly supports the conclusion that anthropogenic greenhouse gas emissions are the primary driver of observed warming trends. Consequently, nations worldwide have begun implementing comprehensive mitigation strategies, including transitioning to renewable energy sources and establishing carbon pricing mechanisms. However, the pace of these efforts remains insufficient to meet the targets outlined in the Paris Agreement." **Test Input 3 (Education):** "The rapid advancement of educational technology has revolutionized the way students engage with learning materials. Digital platforms now offer personalized learning experiences that adapt to individual student needs and learning styles. Moreover, the integration of artificial intelligence into educational frameworks has enabled more efficient assessment methods and targeted feedback mechanisms. These innovations collectively contribute to improved learning outcomes and greater accessibility in education." For each test input, verify: 1. Stage 1 generates specific, actionable instructions (check via /analyze endpoint) 2. The final output reads naturally and sounds like a real student 3. Expansion stays under 40% 4. No banned words remain in the output 5. All factual content is preserved --- ## IMPORTANT REMINDERS - The analysis engine (Stage 1) is the MOST CRITICAL component. It drives everything. - Stage 1 does NOT modify text. It generates INSTRUCTIONS. This is the key architectural difference. - The LLM (Stage 2) must be given the ORIGINAL text plus the instructions. Not a modified version. - Meaning preservation is NON-NEGOTIABLE. Never distort facts or arguments. - The AI vocabulary database must be EXTENSIVE and CAREFULLY CURATED. This directly affects accuracy. - Test with diverse inputs: short paragraphs, long essays, technical content, humanities content. - Every function should have docstrings and type hints. - Handle edge cases: very short input, very long input, special characters, code snippets, citations. - The /analyze endpoint is crucial for debugging — use it frequently during development. --- Now begin building. Start with Step 1 and proceed sequentially. Ask me if anything is unclear before starting a step.