Spaces:
Runtime error
Runtime error
|
Download PROGRESS.md from digitalytics/humanizer-engine: direct link, hf CLI and curl.
- Browser
- Download file 14.6 kB
-
https://huggingface.co/spaces/digitalytics/humanizer-engine/resolve/main/PROGRESS.md
- Command line
-
hf download hf://spaces/digitalytics/humanizer-engine/PROGRESS.md
-
curl -L -o PROGRESS.md https://huggingface.co/spaces/digitalytics/humanizer-engine/resolve/main/PROGRESS.md
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`. | |