Spaces:
Runtime error

humanizer-engine / PROGRESS.md
faseehsandhu's picture
stage 1 completed
f66da21
|
Raw History Blame Contribute Delete
14.6 kB
# 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`.