Spaces:
Runtime error

faseehsandhu commited on
Commit
f66da21
·
0 Parent(s):

stage 1 completed

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .claude/settings.local.json +12 -0
  2. .env.example +11 -0
  3. PROGRESS.md +348 -0
  4. PROJECT_INSTRUCTIONS.md +974 -0
  5. app/__init__.py +0 -0
  6. app/__pycache__/__init__.cpython-313.pyc +0 -0
  7. app/api/__init__.py +0 -0
  8. app/api/models.py +133 -0
  9. app/api/routes.py +12 -0
  10. app/config.py +94 -0
  11. app/core/__init__.py +0 -0
  12. app/core/__pycache__/__init__.cpython-313.pyc +0 -0
  13. app/core/__pycache__/analyzer.cpython-313.pyc +0 -0
  14. app/core/__pycache__/perplexity_scorer.cpython-313.pyc +0 -0
  15. app/core/analyzer.py +259 -0
  16. app/core/analyzers/__init__.py +0 -0
  17. app/core/analyzers/__pycache__/__init__.cpython-313.pyc +0 -0
  18. app/core/analyzers/__pycache__/burstiness.cpython-313.pyc +0 -0
  19. app/core/analyzers/__pycache__/informality.cpython-313.pyc +0 -0
  20. app/core/analyzers/__pycache__/openings.cpython-313.pyc +0 -0
  21. app/core/analyzers/__pycache__/perplexity.cpython-313.pyc +0 -0
  22. app/core/analyzers/__pycache__/structure.cpython-313.pyc +0 -0
  23. app/core/analyzers/__pycache__/transitions.cpython-313.pyc +0 -0
  24. app/core/analyzers/__pycache__/vocabulary.cpython-313.pyc +0 -0
  25. app/core/analyzers/burstiness.py +172 -0
  26. app/core/analyzers/informality.py +284 -0
  27. app/core/analyzers/openings.py +362 -0
  28. app/core/analyzers/perplexity.py +349 -0
  29. app/core/analyzers/structure.py +298 -0
  30. app/core/analyzers/transitions.py +224 -0
  31. app/core/analyzers/vocabulary.py +150 -0
  32. app/core/perplexity_scorer.py +316 -0
  33. app/data/.gitkeep +0 -0
  34. app/data/ai_vocabulary.json +2210 -0
  35. app/data/heuristic_patterns.json +365 -0
  36. app/data/transition_words.json +137 -0
  37. app/main.py +174 -0
  38. app/prompts/__init__.py +0 -0
  39. app/utils/__init__.py +0 -0
  40. app/utils/__pycache__/__init__.cpython-313.pyc +0 -0
  41. app/utils/__pycache__/text_utils.cpython-313.pyc +0 -0
  42. app/utils/text_utils.py +143 -0
  43. app/utils/token_utils.py +53 -0
  44. err.txt +11 -0
  45. errors.txt +4 -0
  46. frontend/.gitkeep +0 -0
  47. requirements.txt +11 -0
  48. test_ppl.py +45 -0
  49. test_stage1.py +247 -0
  50. tests/__init__.py +0 -0
.claude/settings.local.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "permissions": {
3
+ "allow": [
4
+ "Bash(dir:*)",
5
+ "Bash(cmd.exe /c \"mkdir d:\\\\Workspace\\\\humanization-engine\\\\app\\\\data 2>nul && echo created\")",
6
+ "Bash(python3:*)",
7
+ "Bash(node:*)",
8
+ "Bash(python:*)",
9
+ "Bash(pip install:*)"
10
+ ]
11
+ }
12
+ }
.env.example ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ANTHROPIC_API_KEY=sk-ant-your-key-here
2
+ OPENAI_API_KEY=sk-your-openai-key-here
3
+ PRIMARY_LLM=claude # "claude" or "openai"
4
+ MAX_INPUT_WORDS=5000
5
+ MIN_INPUT_WORDS=50
6
+ MAX_EXPANSION_PERCENT=40
7
+ LLM_TIMEOUT_SECONDS=8
8
+ WORKERS=1
9
+ PORT=8000
10
+ LOG_LEVEL=INFO
11
+ THOROUGH_MODE_DEFAULT=false # Enable Stage 3 perplexity re-scoring by default
PROGRESS.md ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Humanization Engine — Build Progress & Context
2
+
3
+ > **For new conversations:** Read this file + `PROJECT_INSTRUCTIONS.md` before doing anything.
4
+ > The project root is `d:\Workspace\humanization-engine\`.
5
+ > Global Python 3.13 is used — NO venv, packages installed system-wide.
6
+
7
+ ---
8
+
9
+ ## What This Project Is
10
+
11
+ A production-ready web app that rewrites AI-generated text to bypass AI detectors (primarily Originality.ai).
12
+ Architecture: **Analysis-Guided LLM Rewrite** (3-stage pipeline). NOT a wrapper around any third-party humanizer.
13
+
14
+ ---
15
+
16
+ ## Architecture: 3-Stage Pipeline
17
+
18
+ ```
19
+ Input AI Text
20
+ │
21
+ ▼
22
+ STAGE 1: ANALYSIS ENGINE ← Local, <300ms, NO API cost, does NOT modify text
23
+ - Analyzes text using 7 sub-analyzers + Qwen2.5-0.5B
24
+ - Produces structured JSON instruction set (AnalysisResult)
25
+ │
26
+ ▼
27
+ STAGE 2: GUIDED LLM REWRITE ← Single API call (Claude Sonnet primary, GPT-4o-mini fallback)
28
+ - Receives ORIGINAL text (unchanged) + Stage 1 instruction set
29
+ - LLM changes ONLY what is flagged, keeps everything else as-is
30
+ │
31
+ ▼
32
+ STAGE 3: POST-VALIDATION ← Local, <200ms, NO API cost
33
+ - Checks length, auto-fixes banned words, grammar check
34
+ - Returns output + full stats
35
+ │
36
+ ▼
37
+ Output Text
38
+ ```
39
+
40
+ **Critical rule:** Stage 1 NEVER modifies the text. Stage 2 always gets the original text.
41
+
42
+ ---
43
+
44
+ ## Environment
45
+
46
+ | Item | Value |
47
+ |------|-------|
48
+ | Python | 3.13.7 (global, no venv) |
49
+ | Python path | `C:\Users\User\AppData\Local\Programs\Python\Python313\python.exe` |
50
+ | torch | 2.10.0+cpu |
51
+ | transformers | 5.2.0 |
52
+ | spaCy | 3.8.11 + `en_core_web_sm` model installed |
53
+ | pydantic | 2.12.5 |
54
+ | pydantic-settings | 2.13.0 |
55
+ | accelerate | 1.12.0 |
56
+ | Qwen2.5-0.5B cache | `C:\Users\User\.cache\huggingface\hub\models--Qwen--Qwen2.5-0.5B` |
57
+
58
+ **Packages NOT yet installed (needed for later steps):**
59
+ - `fastapi`, `uvicorn`, `httpx` — needed for Step 8 (API layer)
60
+ - `language-tool-python` — needed for Step 6 (grammar checking in Stage 3)
61
+
62
+ ---
63
+
64
+ ## .env Configuration
65
+
66
+ Located at `d:\Workspace\humanization-engine\.env`:
67
+ ```
68
+ ANTHROPIC_API_KEY=sk-ant-your-key-here ← placeholder, needs real key
69
+ OPENAI_API_KEY=sk-proj-5oQdbwo... ← real key already set
70
+ PRIMARY_LLM=openai ← using GPT-4o-mini as primary
71
+ MAX_INPUT_WORDS=5000
72
+ MIN_INPUT_WORDS=50
73
+ MAX_EXPANSION_PERCENT=40
74
+ LLM_TIMEOUT_SECONDS=8
75
+ WORKERS=1
76
+ PORT=8000
77
+ LOG_LEVEL=INFO
78
+ ```
79
+
80
+ ---
81
+
82
+ ## Complete File Tree (what exists right now)
83
+
84
+ ```
85
+ humanization-engine/
86
+ ├── app/
87
+ │ ├── __init__.py
88
+ │ ├── main.py ✅ FastAPI app + lifespan (loads spaCy + Qwen2.5)
89
+ │ ├── config.py ✅ All settings via pydantic-settings
90
+ │ ├── api/
91
+ │ │ ├── __init__.py
92
+ │ │ ├── models.py ✅ Pydantic request/response models
93
+ │ │ └── routes.py ✅ SKELETON ONLY — routes to be added in Step 8
94
+ │ ├── core/
95
+ │ │ ├── __init__.py
96
+ │ │ ├── analyzer.py ✅ TextAnalyzer — main Stage 1 orchestrator
97
+ │ │ ├── perplexity_scorer.py ✅ Qwen2.5-0.5B wrapper — HAS KNOWN BUG (see below)
98
+ │ │ ├── analyzers/
99
+ │ │ │ ├── __init__.py
100
+ │ │ │ ├── perplexity.py ✅ PerplexityAnalyzer (heuristic pre-filter + Qwen2.5)
101
+ │ │ │ ├── burstiness.py ✅ BurstinessAnalyzer (sentence-length CV)
102
+ │ │ │ ├── vocabulary.py ✅ VocabularyAnalyzer (loads ai_vocabulary.json)
103
+ │ │ │ ├── transitions.py ✅ TransitionAnalyzer (loads transition_words.json)
104
+ │ │ │ ├── openings.py ✅ OpeningPatternAnalyzer
105
+ │ │ │ ├── structure.py ✅ StructuralAnalyzer (paragraph-level)
106
+ │ │ │ └── informality.py ✅ InformalityAnalyzer (contractions + hedging)
107
+ │ │ ├── pipeline.py ❌ NOT BUILT (Step 7)
108
+ │ │ ├── llm_rewriter.py ❌ NOT BUILT (Step 5)
109
+ │ │ ├── prompt_manager.py ❌ NOT BUILT (Step 5)
110
+ │ │ └── post_validator.py ❌ NOT BUILT (Step 6)
111
+ │ ├── prompts/
112
+ │ │ ├── __init__.py
113
+ │ │ └── variants.py ❌ NOT BUILT (Step 5)
114
+ │ ├── data/
115
+ │ │ ├── ai_vocabulary.json ✅ 149 words + 72 phrases with severity + suggestions
116
+ │ │ ├── transition_words.json ✅ 128 entries (starters, connectors, formulaic openers)
117
+ │ │ └── heuristic_patterns.json ✅ 79 starters, 113 vocab triggers, 66 phrase patterns
118
+ │ └── utils/
119
+ │ ├── __init__.py
120
+ │ ├── text_utils.py ✅ count_words, split_sentences, calculate_burstiness, etc.
121
+ │ └── token_utils.py ✅ count_tokens, calculate_max_tokens
122
+ ├── frontend/
123
+ │ └── .gitkeep ❌ NOT BUILT (Step 9)
124
+ ├── tests/
125
+ │ ├── __init__.py
126
+ │ └── test_analyzers/
127
+ │ └── __init__.py ❌ Test files NOT BUILT (Step 11)
128
+ ├── verify_stage1.py ✅ Test script for Stage 1 (no Qwen2.5 needed)
129
+ ├── test_ppl.py ✅ Test script for perplexity scorer timing
130
+ ├── PROJECT_INSTRUCTIONS.md ✅ Full project spec
131
+ ├── PROGRESS.md ✅ This file
132
+ ├── requirements.txt ✅
133
+ ├── .env ✅ (has real OpenAI key)
134
+ ├── .env.example ✅
135
+ ├── Dockerfile ❌ NOT BUILT (Step 10)
136
+ └── docker-compose.yml ❌ NOT BUILT (Step 10)
137
+ ```
138
+
139
+ ---
140
+
141
+ ## ✅ COMPLETED STEPS
142
+
143
+ ### Step 1: Project Setup — DONE
144
+ All package directories, `__init__.py` files, `config.py`, `models.py`, `main.py`, `requirements.txt`, `.env.example`.
145
+
146
+ ### Step 2: Utility Functions — DONE
147
+ `text_utils.py`, `token_utils.py`, `perplexity_scorer.py` (has known bug — see below).
148
+
149
+ ### Steps 3 & 4: Stage 1 Analyzers + Data Files — DONE
150
+ All 7 sub-analyzers + `analyzer.py` orchestrator + all 3 data JSON files.
151
+
152
+ ---
153
+
154
+ ## 🔴 MUST FIX BEFORE CONTINUING — perplexity_scorer.py bug
155
+
156
+ **File:** `app/core/perplexity_scorer.py`
157
+
158
+ **Problem 1 — Span detection is catastrophically slow:**
159
+ The `score_sentence()` method calls `_find_low_perplexity_spans()` by default.
160
+ That method runs a sliding-window with ~16 forward passes per sentence → adds 750–1100ms per sentence.
161
+ Single forward pass (what we actually need) = 100–120ms. Spans = 10× slower, not needed for Stage 2.
162
+
163
+ **Fix:** In `score_sentence()` around line 114, change:
164
+ ```python
165
+ # CURRENT (broken - always runs spans):
166
+ def score_sentence(self, sentence: str, sentence_index: int = 0) -> SentencePerplexityResult:
167
+ mean_ppl = self._compute_mean_perplexity(sentence)
168
+ classification = self._classify(mean_ppl)
169
+ low_spans = self._find_low_perplexity_spans(sentence) # ← DELETE/DISABLE THIS
170
+
171
+ # FIXED (spans off by default):
172
+ def score_sentence(self, sentence: str, sentence_index: int = 0, compute_spans: bool = False) -> SentencePerplexityResult:
173
+ mean_ppl = self._compute_mean_perplexity(sentence)
174
+ classification = self._classify(mean_ppl)
175
+ low_spans = self._find_low_perplexity_spans(sentence) if compute_spans else []
176
+ ```
177
+
178
+ **Problem 2 — Deprecated argument (transformers 5.x warning):**
179
+ ```python
180
+ # CURRENT:
181
+ self.model = AutoModelForCausalLM.from_pretrained(
182
+ model_id,
183
+ torch_dtype=torch.float32, # ← deprecated in transformers 5.x
184
+ device_map="cpu",
185
+ )
186
+
187
+ # FIXED:
188
+ self.model = AutoModelForCausalLM.from_pretrained(
189
+ model_id,
190
+ dtype=torch.float32, # ← correct for transformers 5.x
191
+ device_map="cpu",
192
+ )
193
+ ```
194
+
195
+ **After fix:** ~100–120ms per sentence. For 1K words (~15 sentences), pre-filter passes ~8 sentences → ~850ms total perplexity scoring time.
196
+
197
+ ---
198
+
199
+ ## Stage 1 Verification Results (already tested)
200
+
201
+ Run `python verify_stage1.py` from project root to verify Stage 1 (no Qwen2.5 needed).
202
+
203
+ | Sample | Words | Sentences | Time | Banned Words | Instructions | Burstiness CV |
204
+ |--------|-------|-----------|------|-------------|--------------|--------------|
205
+ | Healthcare | 63 | 4 | 24ms | 14 | 17 | 0.290 (high_uniformity) |
206
+ | Climate | 69 | 4 | 17ms | 3 | 7 | 0.219 (high_uniformity) |
207
+ | Education | 63 | 4 | 16ms | 7 | 10 | 0.159 (high_uniformity) |
208
+
209
+ All targets met. Transitions correctly flagged (Furthermore, Consequently, Moreover, However). Target is <300ms — we're 10–15× faster even without optimization.
210
+
211
+ **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.
212
+
213
+ ---
214
+
215
+ ## ❌ REMAINING STEPS (pick up from here)
216
+
217
+ ### Step 5: Stage 2 — Guided LLM Rewriter ← NEXT TO BUILD
218
+
219
+ Three files to create:
220
+
221
+ **`app/prompts/variants.py`**
222
+ - 8–10 system prompt variants (different role framing, emphasis, tone guidance)
223
+ - Core rules identical across all variants (follow instructions, don't exceed 135% length, no banned words)
224
+ - Variants differ in: role ("student revising draft" vs "confident undergrad"), tone guidance, micro-instructions
225
+
226
+ **`app/core/prompt_manager.py`**
227
+ - `PromptManager` class
228
+ - Stores all variants, rotates randomly, never uses same variant twice in a row
229
+ - `format_analysis_for_llm(analysis_result, original_text)` → converts JSON instructions to human-readable text block for the prompt
230
+ - Logs which variant was used per request
231
+
232
+ **`app/core/llm_rewriter.py`**
233
+ - `LLMRewriter` class (async)
234
+ - `async def rewrite(text, analysis_result, mode) -> RewriteResult`
235
+ - Primary: `claude-sonnet-4-20250514` via Anthropic API (httpx)
236
+ - Fallback: `gpt-4o-mini` via OpenAI API (httpx)
237
+ - Dynamic `max_tokens` = `input_word_count * 1.4 * 1.5`
238
+ - Hard 8-second timeout
239
+ - If both fail → return original text with error flag
240
+
241
+ ### Step 6: Stage 3 — Post Validator
242
+
243
+ **`app/core/post_validator.py`**
244
+ - `PostValidator` class
245
+ - Length check: if output > 140% of input → trim elaborations
246
+ - Banned word check: if any banned words remain → regex-replace with first suggestion from vocab DB
247
+ - Grammar check: `language_tool_python` (needs `pip install language-tool-python`)
248
+ - NER preservation: compare named entities in input vs output using spaCy
249
+ - Optional perplexity re-scoring (thorough mode only): re-score output with Qwen2.5, compare to input
250
+ - Returns full `stats` dict (word counts, perplexity before/after, banned words fixed, timing, etc.)
251
+
252
+ ### Step 7: Pipeline Orchestrator
253
+
254
+ **`app/core/pipeline.py`**
255
+ - `HumanizationPipeline` class
256
+ - `async def run(text, mode) -> PipelineResult`
257
+ - Wires Stage 1 → Stage 2 → Stage 3
258
+ - Times each stage
259
+ - Error handling: Stage 1 fail → generic prompt; Stage 2 primary fail → fallback LLM; Stage 2 both fail → return original
260
+ - Accepts `nlp`, `perplexity_scorer`, `vocab_analyzer`, `language_tool` injected at init (shared from app startup)
261
+
262
+ ### Step 8: API Layer
263
+
264
+ **`app/api/routes.py`** (replace the skeleton)
265
+ - `POST /humanize` — main endpoint, calls pipeline
266
+ - `POST /analyze` — debug endpoint, returns Stage 1 only (no LLM call)
267
+ - `GET /health` — returns status + uptime + `models_loaded`
268
+ - CORS already configured in `main.py`
269
+ - Add simple in-memory rate limiting (e.g. 20 req/min per IP)
270
+ - Input validation: word count between `MIN_INPUT_WORDS` and `MAX_INPUT_WORDS`
271
+
272
+ Also update `app/main.py` to:
273
+ - Create `TextAnalyzer` and `HumanizationPipeline` in lifespan and store on `app.state`
274
+ - Pass shared models (nlp, scorer, vocab) to both
275
+
276
+ ### Step 9: Frontend
277
+
278
+ **`frontend/index.html`** — Single file, plain HTML + CSS + JS, no framework
279
+ - Dark theme
280
+ - Left/top: text input with word counter
281
+ - Right/bottom: output with copy button
282
+ - "Humanize" button + Standard/Thorough mode toggle
283
+ - Loading spinner during processing
284
+ - Stats panel after processing: word counts, expansion %, perplexity before/after, CV before/after, instructions generated, timing breakdown, LLM used, banned words auto-fixed
285
+ - "Show Analysis" toggle → shows raw Stage 1 JSON
286
+ - Serve from FastAPI as static files
287
+
288
+ ### Step 10: Docker
289
+
290
+ **`Dockerfile`**
291
+ ```dockerfile
292
+ FROM python:3.11-slim
293
+ RUN apt-get update && apt-get install -y build-essential
294
+ WORKDIR /app
295
+ COPY requirements.txt .
296
+ RUN pip install --no-cache-dir -r requirements.txt
297
+ RUN python -c "from transformers import AutoModelForCausalLM, AutoTokenizer; AutoModelForCausalLM.from_pretrained('Qwen/Qwen2.5-0.5B'); AutoTokenizer.from_pretrained('Qwen/Qwen2.5-0.5B')"
298
+ RUN python -m spacy download en_core_web_sm
299
+ COPY . .
300
+ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"]
301
+ ```
302
+
303
+ **`docker-compose.yml`** — mounts `.env`, exposes port 8000
304
+
305
+ ### Step 11: Testing & Tuning
306
+
307
+ Test files in `tests/`:
308
+ - `test_analyzer.py` — full TextAnalyzer with sample inputs
309
+ - `test_analyzers/test_burstiness.py`, `test_vocabulary.py`, `test_transitions.py`, `test_openings.py`, `test_structure.py`, `test_informality.py`, `test_perplexity.py`
310
+ - `test_llm_rewriter.py` — mock LLM responses
311
+ - `test_post_validator.py`
312
+ - `test_pipeline.py` — end-to-end with mocked LLM
313
+ - `test_api.py` — FastAPI test client
314
+
315
+ ---
316
+
317
+ ## How to Run / Test
318
+
319
+ ### Test Stage 1 (no Qwen2.5, fast)
320
+ ```bash
321
+ cd d:\Workspace\humanization-engine
322
+ python verify_stage1.py
323
+ ```
324
+
325
+ ### Test perplexity scorer (Qwen2.5)
326
+ ```bash
327
+ cd d:\Workspace\humanization-engine
328
+ python test_ppl.py
329
+ ```
330
+ Note: apply the two fixes in `perplexity_scorer.py` first (span detection + dtype arg).
331
+
332
+ ### Run the full app (once Steps 5–8 are done)
333
+ ```bash
334
+ cd d:\Workspace\humanization-engine
335
+ uvicorn app.main:app --port 8000 --reload
336
+ ```
337
+
338
+ ---
339
+
340
+ ## Key Design Decisions to Preserve
341
+
342
+ 1. **`TextAnalyzer` is stateless per-call** — injected with shared `nlp` and `perplexity_scorer` at init, safe for async reuse.
343
+ 2. **All data files resolve paths relative to `__file__`** so they work regardless of working directory.
344
+ 3. **Pre-filter before Qwen2.5** — always run heuristic_prefilter first, only score flagged sentences.
345
+ 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.
346
+ 5. **`max_tokens` is dynamic** — calculated as `input_word_count * 1.4 * 1.5`, never hardcoded.
347
+ 6. **Stage 3 is non-blocking** — if it fails, return Stage 2 output with an error flag. Never crash the request.
348
+ 7. **LLM model IDs**: primary = `claude-sonnet-4-20250514`, fallback = `gpt-4o-mini`.
PROJECT_INSTRUCTIONS.md ADDED
@@ -0,0 +1,974 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HUMANIZATION ENGINE — Full Project Context & Build Instructions
2
+ ## Architecture C: Analysis-Guided LLM Rewrite
3
+
4
+ ## ROLE
5
+ 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.
6
+
7
+ ---
8
+
9
+ ## PROJECT GOAL
10
+ 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.
11
+
12
+ ---
13
+
14
+ ## SUCCESS CRITERIA
15
+ The output text must:
16
+ - Be flagged as **"Human"** by Originality.ai in most cases (target >85% pass rate)
17
+ - Maintain high academic quality suitable for university students
18
+ - Have strong grammar and natural readability
19
+ - Stay within **30–40% length increase** of the original (NEVER 2x longer)
20
+ - Be confirmed as well-written by any major LLM (GPT, Claude, Gemini)
21
+ - Process 1,000 words in **under 10 seconds**
22
+ - Support approximately **500 users per 30 minutes** (~17 concurrent requests/min)
23
+
24
+ ---
25
+
26
+ ## CRITICAL ARCHITECTURAL INSIGHT — READ THIS FIRST
27
+
28
+ 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.
29
+
30
+ The fundamental problem with most humanizers is:
31
+
32
+ ```
33
+ AI text → LLM rewrites it → Output is STILL LLM-generated → Still gets detected
34
+ ```
35
+
36
+ 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.
37
+
38
+ **Our solution: Architecture C — Analysis-Guided Rewrite**
39
+
40
+ 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:
41
+
42
+ 1. The LLM makes **targeted changes** (only to flagged portions), not a full rewrite
43
+ 2. Untouched portions retain original structure — no new LLM fingerprint on those parts
44
+ 3. Stage 1's analysis **directly controls** the output rather than being overwritten
45
+ 4. Fewer total tokens are LLM-generated = weaker AI signal overall
46
+
47
+ ---
48
+
49
+ ## CORE ARCHITECTURE — 3-Stage Pipeline
50
+
51
+ ```
52
+ Input AI Text
53
+ │
54
+ ▼
55
+ ┌──────────────────────────────────────────────────┐
56
+ │ STAGE 1: ANALYSIS ENGINE │
57
+ │ (Analyzes text, generates specific instructions)│
58
+ │ Local, <300ms, no API cost │
59
+ │ This stage does NOT modify the text. │
60
+ │ It produces a structured instruction set. │
61
+ └──────────────────┬───────────────────────────────┘
62
+ │
63
+ ├── Original text (unchanged)
64
+ ├── Structured instruction set (JSON)
65
+ │
66
+ ▼
67
+ ┌──────────────────────────────────────────────────┐
68
+ │ STAGE 2: GUIDED LLM REWRITE │
69
+ │ (Receives original text + instructions) │
70
+ │ Single API call, ~3-6 seconds │
71
+ │ LLM follows the instructions precisely, │
72
+ │ changing ONLY what is flagged. │
73
+ └──────────────────┬───────────────────────────────┘
74
+ │
75
+ ▼
76
+ ┌──────────────────────────────────────────────────┐
77
+ │ STAGE 3: POST-VALIDATION & MICRO-CORRECTIONS │
78
+ │ Local, <200ms, no API cost │
79
+ │ Verifies quality, length, and that the LLM │
80
+ │ actually followed the instructions. │
81
+ └──────────────────┬───────────────────────────────┘
82
+ │
83
+ ▼
84
+ Output Text
85
+ ```
86
+
87
+ ---
88
+
89
+ ## STAGE 1: ANALYSIS ENGINE (CRITICAL — 60% of success depends on this)
90
+
91
+ ### PURPOSE
92
+ 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.
93
+
94
+ ### WHAT TO BUILD
95
+
96
+ Create a Python class `TextAnalyzer` with the following analysis sub-components:
97
+
98
+ #### 1a. Perplexity Analysis (Qwen2.5-0.5B)
99
+ - Load **Qwen2.5-0.5B** (`Qwen/Qwen2.5-0.5B`) at application startup
100
+ - Use `torch_dtype=torch.float32` for CPU deployment
101
+ - Use `device_map="cpu"` explicitly
102
+ - Wrap all inference in `@torch.no_grad()` to save memory
103
+ - RAM usage: ~1.1GB
104
+ - **Speed optimization — sentence-level filtering:**
105
+ 1. First run a fast heuristic pre-filter (<10ms) to flag sentences that LOOK AI-like:
106
+ - Starts with common transition words (Furthermore, Moreover, Additionally, Consequently, etc.)
107
+ - Length is within ±3 words of the average sentence length (too uniform)
108
+ - Contains 2+ words from a known AI-vocabulary list
109
+ - Contains common AI phrase patterns ("it is important to note", "plays a crucial role", etc.)
110
+ 2. Only send the flagged sentences (~50-60% of total) through Qwen2.5 for actual perplexity scoring
111
+ 3. This brings scoring time from ~400-700ms down to ~200-350ms for 1K words
112
+ - For each scored sentence, output:
113
+ ```json
114
+ {
115
+ "sentence_index": 2,
116
+ "sentence_text": "Through the implementation of sophisticated...",
117
+ "mean_perplexity": 22.4,
118
+ "classification": "high_risk", // "high_risk" | "medium_risk" | "low_risk"
119
+ "low_perplexity_spans": [
120
+ {"tokens": "implementation of sophisticated", "perplexity": 8.3}
121
+ ]
122
+ }
123
+ ```
124
+ - Classification thresholds (tune these based on testing):
125
+ - `high_risk`: mean perplexity < 30 (very predictable — needs major restructuring)
126
+ - `medium_risk`: mean perplexity 30-60 (somewhat predictable — needs targeted changes)
127
+ - `low_risk`: mean perplexity > 60 (already human-like — minimal or no changes)
128
+
129
+ #### 1b. Burstiness Analysis
130
+ - Parse text using **spaCy** (`en_core_web_sm`)
131
+ - Calculate sentence lengths (word counts) for every sentence
132
+ - Calculate:
133
+ - Mean sentence length
134
+ - Standard deviation of sentence lengths
135
+ - Coefficient of variation (CV = std/mean)
136
+ - Min and max sentence length
137
+ - Flag uniformity problems:
138
+ - If CV < 0.3 → "high_uniformity" (AI text typically has CV 0.15-0.30)
139
+ - If CV 0.3-0.45 → "moderate_uniformity"
140
+ - If CV > 0.45 → "acceptable" (human text typically has CV 0.4-0.6+)
141
+ - For uniform text, generate specific instructions:
142
+ ```json
143
+ {
144
+ "type": "burstiness",
145
+ "severity": "high_uniformity",
146
+ "current_cv": 0.22,
147
+ "target_cv": "0.45-0.60",
148
+ "instructions": [
149
+ {"sentence_index": 3, "action": "shorten", "detail": "Make this much shorter (8-10 words). Currently 19 words, similar to adjacent sentences."},
150
+ {"sentence_index": 5, "action": "lengthen", "detail": "Expand this slightly or merge with sentence 6 to create one longer complex sentence."},
151
+ {"sentence_index": 7, "action": "split", "detail": "Split into two sentences at the clause boundary after 'however'."}
152
+ ]
153
+ }
154
+ ```
155
+
156
+ #### 1c. Vocabulary Analysis
157
+ - Build and load a comprehensive **AI-vocabulary database** (JSON file) containing 80-100+ words/phrases that AI text overuses. Organized as:
158
+ ```json
159
+ {
160
+ "single_words": {
161
+ "furthermore": {"severity": "high", "suggestions": ["Beyond this", "What's more", "On top of that", "Adding to this", "[remove transition entirely]"]},
162
+ "moreover": {"severity": "high", "suggestions": ["Also worth noting", "In addition", "Alongside this", "[remove transition entirely]"]},
163
+ "additionally": {"severity": "high", "suggestions": ["Another point is", "It's also true that", "Equally", "[restructure without transition]"]},
164
+ "consequently": {"severity": "high", "suggestions": ["As a result", "This means", "Because of this", "[restructure as cause-effect]"]},
165
+ "significantly": {"severity": "medium", "suggestions": ["Notably", "To a large degree", "In meaningful ways", "Quite a bit"]},
166
+ "demonstrates": {"severity": "medium", "suggestions": ["Shows", "Points to", "Makes clear", "Highlights"]},
167
+ "utilize": {"severity": "high", "suggestions": ["Use", "Make use of", "Draw on", "Rely on"]},
168
+ "implement": {"severity": "medium", "suggestions": ["Put in place", "Roll out", "Carry out", "Set up"]},
169
+ "comprehensive": {"severity": "medium", "suggestions": ["Thorough", "Wide-ranging", "In-depth", "Detailed"]},
170
+ "facilitate": {"severity": "high", "suggestions": ["Help", "Support", "Make possible", "Enable"]},
171
+ "leverage": {"severity": "high", "suggestions": ["Use", "Take advantage of", "Build on", "Tap into"]},
172
+ "robust": {"severity": "high", "suggestions": ["Strong", "Solid", "Reliable", "Sturdy"]},
173
+ "paradigm": {"severity": "high", "suggestions": ["Model", "Framework", "Approach", "Way of thinking"]},
174
+ "unprecedented": {"severity": "high", "suggestions": ["Never seen before", "Rare", "Unusual", "Exceptional"]},
175
+ "transformative": {"severity": "high", "suggestions": ["Game-changing", "Major", "Powerful", "Meaningful"]},
176
+ "optimize": {"severity": "medium", "suggestions": ["Improve", "Fine-tune", "Make better", "Refine"]},
177
+ "streamline": {"severity": "high", "suggestions": ["Simplify", "Speed up", "Clean up", "Make easier"]},
178
+ "innovative": {"severity": "medium", "suggestions": ["Creative", "New", "Fresh", "Original"]},
179
+ "crucial": {"severity": "medium", "suggestions": ["Key", "Central", "Vital", "Essential"]},
180
+ "delve": {"severity": "high", "suggestions": ["Explore", "Look into", "Dig into", "Examine"]},
181
+ "multifaceted": {"severity": "high", "suggestions": ["Complex", "Layered", "Varied", "Many-sided"]},
182
+ "underscore": {"severity": "medium", "suggestions": ["Highlight", "Stress", "Emphasize", "Point out"]},
183
+ "overarching": {"severity": "high", "suggestions": ["Main", "Broad", "Central", "Guiding"]},
184
+ "spearheaded": {"severity": "high", "suggestions": ["Led", "Drove", "Pushed forward", "Championed"]},
185
+ "encompass": {"severity": "medium", "suggestions": ["Include", "Cover", "Take in", "Span"]},
186
+ "pivotal": {"severity": "high", "suggestions": ["Key", "Important", "Critical", "Central"]},
187
+ "landscape": {"severity": "high", "suggestions": ["Field", "Area", "Scene", "World"]},
188
+ "realm": {"severity": "high", "suggestions": ["Area", "Field", "Domain", "World"]},
189
+ "embark": {"severity": "high", "suggestions": ["Start", "Begin", "Set out on", "Take on"]},
190
+ "foster": {"severity": "medium", "suggestions": ["Encourage", "Support", "Build", "Grow"]},
191
+ "navigate": {"severity": "medium", "suggestions": ["Work through", "Handle", "Deal with", "Manage"]},
192
+ "tapestry": {"severity": "high", "suggestions": ["Mix", "Blend", "Collection", "Web"]},
193
+ "testament": {"severity": "high", "suggestions": ["Proof", "Evidence", "Sign", "Example"]},
194
+ "endeavor": {"severity": "high", "suggestions": ["Effort", "Attempt", "Project", "Work"]},
195
+ "commendable": {"severity": "medium", "suggestions": ["Impressive", "Worthy", "Praiseworthy", "Admirable"]},
196
+ "intricate": {"severity": "medium", "suggestions": ["Complex", "Detailed", "Complicated", "Involved"]},
197
+ "noteworthy": {"severity": "medium", "suggestions": ["Worth noting", "Important", "Interesting", "Significant"]},
198
+ "myriad": {"severity": "high", "suggestions": ["Many", "Countless", "A wide range of", "Numerous"]},
199
+ "aforementioned": {"severity": "high", "suggestions": ["These", "Those", "The ones mentioned", "[use specific reference]"]},
200
+ "paramount": {"severity": "high", "suggestions": ["Critical", "Most important", "Top priority", "Essential"]},
201
+ "adept": {"severity": "medium", "suggestions": ["Skilled", "Good at", "Capable", "Proficient"]},
202
+ "burgeoning": {"severity": "high", "suggestions": ["Growing", "Expanding", "Rising", "Booming"]}
203
+ },
204
+ "phrases": {
205
+ "it is important to note": {"severity": "high", "suggestions": ["Worth highlighting", "A key detail here", "One thing that stands out"]},
206
+ "in today's world": {"severity": "high", "suggestions": ["These days", "Right now", "Currently", "[remove entirely]"]},
207
+ "in the realm of": {"severity": "high", "suggestions": ["In", "Within", "When it comes to", "[simplify]"]},
208
+ "plays a crucial role": {"severity": "high", "suggestions": ["Matters a lot", "Is central to", "Is key in", "Drives"]},
209
+ "it is worth noting": {"severity": "high", "suggestions": ["Notably", "Interestingly", "One thing to keep in mind"]},
210
+ "a wide range of": {"severity": "medium", "suggestions": ["Many", "Various", "Different kinds of", "All sorts of"]},
211
+ "in order to": {"severity": "medium", "suggestions": ["To", "So that", "For", "[simplify]"]},
212
+ "due to the fact that": {"severity": "high", "suggestions": ["Because", "Since", "As", "Given that"]},
213
+ "at the end of the day": {"severity": "high", "suggestions": ["Ultimately", "In the end", "When it comes down to it"]},
214
+ "on the other hand": {"severity": "medium", "suggestions": ["Then again", "But", "That said", "At the same time"]},
215
+ "in light of": {"severity": "medium", "suggestions": ["Given", "Considering", "Because of", "With"]},
216
+ "it goes without saying": {"severity": "high", "suggestions": ["Obviously", "Clearly", "Of course", "[remove entirely]"]},
217
+ "serves as a": {"severity": "medium", "suggestions": ["Acts as", "Works as", "Functions as", "Is"]},
218
+ "in conclusion": {"severity": "high", "suggestions": ["To sum up", "Taken together", "All things considered", "Looking at the bigger picture"]},
219
+ "as a result": {"severity": "medium", "suggestions": ["So", "This means", "Because of this", "That's why"]},
220
+ "in addition to": {"severity": "medium", "suggestions": ["Besides", "Along with", "On top of", "Apart from"]},
221
+ "has the potential to": {"severity": "medium", "suggestions": ["Could", "Might", "Can", "Is able to"]},
222
+ "there is no doubt that": {"severity": "high", "suggestions": ["Clearly", "Without question", "It's clear that", "[state directly]"]},
223
+ "this highlights the": {"severity": "medium", "suggestions": ["This shows", "This points to", "This makes clear"]},
224
+ "the fact that": {"severity": "medium", "suggestions": ["That", "[remove — often unnecessary]", "How"]},
225
+ "in terms of": {"severity": "medium", "suggestions": ["For", "Regarding", "When it comes to", "With"]},
226
+ "lends credence to": {"severity": "high", "suggestions": ["Supports", "Backs up", "Strengthens", "Adds weight to"]},
227
+ "is imperative that": {"severity": "high", "suggestions": ["We must", "It's critical to", "We need to", "Has to"]}
228
+ }
229
+ }
230
+ ```
231
+ 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.
232
+
233
+ - Scan the input text for all matches
234
+ - For each match, output:
235
+ ```json
236
+ {
237
+ "type": "vocabulary",
238
+ "word_or_phrase": "furthermore",
239
+ "sentence_index": 2,
240
+ "position_in_sentence": "start",
241
+ "severity": "high",
242
+ "suggestions": ["Beyond this", "What's more", "[remove transition]"]
243
+ }
244
+ ```
245
+
246
+ #### 1d. Transition Pattern Analysis
247
+ - Detect how each sentence/paragraph begins
248
+ - Flag problematic patterns:
249
+ - Sentence starts with a common transition word (Furthermore, Moreover, Additionally, However, Consequently, Nevertheless, etc.)
250
+ - Multiple consecutive sentences start the same way (e.g., "The... The... The...")
251
+ - Paragraph openings follow a predictable pattern
252
+ - For each flag, generate:
253
+ ```json
254
+ {
255
+ "type": "transition",
256
+ "sentence_index": 0,
257
+ "current_opening": "Furthermore,",
258
+ "instruction": "Remove this transition entirely and restructure the sentence to flow from the previous one. Or replace with a less formulaic connector."
259
+ }
260
+ ```
261
+
262
+ #### 1e. Sentence Opening Pattern Analysis
263
+ - Track the first 1-3 words of every sentence
264
+ - Detect repetitive patterns:
265
+ - 3+ sentences starting with "The"
266
+ - 2+ sentences starting with the same word within a paragraph
267
+ - Overly formulaic openings ("This is", "It is", "There are")
268
+ - For each pattern, generate:
269
+ ```json
270
+ {
271
+ "type": "sentence_opening",
272
+ "affected_sentences": [2, 4, 6],
273
+ "pattern": "All start with 'The'",
274
+ "instruction": "Vary the openings. Consider starting sentence 4 with an adverbial phrase, and sentence 6 with the object or a dependent clause."
275
+ }
276
+ ```
277
+
278
+ #### 1f. Structural Analysis
279
+ - Count sentences per paragraph
280
+ - Check if paragraphs are too uniform in length
281
+ - Check if the overall argument follows an overly predictable structure (claim → evidence → conclusion repeating)
282
+ - Generate structural suggestions:
283
+ ```json
284
+ {
285
+ "type": "structural",
286
+ "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."
287
+ }
288
+ ```
289
+
290
+ #### 1g. Informality Injection Points
291
+ - Identify places where a human student would naturally use:
292
+ - Contractions ("don't" vs "do not", "it's" vs "it is")
293
+ - First person ("I would argue", "In my reading of this")
294
+ - Hedging language ("arguably", "to some extent", "it seems")
295
+ - Slightly casual phrasing
296
+ - Target ~10-15% of opportunities for contraction injection
297
+ - Generate:
298
+ ```json
299
+ {
300
+ "type": "informality",
301
+ "sentence_index": 4,
302
+ "instruction": "Change 'do not' to 'don't' — natural contraction point.",
303
+ }
304
+ ```
305
+ ```json
306
+ {
307
+ "type": "informality",
308
+ "sentence_index": 7,
309
+ "instruction": "This is a good place to add a brief personal hedge like 'I would argue that' or 'In my view' at the start."
310
+ }
311
+ ```
312
+
313
+ ### COMBINED OUTPUT FORMAT
314
+
315
+ Stage 1 must produce a single JSON object called `AnalysisResult`:
316
+
317
+ ```json
318
+ {
319
+ "summary": {
320
+ "total_sentences": 12,
321
+ "high_risk_sentences": 4,
322
+ "medium_risk_sentences": 5,
323
+ "low_risk_sentences": 3,
324
+ "burstiness_cv": 0.22,
325
+ "burstiness_rating": "high_uniformity",
326
+ "ai_vocabulary_count": 8,
327
+ "transition_flags": 3,
328
+ "opening_pattern_flags": 2,
329
+ "overall_risk": "high" // "high" | "medium" | "low"
330
+ },
331
+ "instructions": [
332
+ // ALL instructions from all sub-analyzers, sorted by sentence_index
333
+ // Each instruction has: type, sentence_index, severity, instruction text
334
+ {
335
+ "type": "perplexity",
336
+ "sentence_index": 0,
337
+ "severity": "high",
338
+ "instruction": "This sentence has very low perplexity (22.4). Restructure it significantly — change the sentence structure, not just individual words."
339
+ },
340
+ {
341
+ "type": "vocabulary",
342
+ "sentence_index": 0,
343
+ "severity": "high",
344
+ "instruction": "Replace 'Furthermore' at the start. Use 'Beyond this', or remove the transition entirely."
345
+ },
346
+ {
347
+ "type": "burstiness",
348
+ "sentence_index": 2,
349
+ "severity": "medium",
350
+ "instruction": "Shorten this sentence to 8-10 words. It's currently 19 words, same as adjacent sentences."
351
+ },
352
+ // ... more instructions
353
+ ],
354
+ "banned_words": ["furthermore", "moreover", "utilize", "facilitate", ...],
355
+ // List of all AI-vocabulary words found in the text that the LLM must avoid
356
+ "sentence_perplexities": [
357
+ {"index": 0, "text": "Furthermore, artificial...", "mean_ppl": 22.4, "risk": "high"},
358
+ {"index": 1, "text": "The implementation...", "mean_ppl": 31.2, "risk": "medium"},
359
+ // ...
360
+ ]
361
+ }
362
+ ```
363
+
364
+ ### IMPLEMENTATION REQUIREMENTS FOR STAGE 1
365
+ - Must complete in **under 300ms** for 1,000 words
366
+ - Must use **NO API calls** — everything runs locally
367
+ - Load spaCy and Qwen2.5 models at application startup (not per request)
368
+ - The analysis must be **deterministic** for the same input (no randomness in analysis — randomness comes from prompt rotation in Stage 2)
369
+ - Write comprehensive unit tests for each sub-analyzer
370
+ - Every function must have docstrings and type hints
371
+
372
+ ---
373
+
374
+ ## STAGE 2: GUIDED LLM REWRITE
375
+
376
+ ### PURPOSE
377
+ 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.
378
+
379
+ ### LLM SELECTION
380
+ - Primary: **Anthropic Claude Sonnet** (`claude-sonnet-4-20250514`)
381
+ - Fallback: **OpenAI GPT-4o-mini** (`gpt-4o-mini`)
382
+ - Do NOT use reasoning models (o1, o3) — too slow, too expensive
383
+ - Do NOT use small/cheap models (GPT-3.5) — quality too low
384
+
385
+ ### PROMPT ENGINEERING
386
+
387
+ Create a **prompt manager** class that:
388
+ - Stores **at least 8-10 system prompt variants** — rotate randomly per request
389
+ - Each variant instructs the same core behavior but with different phrasing and emphasis
390
+ - NEVER use the same prompt for consecutive requests
391
+ - Log which variant was used per request (for future optimization)
392
+
393
+ ### SYSTEM PROMPT STRUCTURE
394
+
395
+ Every prompt variant must follow this structure:
396
+
397
+ ```
398
+ [ROLE DEFINITION]
399
+ You are a university student revising your own essay draft. You write confidently
400
+ and naturally. You're not rewriting someone else's work — this is YOUR essay and
401
+ you're improving it based on feedback.
402
+
403
+ [CORE RULES - these are NON-NEGOTIABLE in every variant]
404
+ 1. Follow EVERY instruction in the ANALYSIS section below. These are specific
405
+ changes you must make.
406
+ 2. For sentences NOT mentioned in the instructions, keep them as close to the
407
+ original wording as possible. Only make minimal changes for flow.
408
+ 3. NEVER use any word from the BANNED WORDS list.
409
+ 4. Preserve ALL factual content, arguments, and meaning exactly.
410
+ 5. STRICT LENGTH: Output must be between 100% and 135% of the input word count.
411
+ Input is approximately {word_count} words. Your output MUST be {word_count}
412
+ to {max_words} words. Do NOT exceed {hard_max} words under any circumstances.
413
+ 6. Do NOT add new examples, elaborations, or content not in the original.
414
+ 7. Do NOT add meta-commentary ("In this essay", "As discussed above").
415
+ 8. Write naturally — use occasional contractions, vary your rhythm, be direct.
416
+
417
+ [ANALYSIS - Stage 1's instruction set goes here]
418
+ {analysis_json}
419
+
420
+ [BANNED WORDS - never use these]
421
+ {banned_words_list}
422
+
423
+ [ORIGINAL TEXT TO REVISE]
424
+ {original_text}
425
+
426
+ [OUTPUT]
427
+ Write ONLY the revised text. No explanations, no commentary, no preamble.
428
+ ```
429
+
430
+ ### PROMPT VARIANT DIFFERENTIATION
431
+
432
+ Each of the 8-10 variants should differ in:
433
+ - **Role framing**: "university student revising your draft" vs "thoughtful student polishing your assignment" vs "confident undergrad cleaning up your paper"
434
+ - **Emphasis priorities**: One variant emphasizes naturalness, another emphasizes directness, another emphasizes varying rhythm
435
+ - **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"
436
+ - **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"
437
+
438
+ The CORE RULES must be identical across all variants. Only the framing and emphasis differ.
439
+
440
+ ### HOW TO FORMAT STAGE 1 INSTRUCTIONS FOR THE LLM
441
+
442
+ Convert the Stage 1 JSON into human-readable instructions grouped by sentence:
443
+
444
+ ```
445
+ ANALYSIS — Changes Required:
446
+
447
+ SENTENCE 1: "Furthermore, artificial intelligence has demonstrated remarkable capabilities..."
448
+ - ❌ Remove transition "Furthermore" — use a natural connector or remove entirely
449
+ - ❌ "demonstrated" and "remarkable" and "capabilities" are flagged AI words — replace them
450
+ - ⚠️ This sentence has very low perplexity (22.4) — restructure it significantly
451
+
452
+ SENTENCE 2: "The implementation of sophisticated algorithms enables..."
453
+ - ❌ "implementation", "sophisticated" are flagged AI words — use simpler alternatives
454
+ - ⚠️ Moderate perplexity (31.2) — make some changes but doesn't need full restructuring
455
+
456
+ SENTENCE 3: "Additionally, these systems facilitate proactive intervention strategies."
457
+ - ❌ Remove transition "Additionally"
458
+ - ❌ "facilitate" is a flagged AI word — replace it
459
+ - 📏 SHORTEN this sentence to 8-10 words (currently 8 — similar to sentence 2, need variation)
460
+
461
+ OVERALL:
462
+ - 📏 Sentences are too uniform in length (CV: 0.22). Vary significantly.
463
+ - Use contractions in sentences 2 and 5 where natural
464
+ - Consider adding "I think" or "I would argue" before the claim in sentence 4
465
+
466
+ BANNED WORDS (never use these): furthermore, moreover, additionally, demonstrate,
467
+ remarkable, sophisticated, facilitate, unprecedented, comprehensive, paradigm, ...
468
+ ```
469
+
470
+ ### LLM CALL CONFIGURATION
471
+ ```python
472
+ # For Claude Sonnet
473
+ {
474
+ "model": "claude-sonnet-4-20250514",
475
+ "max_tokens": calculated_dynamically, # input_word_count * 1.4 * 1.5 (tokens ratio + buffer)
476
+ "temperature": 0.85, # Higher than default for variation
477
+ "top_p": 0.9,
478
+ }
479
+
480
+ # For GPT-4o-mini (fallback)
481
+ {
482
+ "model": "gpt-4o-mini",
483
+ "max_tokens": calculated_dynamically,
484
+ "temperature": 0.85,
485
+ "top_p": 0.9,
486
+ }
487
+ ```
488
+
489
+ ### CRITICAL CONSTRAINTS
490
+ - **Only ONE LLM call per request.** No multi-pass. No chain-of-thought. No retry loops.
491
+ - Dynamic `max_tokens`: `input_word_count * 1.4 * 1.5` (expansion allowance × token ratio)
492
+ - 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)
493
+ - If primary LLM fails, try fallback LLM before returning error
494
+
495
+ ---
496
+
497
+ ## STAGE 3: POST-VALIDATION & MICRO-CORRECTIONS
498
+
499
+ ### PURPOSE
500
+ Verify the output quality, check that the LLM followed instructions, and make final corrections. No API calls.
501
+
502
+ ### WHAT TO BUILD
503
+
504
+ #### 3a. Length Validation & Enforcement
505
+ - Count output word count vs input word count
506
+ - Calculate expansion percentage
507
+ - If expansion exceeds 40%:
508
+ - Identify and remove any elaborations or examples not in the original (compare against original sentences using basic similarity scoring)
509
+ - Trim redundant phrases
510
+ - If still too long, truncate from the end of the least essential paragraph
511
+ - If output is shorter than 90% of input, flag as warning
512
+
513
+ #### 3b. Instruction Compliance Check
514
+ - Check if banned words appear in the output
515
+ - If any banned words found, apply simple regex-based replacement using suggestions from the vocabulary database
516
+ - This is a LOCAL fix — no API call needed
517
+ - Log which banned words the LLM failed to avoid (useful for prompt tuning)
518
+ - Check if flagged transitions were actually removed
519
+ - These are lightweight string-matching checks
520
+
521
+ #### 3c. Perplexity Re-scoring (Optional but Recommended)
522
+ - Run the output through the same Qwen2.5 perplexity scorer from Stage 1
523
+ - Compare the perplexity distribution of input vs output
524
+ - If output still has too many low-perplexity sentences, apply local synonym substitutions to the worst offenders:
525
+ - Look up the lowest-perplexity tokens
526
+ - Check if they have entries in the synonym bank
527
+ - Replace with a random suggestion
528
+ - This is a lightweight local fix, no API needed
529
+ - This step is optional because it adds ~200ms. Can be skipped in "fast mode" or enabled in "thorough mode"
530
+
531
+ #### 3d. Quality Checks
532
+ - Run grammar check using `language_tool_python`
533
+ - Fix any obvious grammar errors
534
+ - Verify key named entities are preserved (compare NER between input and output using spaCy)
535
+ - Verify no content was hallucinated (all proper nouns in output should exist in input)
536
+
537
+ #### 3e. Final Statistics
538
+ Return alongside the output:
539
+ ```json
540
+ {
541
+ "output_text": "...",
542
+ "stats": {
543
+ "input_word_count": 1000,
544
+ "output_word_count": 1250,
545
+ "expansion_percentage": 25.0,
546
+ "input_avg_perplexity": 28.5,
547
+ "output_avg_perplexity": 52.3,
548
+ "input_burstiness_cv": 0.22,
549
+ "output_burstiness_cv": 0.48,
550
+ "banned_words_found_in_output": ["demonstrate"],
551
+ "banned_words_auto_fixed": 1,
552
+ "instructions_generated": 14,
553
+ "high_risk_sentences": 4,
554
+ "processing_time_ms": 4500,
555
+ "stage1_time_ms": 180,
556
+ "stage2_time_ms": 4100,
557
+ "stage3_time_ms": 150,
558
+ "prompt_variant_used": "variant_3",
559
+ "llm_used": "claude-sonnet"
560
+ }
561
+ }
562
+ ```
563
+
564
+ ---
565
+
566
+ ## BACKEND ARCHITECTURE
567
+
568
+ ### Tech Stack
569
+ - **Python 3.11+**
570
+ - **FastAPI** (async)
571
+ - **uvicorn** with workers (1-2 workers due to model memory)
572
+ - **httpx** (async HTTP client for LLM API calls)
573
+ - **spaCy** (`en_core_web_sm`)
574
+ - **transformers** (Qwen2.5-0.5B for perplexity scoring — load once at startup, ~1.1GB RAM)
575
+ - **language_tool_python** (grammar checking)
576
+ - **Docker** for deployment
577
+
578
+ ### Project Structure
579
+ ```
580
+ humanization-engine/
581
+ ├── app/
582
+ │ ├── main.py # FastAPI app, lifespan events, CORS
583
+ │ ├── config.py # All configuration, environment variables
584
+ │ ├── api/
585
+ │ │ ├── routes.py # API endpoints
586
+ │ │ └── models.py # Pydantic request/response models
587
+ │ ├── core/
588
+ │ │ ├── pipeline.py # Main orchestrator (Stage 1 → 2 → 3)
589
+ │ │ ├── analyzer.py # STAGE 1 — Main TextAnalyzer class
590
+ │ │ ├── analyzers/
591
+ │ │ │ ├── perplexity.py # Qwen2.5 perplexity scoring + heuristic pre-filter
592
+ │ │ │ ├── burstiness.py # Sentence length uniformity analysis
593
+ │ │ │ ├── vocabulary.py # AI vocabulary detection
594
+ │ │ │ ├── transitions.py # Transition pattern detection
595
+ │ │ │ ├── openings.py # Sentence opening pattern detection
596
+ │ │ │ ├── structure.py # Paragraph/structural analysis
597
+ │ │ │ └── informality.py # Informality injection point detection
598
+ │ │ ├── llm_rewriter.py # STAGE 2 — Guided LLM rewrite
599
+ │ │ ├── prompt_manager.py # Prompt variant storage and rotation
600
+ │ │ ├── post_validator.py # STAGE 3 — Validation & corrections
601
+ │ │ └── perplexity_scorer.py # Qwen2.5 model wrapper (shared between stages)
602
+ │ ├── prompts/
603
+ │ │ └── variants.py # All 8-10 prompt template variants
604
+ │ ├── data/
605
+ │ │ ├── ai_vocabulary.json # AI-overused words/phrases with suggestions
606
+ │ │ ├── transition_words.json # Transition words/phrases to flag
607
+ │ │ └── heuristic_patterns.json # Patterns for the pre-filter
608
+ │ └── utils/
609
+ │ ├── text_utils.py # Word counting, sentence splitting, etc.
610
+ │ └── token_utils.py # Token counting, max_tokens calculation
611
+ ├── frontend/
612
+ │ └── index.html # Simple single-page frontend
613
+ ├── tests/
614
+ │ ├── test_analyzer.py # Tests for Stage 1
615
+ │ ├── test_analyzers/ # Tests for each individual analyzer
616
+ │ │ ├── test_perplexity.py
617
+ │ │ ├── test_burstiness.py
618
+ │ │ ├── test_vocabulary.py
619
+ │ │ ├── test_transitions.py
620
+ │ │ ├── test_openings.py
621
+ │ │ ├── test_structure.py
622
+ │ │ └── test_informality.py
623
+ │ ├── test_llm_rewriter.py
624
+ │ ├── test_post_validator.py
625
+ │ ├── test_pipeline.py
626
+ │ └── test_api.py
627
+ ├── Dockerfile
628
+ ├── docker-compose.yml
629
+ ├── requirements.txt
630
+ ├── .env.example
631
+ └── README.md
632
+ ```
633
+
634
+ ### API Endpoints
635
+
636
+ #### POST /humanize
637
+ Main endpoint.
638
+ ```
639
+ Request:
640
+ {
641
+ "text": "string (required, 50-5000 words)",
642
+ "mode": "standard" | "thorough" (optional, default "standard")
643
+ // "thorough" enables Stage 3 perplexity re-scoring
644
+ }
645
+
646
+ Response:
647
+ {
648
+ "success": true,
649
+ "output_text": "string",
650
+ "stats": { ... } // as defined in Stage 3e
651
+ }
652
+
653
+ Error Response:
654
+ {
655
+ "success": false,
656
+ "error": "string",
657
+ "code": "INPUT_TOO_SHORT" | "INPUT_TOO_LONG" | "LLM_TIMEOUT" | "PROCESSING_ERROR"
658
+ }
659
+ ```
660
+
661
+ #### POST /analyze
662
+ Debug/testing endpoint — returns ONLY the Stage 1 analysis without calling the LLM. Useful for testing and tuning the analyzer.
663
+ ```
664
+ Request:
665
+ {
666
+ "text": "string"
667
+ }
668
+
669
+ Response:
670
+ {
671
+ "success": true,
672
+ "analysis": { ... } // The full AnalysisResult JSON from Stage 1
673
+ }
674
+ ```
675
+
676
+ #### GET /health
677
+ ```
678
+ Response:
679
+ {
680
+ "status": "healthy",
681
+ "models_loaded": true,
682
+ "uptime_seconds": 3600
683
+ }
684
+ ```
685
+
686
+ ### Startup / Lifespan Events
687
+ Using FastAPI's lifespan context manager:
688
+ 1. Load spaCy model (`en_core_web_sm`) into memory
689
+ 2. Load Qwen2.5-0.5B model and tokenizer into memory (~1.1GB RAM, `torch_dtype=torch.float32`, `device_map="cpu"`)
690
+ 3. Load AI vocabulary database, transition words, heuristic patterns into memory
691
+ 4. Initialize language_tool_python
692
+ 5. Warm up Qwen2.5 with a dummy inference (first inference is always slower)
693
+ 6. Log successful initialization with memory usage
694
+
695
+ ### Error Handling
696
+ - All stages must have try/except blocks
697
+ - If Stage 1 fails: log error, send text to LLM with a generic instruction set (basic "rewrite as student" prompt without specific analysis)
698
+ - If Stage 2 primary LLM fails: try fallback LLM
699
+ - If both LLMs fail: return original text with error flag
700
+ - If Stage 3 fails: log error, return Stage 2 output without validation
701
+ - Never return a 500 error to the user — always return gracefully degraded output
702
+
703
+ ### Environment Variables
704
+ ```
705
+ ANTHROPIC_API_KEY=sk-ant-...
706
+ OPENAI_API_KEY=sk-...
707
+ PRIMARY_LLM=claude # "claude" or "openai"
708
+ MAX_INPUT_WORDS=5000
709
+ MIN_INPUT_WORDS=50
710
+ MAX_EXPANSION_PERCENT=40
711
+ LLM_TIMEOUT_SECONDS=8
712
+ WORKERS=1
713
+ PORT=8000
714
+ LOG_LEVEL=INFO
715
+ THOROUGH_MODE_DEFAULT=false # Enable Stage 3 perplexity re-scoring by default
716
+ ```
717
+
718
+ ---
719
+
720
+ ## FRONTEND
721
+
722
+ Build a simple, clean single-page frontend in **plain HTML + CSS + JavaScript** (no framework needed).
723
+
724
+ ### Requirements:
725
+ - Clean, modern dark-themed UI
726
+ - Large text input area (left side or top)
727
+ - "Humanize" button with mode toggle (Standard / Thorough)
728
+ - Output text area (right side or bottom)
729
+ - Loading spinner during processing
730
+ - Display stats after processing:
731
+ - Word counts (input/output)
732
+ - Expansion percentage
733
+ - Perplexity improvement (input avg → output avg)
734
+ - Burstiness improvement (input CV → output CV)
735
+ - Number of instructions generated
736
+ - Processing time breakdown (Stage 1 / Stage 2 / Stage 3)
737
+ - Which LLM was used
738
+ - Banned words that were auto-fixed
739
+ - Copy-to-clipboard button for output
740
+ - Character/word count on input area
741
+ - Error messages displayed cleanly
742
+ - Mobile responsive
743
+ - **"Show Analysis" toggle** — allows user to see the raw Stage 1 analysis JSON (useful for debugging and client demos)
744
+ - Serve from FastAPI as a static file
745
+
746
+ ---
747
+
748
+ ## PERFORMANCE REQUIREMENTS
749
+ - 1,000 words must complete end-to-end in **under 10 seconds**
750
+ - Stage 1 (Analysis): under 300ms
751
+ - Stage 2 (LLM call): under 7 seconds
752
+ - Stage 3 (Validation): under 200ms (under 400ms in thorough mode with perplexity re-scoring)
753
+ - System must handle 17 concurrent requests per minute
754
+ - Use async/await throughout
755
+ - Pre-load all models at startup
756
+
757
+ ## COST REQUIREMENTS
758
+ - Target under **$1 per 100,000 words** processed
759
+ - Enforce strict `max_tokens` on every LLM call
760
+ - Never make more than 1 LLM call per request
761
+ - Use cost-efficient models (Sonnet, GPT-4o-mini)
762
+
763
+ ---
764
+
765
+ ## DOCKER DEPLOYMENT
766
+
767
+ ```dockerfile
768
+ FROM python:3.11-slim
769
+
770
+ RUN apt-get update && apt-get install -y \
771
+ build-essential \
772
+ && rm -rf /var/lib/apt/lists/*
773
+
774
+ WORKDIR /app
775
+
776
+ COPY requirements.txt .
777
+ RUN pip install --no-cache-dir -r requirements.txt
778
+
779
+ # Pre-download Qwen2.5-0.5B during build (avoids 1GB download on every container start)
780
+ RUN python -c "from transformers import AutoModelForCausalLM, AutoTokenizer; \
781
+ AutoModelForCausalLM.from_pretrained('Qwen/Qwen2.5-0.5B'); \
782
+ AutoTokenizer.from_pretrained('Qwen/Qwen2.5-0.5B')"
783
+
784
+ # Pre-download spaCy model
785
+ RUN python -m spacy download en_core_web_sm
786
+
787
+ COPY . .
788
+
789
+ # Single worker due to model memory (~1.1GB per worker)
790
+ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"]
791
+ ```
792
+
793
+ **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`.
794
+
795
+ **Memory optimization — share models across async requests:**
796
+ ```python
797
+ from contextlib import asynccontextmanager
798
+
799
+ perplexity_scorer = None
800
+ nlp = None
801
+
802
+ @asynccontextmanager
803
+ async def lifespan(app: FastAPI):
804
+ global perplexity_scorer, nlp
805
+ perplexity_scorer = PerplexityScorer() # Qwen2.5-0.5B, ~1.1GB
806
+ nlp = spacy.load("en_core_web_sm") # ~50MB
807
+ yield
808
+ del perplexity_scorer, nlp
809
+
810
+ app = FastAPI(lifespan=lifespan)
811
+ ```
812
+
813
+ ---
814
+
815
+ ## BUILD ORDER (Follow this sequence strictly)
816
+
817
+ ### Step 1: Project Setup
818
+ - Initialize project structure exactly as defined above
819
+ - Create requirements.txt with all dependencies:
820
+ ```
821
+ fastapi>=0.104.0
822
+ uvicorn>=0.24.0
823
+ httpx>=0.25.0
824
+ torch>=2.1.0
825
+ transformers>=4.36.0
826
+ accelerate>=0.25.0
827
+ spacy>=3.7.0
828
+ language-tool-python>=2.7.0
829
+ python-dotenv>=1.0.0
830
+ pydantic>=2.5.0
831
+ ```
832
+ - Create .env.example
833
+ - Create config.py with all settings loaded from environment variables
834
+ - Create Pydantic models for request/response in models.py
835
+
836
+ ### Step 2: Utility Functions
837
+ - Build text_utils.py:
838
+ - `count_words(text: str) -> int`
839
+ - `split_sentences(text: str) -> list[str]` (use spaCy)
840
+ - `calculate_burstiness(sentence_lengths: list[int]) -> dict` (mean, std, CV)
841
+ - `calculate_expansion_percentage(input_count: int, output_count: int) -> float`
842
+ - Build token_utils.py:
843
+ - `count_tokens(text: str, model: str) -> int` (approximate — use word_count * 1.4)
844
+ - `calculate_max_tokens(input_word_count: int, max_expansion: float) -> int`
845
+ - Build perplexity_scorer.py:
846
+ - `PerplexityScorer` class with Qwen2.5-0.5B
847
+ - `score_text(text: str) -> PerplexityResult`
848
+ - `score_sentence(sentence: str) -> SentencePerplexityResult`
849
+ - `score_sentences(sentences: list[str]) -> list[SentencePerplexityResult]`
850
+ - Include the heuristic pre-filter as a method
851
+
852
+ ### Step 3: Stage 1 — Individual Analyzers
853
+ Build each analyzer in `app/core/analyzers/` one at a time:
854
+ 1. `perplexity.py` — PerplexityAnalyzer
855
+ 2. `burstiness.py` — BurstinessAnalyzer
856
+ 3. `vocabulary.py` — VocabularyAnalyzer (loads ai_vocabulary.json)
857
+ 4. `transitions.py` — TransitionAnalyzer
858
+ 5. `openings.py` — OpeningPatternAnalyzer
859
+ 6. `structure.py` — StructuralAnalyzer
860
+ 7. `informality.py` — InformalityAnalyzer
861
+
862
+ Each analyzer must:
863
+ - Accept text (and optionally parsed spaCy doc) as input
864
+ - Return a list of instruction dicts following the format specified in Stage 1
865
+ - Have its own unit test file
866
+ - Complete in under 50ms individually (except perplexity which gets 200ms)
867
+
868
+ Then build `analyzer.py` — the main `TextAnalyzer` class that:
869
+ - Runs all sub-analyzers
870
+ - Combines their outputs into the unified `AnalysisResult` format
871
+ - Sorts instructions by sentence_index
872
+ - Compiles the banned_words list
873
+ - Generates the summary
874
+
875
+ ### Step 4: Data Files
876
+ - Create `ai_vocabulary.json` with 80-100+ entries (use the structure defined in section 1c, expand significantly beyond the examples given)
877
+ - Create `transition_words.json` with all common academic transitions
878
+ - Create `heuristic_patterns.json` with patterns for the perplexity pre-filter
879
+
880
+ ### Step 5: Stage 2 — Guided LLM Rewriter
881
+ - Build `prompt_manager.py`:
882
+ - Store 8-10 prompt variants
883
+ - Random rotation with no consecutive repeats
884
+ - Method to format Stage 1 analysis into human-readable instructions for the LLM
885
+ - Logging of which variant was used
886
+ - Build `llm_rewriter.py`:
887
+ - Async LLM calling with httpx
888
+ - Support for Claude Sonnet (primary) and GPT-4o-mini (fallback)
889
+ - Dynamic max_tokens calculation
890
+ - Timeout handling (8 seconds)
891
+ - Fallback logic: Claude → OpenAI → return original with error
892
+ - Response parsing and cleaning
893
+
894
+ ### Step 6: Stage 3 — Post Validator
895
+ - Build `post_validator.py`:
896
+ - Length validation and smart trimming
897
+ - Banned word checking and auto-replacement
898
+ - Grammar checking with language_tool_python
899
+ - Entity preservation checking (NER comparison)
900
+ - Optional perplexity re-scoring (thorough mode)
901
+ - Stats aggregation
902
+
903
+ ### Step 7: Pipeline Orchestrator
904
+ - Build `pipeline.py`:
905
+ - Wire all 3 stages together
906
+ - Add timing measurements for each stage
907
+ - Add comprehensive error handling with fallback logic
908
+ - Support for "standard" and "thorough" modes
909
+
910
+ ### Step 8: API Layer
911
+ - Build FastAPI endpoints in routes.py:
912
+ - POST /humanize
913
+ - POST /analyze (debug endpoint)
914
+ - GET /health
915
+ - Add CORS middleware (allow all origins for development)
916
+ - Add input validation (min/max word count)
917
+ - Add request logging
918
+ - Add simple in-memory rate limiting
919
+
920
+ ### Step 9: Frontend
921
+ - Build index.html with all features specified above
922
+ - Clean, dark-themed design
923
+ - Connect to API endpoints
924
+ - Test end-to-end
925
+
926
+ ### Step 10: Docker
927
+ - Create Dockerfile as specified
928
+ - Create docker-compose.yml
929
+ - Test containerized deployment
930
+
931
+ ### Step 11: Testing & Tuning
932
+ - Write and run all unit tests
933
+ - Test with sample AI-generated texts (use the examples provided below)
934
+ - Test the /analyze endpoint to verify Stage 1 generates sensible instructions
935
+ - Measure processing times per stage
936
+ - Verify expansion percentages stay under 40%
937
+ - Test error handling (LLM timeout, invalid input, etc.)
938
+
939
+ ---
940
+
941
+ ## SAMPLE TEST INPUTS
942
+
943
+ **Test Input 1 (Healthcare):**
944
+ "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."
945
+
946
+ **Test Input 2 (Climate):**
947
+ "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."
948
+
949
+ **Test Input 3 (Education):**
950
+ "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."
951
+
952
+ For each test input, verify:
953
+ 1. Stage 1 generates specific, actionable instructions (check via /analyze endpoint)
954
+ 2. The final output reads naturally and sounds like a real student
955
+ 3. Expansion stays under 40%
956
+ 4. No banned words remain in the output
957
+ 5. All factual content is preserved
958
+
959
+ ---
960
+
961
+ ## IMPORTANT REMINDERS
962
+ - The analysis engine (Stage 1) is the MOST CRITICAL component. It drives everything.
963
+ - Stage 1 does NOT modify text. It generates INSTRUCTIONS. This is the key architectural difference.
964
+ - The LLM (Stage 2) must be given the ORIGINAL text plus the instructions. Not a modified version.
965
+ - Meaning preservation is NON-NEGOTIABLE. Never distort facts or arguments.
966
+ - The AI vocabulary database must be EXTENSIVE and CAREFULLY CURATED. This directly affects accuracy.
967
+ - Test with diverse inputs: short paragraphs, long essays, technical content, humanities content.
968
+ - Every function should have docstrings and type hints.
969
+ - Handle edge cases: very short input, very long input, special characters, code snippets, citations.
970
+ - The /analyze endpoint is crucial for debugging — use it frequently during development.
971
+
972
+ ---
973
+
974
+ Now begin building. Start with Step 1 and proceed sequentially. Ask me if anything is unclear before starting a step.
app/__init__.py ADDED
File without changes
app/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (145 Bytes). View file
 
app/api/__init__.py ADDED
File without changes
app/api/models.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pydantic request/response models for the Humanization Engine API.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import Any, Literal, Optional
8
+
9
+ from pydantic import BaseModel, Field, field_validator
10
+
11
+
12
+ # ---------------------------------------------------------------------------
13
+ # Request models
14
+ # ---------------------------------------------------------------------------
15
+
16
+
17
+ class HumanizeRequest(BaseModel):
18
+ """POST /humanize request body."""
19
+
20
+ text: str = Field(
21
+ ...,
22
+ description="The AI-generated text to humanize (50–5000 words)",
23
+ min_length=10,
24
+ )
25
+ mode: Literal["standard", "thorough"] = Field(
26
+ default="standard",
27
+ description=(
28
+ "'standard' skips Stage 3 perplexity re-scoring; "
29
+ "'thorough' enables it for a better result at ~200ms extra cost"
30
+ ),
31
+ )
32
+
33
+ @field_validator("text")
34
+ @classmethod
35
+ def text_must_not_be_blank(cls, v: str) -> str:
36
+ """Reject whitespace-only input."""
37
+ if not v.strip():
38
+ raise ValueError("text must not be blank")
39
+ return v
40
+
41
+
42
+ class AnalyzeRequest(BaseModel):
43
+ """POST /analyze request body."""
44
+
45
+ text: str = Field(
46
+ ...,
47
+ description="The text to analyse (returns Stage 1 analysis without LLM rewrite)",
48
+ min_length=10,
49
+ )
50
+
51
+ @field_validator("text")
52
+ @classmethod
53
+ def text_must_not_be_blank(cls, v: str) -> str:
54
+ if not v.strip():
55
+ raise ValueError("text must not be blank")
56
+ return v
57
+
58
+
59
+ # ---------------------------------------------------------------------------
60
+ # Shared sub-models
61
+ # ---------------------------------------------------------------------------
62
+
63
+
64
+ class ProcessingStats(BaseModel):
65
+ """Processing statistics returned with every successful /humanize response."""
66
+
67
+ input_word_count: int
68
+ output_word_count: int
69
+ expansion_percentage: float
70
+ input_avg_perplexity: Optional[float] = None
71
+ output_avg_perplexity: Optional[float] = None
72
+ input_burstiness_cv: Optional[float] = None
73
+ output_burstiness_cv: Optional[float] = None
74
+ banned_words_found_in_output: list[str] = Field(default_factory=list)
75
+ banned_words_auto_fixed: int = 0
76
+ instructions_generated: int = 0
77
+ high_risk_sentences: int = 0
78
+ processing_time_ms: float = 0.0
79
+ stage1_time_ms: float = 0.0
80
+ stage2_time_ms: float = 0.0
81
+ stage3_time_ms: float = 0.0
82
+ prompt_variant_used: str = ""
83
+ llm_used: str = ""
84
+
85
+
86
+ # ---------------------------------------------------------------------------
87
+ # Response models
88
+ # ---------------------------------------------------------------------------
89
+
90
+
91
+ class HumanizeResponse(BaseModel):
92
+ """POST /humanize success response."""
93
+
94
+ success: Literal[True] = True
95
+ output_text: str
96
+ stats: ProcessingStats
97
+
98
+
99
+ class HumanizeErrorResponse(BaseModel):
100
+ """POST /humanize error response."""
101
+
102
+ success: Literal[False] = False
103
+ error: str
104
+ code: Literal[
105
+ "INPUT_TOO_SHORT",
106
+ "INPUT_TOO_LONG",
107
+ "LLM_TIMEOUT",
108
+ "PROCESSING_ERROR",
109
+ "INVALID_INPUT",
110
+ ]
111
+
112
+
113
+ class AnalyzeResponse(BaseModel):
114
+ """POST /analyze success response."""
115
+
116
+ success: Literal[True] = True
117
+ analysis: dict[str, Any]
118
+
119
+
120
+ class AnalyzeErrorResponse(BaseModel):
121
+ """POST /analyze error response."""
122
+
123
+ success: Literal[False] = False
124
+ error: str
125
+ code: str
126
+
127
+
128
+ class HealthResponse(BaseModel):
129
+ """GET /health response."""
130
+
131
+ status: Literal["healthy", "degraded", "starting"]
132
+ models_loaded: bool
133
+ uptime_seconds: float
app/api/routes.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ API route definitions — skeleton filled in during Step 8.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from fastapi import APIRouter
8
+
9
+ router = APIRouter()
10
+
11
+ # Routes are added in Step 8 of the build order.
12
+ # This stub allows main.py to import cleanly from the start.
app/config.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Application configuration loaded from environment variables.
3
+ All settings are centralised here; nothing else should read os.environ directly.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ from functools import lru_cache
10
+ from typing import Literal
11
+
12
+ from pydantic import Field
13
+ from pydantic_settings import BaseSettings, SettingsConfigDict
14
+
15
+
16
+ class Settings(BaseSettings):
17
+ """All application configuration, loaded from .env or environment."""
18
+
19
+ model_config = SettingsConfigDict(
20
+ env_file=".env",
21
+ env_file_encoding="utf-8",
22
+ case_sensitive=False,
23
+ extra="ignore",
24
+ )
25
+
26
+ # --- LLM credentials ---
27
+ anthropic_api_key: str = Field(default="", description="Anthropic API key")
28
+ openai_api_key: str = Field(default="", description="OpenAI API key")
29
+ primary_llm: Literal["claude", "openai"] = Field(
30
+ default="claude",
31
+ description="Which LLM to use as primary: 'claude' or 'openai'",
32
+ )
33
+
34
+ # --- Input constraints ---
35
+ max_input_words: int = Field(default=5000, ge=1)
36
+ min_input_words: int = Field(default=50, ge=1)
37
+
38
+ # --- Output constraints ---
39
+ max_expansion_percent: float = Field(default=40.0, ge=0.0, le=200.0)
40
+
41
+ # --- LLM call settings ---
42
+ llm_timeout_seconds: float = Field(default=8.0, gt=0.0)
43
+
44
+ # --- Server settings ---
45
+ workers: int = Field(default=1, ge=1)
46
+ port: int = Field(default=8000, ge=1, le=65535)
47
+ log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = Field(
48
+ default="INFO"
49
+ )
50
+
51
+ # --- Processing modes ---
52
+ thorough_mode_default: bool = Field(
53
+ default=False,
54
+ description="Enable Stage 3 perplexity re-scoring by default",
55
+ )
56
+
57
+ # --- Model identifiers ---
58
+ claude_model: str = Field(default="claude-sonnet-4-20250514")
59
+ openai_model: str = Field(default="gpt-4o-mini")
60
+
61
+ # --- Local model settings ---
62
+ qwen_model_id: str = Field(default="Qwen/Qwen2.5-0.5B")
63
+ spacy_model: str = Field(default="en_core_web_sm")
64
+
65
+ # --- Perplexity thresholds ---
66
+ perplexity_high_risk_threshold: float = Field(
67
+ default=30.0,
68
+ description="Sentences with mean perplexity below this are 'high_risk'",
69
+ )
70
+ perplexity_medium_risk_threshold: float = Field(
71
+ default=60.0,
72
+ description="Sentences with mean perplexity below this (and above high) are 'medium_risk'",
73
+ )
74
+
75
+ # --- Burstiness thresholds ---
76
+ burstiness_high_uniformity_cv: float = Field(
77
+ default=0.30,
78
+ description="CV below this → 'high_uniformity'",
79
+ )
80
+ burstiness_moderate_uniformity_cv: float = Field(
81
+ default=0.45,
82
+ description="CV below this (and above high) → 'moderate_uniformity'",
83
+ )
84
+
85
+ # --- Data file paths (relative to project root) ---
86
+ ai_vocabulary_path: str = Field(default="app/data/ai_vocabulary.json")
87
+ transition_words_path: str = Field(default="app/data/transition_words.json")
88
+ heuristic_patterns_path: str = Field(default="app/data/heuristic_patterns.json")
89
+
90
+
91
+ @lru_cache(maxsize=1)
92
+ def get_settings() -> Settings:
93
+ """Return a cached Settings instance (singleton)."""
94
+ return Settings()
app/core/__init__.py ADDED
File without changes
app/core/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (150 Bytes). View file
 
app/core/__pycache__/analyzer.cpython-313.pyc ADDED
Binary file (9.78 kB). View file
 
app/core/__pycache__/perplexity_scorer.cpython-313.pyc ADDED
Binary file (11.6 kB). View file
 
app/core/analyzer.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ TextAnalyzer — Stage 1 main orchestrator.
3
+
4
+ Runs all sub-analyzers, combines their outputs into the unified AnalysisResult
5
+ format, sorts instructions by sentence_index, compiles the banned_words list,
6
+ and generates the summary.
7
+
8
+ This class does NOT modify the input text. It produces a structured
9
+ instruction set (JSON-serialisable dict) that Stage 2 uses to guide the LLM.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ import time
16
+ from typing import Any, TYPE_CHECKING
17
+
18
+ from app.utils.text_utils import (
19
+ count_words,
20
+ split_sentences,
21
+ sentence_word_counts,
22
+ calculate_burstiness,
23
+ )
24
+ from app.core.analyzers.burstiness import BurstinessAnalyzer
25
+ from app.core.analyzers.vocabulary import VocabularyAnalyzer
26
+ from app.core.analyzers.transitions import TransitionAnalyzer
27
+ from app.core.analyzers.openings import OpeningPatternAnalyzer
28
+ from app.core.analyzers.structure import StructuralAnalyzer
29
+ from app.core.analyzers.informality import InformalityAnalyzer
30
+ from app.core.analyzers.perplexity import PerplexityAnalyzer
31
+
32
+ if TYPE_CHECKING:
33
+ import spacy # type: ignore
34
+ from app.core.perplexity_scorer import PerplexityScorer
35
+
36
+ logger = logging.getLogger(__name__)
37
+
38
+
39
+ class TextAnalyzer:
40
+ """Orchestrates all Stage 1 sub-analyzers.
41
+
42
+ A single instance is created at application startup and reused for every
43
+ request. Heavy resources (spaCy, Qwen2.5) are injected via the constructor
44
+ so they are loaded only once.
45
+
46
+ Args:
47
+ nlp: Loaded spaCy Language model (or None — fallback to regex).
48
+ perplexity_scorer: Loaded PerplexityScorer (or None — perplexity analysis skipped).
49
+ vocab_path: Path to ai_vocabulary.json.
50
+ transition_path: Path to transition_words.json.
51
+ heuristic_path: Path to heuristic_patterns.json.
52
+ """
53
+
54
+ def __init__(
55
+ self,
56
+ nlp: "spacy.Language | None" = None,
57
+ perplexity_scorer: "PerplexityScorer | None" = None,
58
+ vocab_path: str = "app/data/ai_vocabulary.json",
59
+ transition_path: str = "app/data/transition_words.json",
60
+ heuristic_path: str = "app/data/heuristic_patterns.json",
61
+ ) -> None:
62
+ self.nlp = nlp
63
+
64
+ self._burstiness = BurstinessAnalyzer()
65
+ self._vocabulary = VocabularyAnalyzer(vocab_path=vocab_path)
66
+ self._transitions = TransitionAnalyzer(transition_path=transition_path)
67
+ self._openings = OpeningPatternAnalyzer()
68
+ self._structure = StructuralAnalyzer()
69
+ self._informality = InformalityAnalyzer()
70
+ self._perplexity = PerplexityAnalyzer(
71
+ scorer=perplexity_scorer,
72
+ heuristic_path=heuristic_path,
73
+ )
74
+
75
+ # ------------------------------------------------------------------
76
+ # Public API
77
+ # ------------------------------------------------------------------
78
+
79
+ def analyze(self, text: str) -> dict[str, Any]:
80
+ """Run full Stage 1 analysis on *text*.
81
+
82
+ Args:
83
+ text: The raw AI-generated text to analyse.
84
+
85
+ Returns:
86
+ AnalysisResult dict (JSON-serialisable) containing:
87
+ - summary
88
+ - instructions (all sub-analyzer outputs, sorted by sentence_index)
89
+ - banned_words
90
+ - sentence_perplexities
91
+ """
92
+ t0 = time.perf_counter()
93
+
94
+ # ---- Sentence splitting ----
95
+ sentences = split_sentences(text, nlp=self.nlp)
96
+ if not sentences:
97
+ return self._empty_result()
98
+
99
+ # ---- Run all sub-analyzers ----
100
+ burst_result = self._burstiness.analyze(sentences)
101
+ vocab_instructions = self._vocabulary.analyze(sentences)
102
+ transition_instructions = self._transitions.analyze(sentences)
103
+ opening_instructions = self._openings.analyze(sentences)
104
+ structure_instructions = self._structure.analyze(text, sentences)
105
+ informality_instructions = self._informality.analyze(sentences)
106
+ perplexity_instructions = self._perplexity.analyze(sentences)
107
+
108
+ # ---- Gather perplexity per-sentence for the summary ----
109
+ sentence_perplexities = self._build_sentence_perplexities(
110
+ sentences, perplexity_instructions
111
+ )
112
+
113
+ # ---- Combine all instructions ----
114
+ all_instructions: list[dict] = []
115
+ all_instructions.extend(perplexity_instructions)
116
+ all_instructions.extend(burst_result["instructions"])
117
+ all_instructions.extend(vocab_instructions)
118
+ all_instructions.extend(transition_instructions)
119
+ all_instructions.extend(opening_instructions)
120
+ all_instructions.extend(structure_instructions)
121
+ all_instructions.extend(informality_instructions)
122
+
123
+ # Sort by sentence_index (structural instructions may have None → put at end)
124
+ all_instructions.sort(
125
+ key=lambda x: (x.get("sentence_index") is None, x.get("sentence_index", 999))
126
+ )
127
+
128
+ # ---- Banned words ----
129
+ banned_words = self._vocabulary.get_banned_words(text)
130
+
131
+ # ---- Summary ----
132
+ high_risk = sum(
133
+ 1
134
+ for s in sentence_perplexities
135
+ if s.get("risk") == "high_risk"
136
+ )
137
+ medium_risk = sum(
138
+ 1
139
+ for s in sentence_perplexities
140
+ if s.get("risk") == "medium_risk"
141
+ )
142
+ low_risk = len(sentences) - high_risk - medium_risk
143
+
144
+ overall_risk = _compute_overall_risk(high_risk, medium_risk, len(sentences))
145
+
146
+ elapsed_ms = round((time.perf_counter() - t0) * 1000, 1)
147
+ logger.debug("Stage 1 analysis completed in %.1f ms", elapsed_ms)
148
+
149
+ summary: dict[str, Any] = {
150
+ "total_sentences": len(sentences),
151
+ "high_risk_sentences": high_risk,
152
+ "medium_risk_sentences": medium_risk,
153
+ "low_risk_sentences": low_risk,
154
+ "burstiness_cv": burst_result["burstiness_stats"]["cv"],
155
+ "burstiness_rating": burst_result["rating"],
156
+ "ai_vocabulary_count": len(
157
+ [i for i in vocab_instructions if i["type"] == "vocabulary"]
158
+ ),
159
+ "transition_flags": len(
160
+ [i for i in transition_instructions if i["type"] == "transition"]
161
+ ),
162
+ "opening_pattern_flags": len(
163
+ [i for i in opening_instructions if i["type"] == "sentence_opening"]
164
+ ),
165
+ "overall_risk": overall_risk,
166
+ "analysis_time_ms": elapsed_ms,
167
+ }
168
+
169
+ return {
170
+ "summary": summary,
171
+ "instructions": all_instructions,
172
+ "banned_words": banned_words,
173
+ "sentence_perplexities": sentence_perplexities,
174
+ }
175
+
176
+ # ------------------------------------------------------------------
177
+ # Private helpers
178
+ # ------------------------------------------------------------------
179
+
180
+ def _build_sentence_perplexities(
181
+ self,
182
+ sentences: list[str],
183
+ perplexity_instructions: list[dict],
184
+ ) -> list[dict]:
185
+ """Build the sentence_perplexities list from perplexity instructions.
186
+
187
+ For sentences that weren't scored (pre-filter excluded them or scorer
188
+ is None), we assign 'low_risk' with a placeholder perplexity of 100.0.
189
+ """
190
+ # Index perplexity data by sentence_index
191
+ ppl_by_idx: dict[int, dict] = {}
192
+ for instr in perplexity_instructions:
193
+ idx = instr.get("sentence_index", -1)
194
+ if idx >= 0:
195
+ ppl_by_idx[idx] = {
196
+ "index": idx,
197
+ "text": sentences[idx] if idx < len(sentences) else "",
198
+ "mean_ppl": instr.get("mean_perplexity", 100.0),
199
+ "risk": (
200
+ "high_risk" if instr.get("severity") == "high" else "medium_risk"
201
+ ),
202
+ }
203
+
204
+ result = []
205
+ for i, sent in enumerate(sentences):
206
+ if i in ppl_by_idx:
207
+ result.append(ppl_by_idx[i])
208
+ else:
209
+ result.append({
210
+ "index": i,
211
+ "text": sent,
212
+ "mean_ppl": 100.0,
213
+ "risk": "low_risk",
214
+ })
215
+ return result
216
+
217
+ @staticmethod
218
+ def _empty_result() -> dict[str, Any]:
219
+ """Return a valid but empty AnalysisResult for empty/whitespace input."""
220
+ return {
221
+ "summary": {
222
+ "total_sentences": 0,
223
+ "high_risk_sentences": 0,
224
+ "medium_risk_sentences": 0,
225
+ "low_risk_sentences": 0,
226
+ "burstiness_cv": 0.0,
227
+ "burstiness_rating": "acceptable",
228
+ "ai_vocabulary_count": 0,
229
+ "transition_flags": 0,
230
+ "opening_pattern_flags": 0,
231
+ "overall_risk": "low",
232
+ "analysis_time_ms": 0.0,
233
+ },
234
+ "instructions": [],
235
+ "banned_words": [],
236
+ "sentence_perplexities": [],
237
+ }
238
+
239
+
240
+ # ---------------------------------------------------------------------------
241
+ # Module-level helper
242
+ # ---------------------------------------------------------------------------
243
+
244
+
245
+ def _compute_overall_risk(
246
+ high_risk: int,
247
+ medium_risk: int,
248
+ total_sentences: int,
249
+ ) -> str:
250
+ """Compute overall document risk from per-sentence risk counts."""
251
+ if total_sentences == 0:
252
+ return "low"
253
+ high_ratio = high_risk / total_sentences
254
+ medium_ratio = medium_risk / total_sentences
255
+ if high_ratio >= 0.30 or (high_ratio + medium_ratio) >= 0.60:
256
+ return "high"
257
+ if high_ratio >= 0.15 or (high_ratio + medium_ratio) >= 0.40:
258
+ return "medium"
259
+ return "low"
app/core/analyzers/__init__.py ADDED
File without changes
app/core/analyzers/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (160 Bytes). View file
 
app/core/analyzers/__pycache__/burstiness.cpython-313.pyc ADDED
Binary file (6.18 kB). View file
 
app/core/analyzers/__pycache__/informality.cpython-313.pyc ADDED
Binary file (7.86 kB). View file
 
app/core/analyzers/__pycache__/openings.cpython-313.pyc ADDED
Binary file (11.6 kB). View file
 
app/core/analyzers/__pycache__/perplexity.cpython-313.pyc ADDED
Binary file (11.4 kB). View file
 
app/core/analyzers/__pycache__/structure.cpython-313.pyc ADDED
Binary file (10.6 kB). View file
 
app/core/analyzers/__pycache__/transitions.cpython-313.pyc ADDED
Binary file (9.31 kB). View file
 
app/core/analyzers/__pycache__/vocabulary.cpython-313.pyc ADDED
Binary file (7.17 kB). View file
 
app/core/analyzers/burstiness.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Burstiness Analyzer — Stage 1 sub-analyzer.
3
+
4
+ Detects sentence-length uniformity (low burstiness), a hallmark of AI text.
5
+ Human text typically has coefficient of variation (CV) >= 0.45.
6
+ AI text clusters around CV 0.15-0.30.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import statistics
12
+ from typing import TYPE_CHECKING
13
+
14
+ if TYPE_CHECKING:
15
+ import spacy
16
+
17
+ from app.utils.text_utils import count_words, split_sentences, calculate_burstiness
18
+
19
+
20
+ class BurstinessAnalyzer:
21
+ """Analyzes sentence-length variation to detect AI-like uniformity.
22
+
23
+ Args:
24
+ high_uniformity_cv: CV below this threshold → 'high_uniformity'. Default 0.30.
25
+ moderate_uniformity_cv: CV below this (and above high) → 'moderate_uniformity'. Default 0.45.
26
+ """
27
+
28
+ HIGH_UNIFORMITY_CV: float = 0.30
29
+ MODERATE_UNIFORMITY_CV: float = 0.45
30
+
31
+ def __init__(
32
+ self,
33
+ high_uniformity_cv: float = 0.30,
34
+ moderate_uniformity_cv: float = 0.45,
35
+ ) -> None:
36
+ self.high_uniformity_cv = high_uniformity_cv
37
+ self.moderate_uniformity_cv = moderate_uniformity_cv
38
+
39
+ def analyze(
40
+ self,
41
+ sentences: list[str],
42
+ ) -> dict:
43
+ """Analyze sentence-length burstiness and generate instructions.
44
+
45
+ Args:
46
+ sentences: List of sentence strings.
47
+
48
+ Returns:
49
+ Dict with keys:
50
+ - 'burstiness_stats': dict with mean, std, cv, min_length, max_length
51
+ - 'rating': 'high_uniformity' | 'moderate_uniformity' | 'acceptable'
52
+ - 'instructions': list of instruction dicts
53
+ """
54
+ if len(sentences) < 2:
55
+ return {
56
+ 'burstiness_stats': {'mean': 0, 'std': 0, 'cv': 0, 'min_length': 0, 'max_length': 0},
57
+ 'rating': 'acceptable',
58
+ 'instructions': [],
59
+ }
60
+
61
+ lengths = [count_words(s) for s in sentences]
62
+ stats = calculate_burstiness(lengths)
63
+ cv = stats['cv']
64
+ mean_len = stats['mean']
65
+
66
+ # Determine rating
67
+ if cv < self.high_uniformity_cv:
68
+ rating = 'high_uniformity'
69
+ elif cv < self.moderate_uniformity_cv:
70
+ rating = 'moderate_uniformity'
71
+ else:
72
+ rating = 'acceptable'
73
+
74
+ instructions = []
75
+
76
+ if rating in ('high_uniformity', 'moderate_uniformity'):
77
+ instructions = self._generate_instructions(sentences, lengths, mean_len, rating)
78
+
79
+ return {
80
+ 'burstiness_stats': stats,
81
+ 'rating': rating,
82
+ 'instructions': instructions,
83
+ }
84
+
85
+ def _generate_instructions(
86
+ self,
87
+ sentences: list[str],
88
+ lengths: list[int],
89
+ mean_len: float,
90
+ rating: str,
91
+ ) -> list[dict]:
92
+ """Generate specific burstiness fix instructions per sentence.
93
+
94
+ Strategy:
95
+ - Identify sentences that are closest to the mean (most AI-uniform)
96
+ - Alternate between shorten/lengthen/split to create variation
97
+ - Target ~30-40% of sentences for modification
98
+ """
99
+ instructions = []
100
+ n = len(sentences)
101
+
102
+ # Sort by how close they are to the mean (ascending = most uniform)
103
+ indexed = sorted(enumerate(lengths), key=lambda x: abs(x[1] - mean_len))
104
+
105
+ # Select top 40% most uniform sentences for modification
106
+ n_to_modify = max(2, int(n * 0.40))
107
+ to_modify = sorted([i for i, _ in indexed[:n_to_modify]])
108
+
109
+ # Alternate actions for variety
110
+ actions = _get_action_sequence(to_modify, lengths, mean_len)
111
+
112
+ severity = 'high' if rating == 'high_uniformity' else 'medium'
113
+
114
+ for idx, action in zip(to_modify, actions):
115
+ sent = sentences[idx]
116
+ sent_len = lengths[idx]
117
+
118
+ if action == 'shorten':
119
+ target = max(6, int(mean_len * 0.55))
120
+ instructions.append({
121
+ 'type': 'burstiness',
122
+ 'sentence_index': idx,
123
+ 'severity': severity,
124
+ 'instruction': (
125
+ f'Shorten this sentence significantly (target {target}-{target+4} words). '
126
+ f'Currently {sent_len} words, similar to adjacent sentences. '
127
+ f'Cut secondary clauses; keep the core idea only.'
128
+ ),
129
+ })
130
+ elif action == 'lengthen':
131
+ target = int(mean_len * 1.6)
132
+ instructions.append({
133
+ 'type': 'burstiness',
134
+ 'sentence_index': idx,
135
+ 'severity': severity,
136
+ 'instruction': (
137
+ f'Expand or merge this sentence with the next to create one longer, '
138
+ f'more complex sentence (target {target}-{target+6} words). '
139
+ f'Currently {sent_len} words. Add a subordinate clause or qualification.'
140
+ ),
141
+ })
142
+ else: # split
143
+ instructions.append({
144
+ 'type': 'burstiness',
145
+ 'sentence_index': idx,
146
+ 'severity': severity,
147
+ 'instruction': (
148
+ f'Split this {sent_len}-word sentence into two shorter sentences at a '
149
+ f'natural clause boundary. This creates rhythm variation.'
150
+ ),
151
+ })
152
+
153
+ return instructions
154
+
155
+
156
+ def _get_action_sequence(
157
+ indices: list[int],
158
+ lengths: list[int],
159
+ mean_len: float,
160
+ ) -> list[str]:
161
+ """Choose shorten/lengthen/split actions based on current sentence lengths."""
162
+ actions = []
163
+ for idx in indices:
164
+ l = lengths[idx]
165
+ if l > mean_len * 1.3:
166
+ actions.append('split')
167
+ elif l > mean_len * 0.85:
168
+ # Near mean — alternate shorten/lengthen
169
+ actions.append('shorten' if len(actions) % 2 == 0 else 'lengthen')
170
+ else:
171
+ actions.append('lengthen')
172
+ return actions
app/core/analyzers/informality.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Informality Injection Analyzer — Stage 1 sub-analyzer.
3
+
4
+ Identifies places where natural human writing would use:
5
+ - Contractions ("don't" vs "do not", "it's" vs "it is", "they're", "we're",
6
+ "I've", "you'll", "can't", "won't", "isn't", "aren't", "doesn't", "didn't",
7
+ "couldn't", "wouldn't", "shouldn't").
8
+ - First-person hedging ("I would argue", "In my view", "I think").
9
+ - Casual phrasing and hedging language ("arguably", "to some extent").
10
+
11
+ Targets ~10-15% of sentences for informality injections.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import re
17
+
18
+
19
+ # ---------------------------------------------------------------------------
20
+ # Contraction mapping: expanded form (regex pattern) → contraction
21
+ # ---------------------------------------------------------------------------
22
+
23
+ # Each entry is (expanded_regex_pattern, contraction_string).
24
+ # Patterns use word boundaries (\b) and are case-insensitive.
25
+ # The expanded forms are ordered from more specific (longer) to more general
26
+ # to prevent short patterns from shadowing longer ones on the same word.
27
+ _CONTRACTION_MAP: list[tuple[str, str]] = [
28
+ # Two-word expansions — specific first.
29
+ (r'\bdo not\b', "don't"),
30
+ (r'\bcannot\b', "can't"),
31
+ (r'\bwill not\b', "won't"),
32
+ (r'\bshould not\b', "shouldn't"),
33
+ (r'\bwould not\b', "wouldn't"),
34
+ (r'\bcould not\b', "couldn't"),
35
+ (r'\bis not\b', "isn't"),
36
+ (r'\bare not\b', "aren't"),
37
+ (r'\bdoes not\b', "doesn't"),
38
+ (r'\bdid not\b', "didn't"),
39
+ (r'\bhas not\b', "hasn't"),
40
+ (r'\bhave not\b', "haven't"),
41
+ (r'\bwas not\b', "wasn't"),
42
+ (r'\bwere not\b', "weren't"),
43
+ (r'\bthey are\b', "they're"),
44
+ (r'\bwe are\b', "we're"),
45
+ (r'\byou are\b', "you're"),
46
+ (r'\bI am\b', "I'm"),
47
+ (r'\bI have\b', "I've"),
48
+ (r'\bI will\b', "I'll"),
49
+ (r'\bI would\b', "I'd"),
50
+ (r'\byou will\b', "you'll"),
51
+ (r'\bhe is\b', "he's"),
52
+ (r'\bshe is\b', "she's"),
53
+ (r'\bit is\b', "it's"),
54
+ (r'\bthat is\b', "that's"),
55
+ (r'\bthere is\b', "there's"),
56
+ (r'\bwhat is\b', "what's"),
57
+ (r'\bwho is\b', "who's"),
58
+ ]
59
+
60
+ # Compiled patterns: (compiled_regex, contraction_string)
61
+ _COMPILED_CONTRACTIONS: list[tuple[re.Pattern[str], str]] = [
62
+ (re.compile(pattern, re.IGNORECASE), contraction)
63
+ for pattern, contraction in _CONTRACTION_MAP
64
+ ]
65
+
66
+ # ---------------------------------------------------------------------------
67
+ # Strong-claim trigger words for first-person hedging
68
+ # ---------------------------------------------------------------------------
69
+
70
+ _STRONG_CLAIM_TRIGGERS: list[str] = [
71
+ # Present tense
72
+ "shows",
73
+ "proves",
74
+ "demonstrates",
75
+ "supports",
76
+ "reveals",
77
+ "indicates",
78
+ "represents",
79
+ "confirms",
80
+ "illustrates",
81
+ "establishes",
82
+ # Past tense (AI often uses past for formal claims)
83
+ "demonstrated",
84
+ "showed",
85
+ "proved",
86
+ "supported",
87
+ "revealed",
88
+ "indicated",
89
+ "represented",
90
+ "confirmed",
91
+ "illustrated",
92
+ "established",
93
+ # Adverbials and certainty markers
94
+ "is clear",
95
+ "is evident",
96
+ "is obvious",
97
+ "clearly shows",
98
+ "clearly demonstrates",
99
+ "undeniably",
100
+ "without doubt",
101
+ "it is certain",
102
+ "certainly",
103
+ "overwhelmingly",
104
+ ]
105
+
106
+ # First-person hedge suggestions rotated through so the rewriter gets variety.
107
+ _HEDGE_SUGGESTIONS: list[str] = [
108
+ "I would argue that",
109
+ "In my view,",
110
+ "I think",
111
+ "To my mind,",
112
+ "It seems to me that",
113
+ ]
114
+
115
+
116
+ class InformalityAnalyzer:
117
+ """Identifies sentences where natural human informality can be injected.
118
+
119
+ Strategy:
120
+ - Scan for expanded contraction forms and suggest the contraction in
121
+ approximately 50% of cases (alternating) to avoid over-contracting.
122
+ - Detect sentences making strong claims and suggest adding a first-person
123
+ hedge phrase at the start.
124
+ - Cap total informality instructions at 15% of the total sentence count.
125
+
126
+ Args:
127
+ contraction_rate: Fraction of contraction matches to act on (0-1).
128
+ Default 0.5 (every other match).
129
+ max_informality_rate: Maximum fraction of sentences to flag for
130
+ informality changes. Default 0.15.
131
+ """
132
+
133
+ def __init__(
134
+ self,
135
+ contraction_rate: float = 0.5,
136
+ max_informality_rate: float = 0.30,
137
+ ) -> None:
138
+ self.contraction_rate = contraction_rate
139
+ self.max_informality_rate = max_informality_rate
140
+
141
+ # ------------------------------------------------------------------
142
+ # Public API
143
+ # ------------------------------------------------------------------
144
+
145
+ def analyze(self, sentences: list[str]) -> list[dict]:
146
+ """Find informality injection opportunities.
147
+
148
+ Args:
149
+ sentences: List of sentence strings.
150
+
151
+ Returns:
152
+ List of instruction dicts with type='informality', sentence_index,
153
+ severity='low', and instruction.
154
+ """
155
+ if not sentences:
156
+ return []
157
+
158
+ instructions: list[dict] = []
159
+ max_instructions = max(1, int(len(sentences) * self.max_informality_rate))
160
+
161
+ # -- Contraction opportunities ----------------------------------
162
+ contraction_instructions = self._find_contraction_opportunities(sentences)
163
+ instructions.extend(contraction_instructions)
164
+
165
+ # -- First-person hedging opportunities ------------------------
166
+ hedge_instructions = self._find_hedge_opportunities(sentences)
167
+ # Avoid duplicating instructions for sentences already flagged.
168
+ already_flagged = {instr['sentence_index'] for instr in instructions}
169
+ for instr in hedge_instructions:
170
+ if instr['sentence_index'] not in already_flagged:
171
+ instructions.append(instr)
172
+ already_flagged.add(instr['sentence_index'])
173
+
174
+ # -- Cap at 15% of total sentences -----------------------------
175
+ if len(instructions) > max_instructions:
176
+ instructions = instructions[:max_instructions]
177
+
178
+ return instructions
179
+
180
+ # ------------------------------------------------------------------
181
+ # Private helpers
182
+ # ------------------------------------------------------------------
183
+
184
+ def _find_contraction_opportunities(self, sentences: list[str]) -> list[dict]:
185
+ """Scan sentences for expanded contraction forms.
186
+
187
+ Every other match is selected (contraction_rate ≈ 0.5) to avoid
188
+ making the text feel over-contracted.
189
+
190
+ Args:
191
+ sentences: List of sentence strings.
192
+
193
+ Returns:
194
+ List of informality instruction dicts.
195
+ """
196
+ instructions: list[dict] = []
197
+ match_count = 0 # Global match counter used for alternation.
198
+
199
+ for idx, sentence in enumerate(sentences):
200
+ matched_pairs: list[tuple[str, str]] = []
201
+
202
+ for pattern, contraction in _COMPILED_CONTRACTIONS:
203
+ if pattern.search(sentence):
204
+ # Find the actual matched text to show in the instruction.
205
+ m = pattern.search(sentence)
206
+ if m:
207
+ matched_pairs.append((m.group(0), contraction))
208
+
209
+ if not matched_pairs:
210
+ continue
211
+
212
+ # Apply the alternation filter: only act on ~50% of matches.
213
+ for expanded_form, contraction in matched_pairs:
214
+ match_count += 1
215
+ if match_count % 2 == 0:
216
+ # Skip this match (every other one).
217
+ continue
218
+
219
+ instructions.append({
220
+ 'type': 'informality',
221
+ 'sentence_index': idx,
222
+ 'severity': 'low',
223
+ 'instruction': (
224
+ f'Replace "{expanded_form}" with the contraction '
225
+ f'"{contraction}" to make this sentence feel more natural '
226
+ f'and less robotic. Formal expanded forms are overused in '
227
+ f'AI text; a contraction here matches natural speech rhythm.'
228
+ ),
229
+ })
230
+ # Only flag one contraction per sentence to keep it readable.
231
+ break
232
+
233
+ return instructions
234
+
235
+ def _find_hedge_opportunities(self, sentences: list[str]) -> list[dict]:
236
+ """Detect sentences making strong claims and suggest hedging.
237
+
238
+ A sentence is flagged when it contains one of the strong-claim
239
+ trigger words/phrases. The suggestion is to prepend a first-person
240
+ hedging phrase, rotating through _HEDGE_SUGGESTIONS for variety.
241
+
242
+ Args:
243
+ sentences: List of sentence strings.
244
+
245
+ Returns:
246
+ List of informality instruction dicts.
247
+ """
248
+ instructions: list[dict] = []
249
+ hedge_idx = 0 # Rotate through hedge suggestions.
250
+
251
+ for sent_idx, sentence in enumerate(sentences):
252
+ sent_lower = sentence.lower()
253
+ matched_trigger: str | None = None
254
+
255
+ for trigger in _STRONG_CLAIM_TRIGGERS:
256
+ # Use word-boundary matching for single-word triggers and
257
+ # substring matching for phrase triggers.
258
+ if ' ' in trigger:
259
+ if trigger in sent_lower:
260
+ matched_trigger = trigger
261
+ break
262
+ else:
263
+ if re.search(r'\b' + re.escape(trigger) + r'\b', sent_lower):
264
+ matched_trigger = trigger
265
+ break
266
+
267
+ if matched_trigger:
268
+ hedge = _HEDGE_SUGGESTIONS[hedge_idx % len(_HEDGE_SUGGESTIONS)]
269
+ hedge_idx += 1
270
+
271
+ instructions.append({
272
+ 'type': 'informality',
273
+ 'sentence_index': sent_idx,
274
+ 'severity': 'low',
275
+ 'instruction': (
276
+ f'This sentence makes a strong claim ("{matched_trigger}") '
277
+ f'without hedging — typical of over-confident AI prose. '
278
+ f'Consider opening it with a first-person qualifier such as '
279
+ f'"{hedge}" to introduce a human perspective and soften the '
280
+ f'assertion into an argued position rather than stated fact.'
281
+ ),
282
+ })
283
+
284
+ return instructions
app/core/analyzers/openings.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Opening Pattern Analyzer — Stage 1 sub-analyzer.
3
+
4
+ Detects repetitive sentence-opening patterns (e.g. "The... The... The..."),
5
+ formulaic openers ("It is...", "This is...", "There are..."), and flags them
6
+ for the LLM to vary.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from collections import defaultdict
13
+
14
+
15
+ # ---------------------------------------------------------------------------
16
+ # Formulaic opener list
17
+ # ---------------------------------------------------------------------------
18
+
19
+ FORMULAIC_OPENERS: list[str] = [
20
+ "it is",
21
+ "this is",
22
+ "there are",
23
+ "there is",
24
+ "this shows",
25
+ "this demonstrates",
26
+ "this indicates",
27
+ "this suggests",
28
+ "this means",
29
+ "this highlights",
30
+ "this allows",
31
+ "this enables",
32
+ "this helps",
33
+ "this makes",
34
+ "this provides",
35
+ "this creates",
36
+ "this leads",
37
+ "this results",
38
+ "it can",
39
+ "it should",
40
+ "it must",
41
+ "it may",
42
+ "it will",
43
+ # AI aggregating/concluding starters
44
+ "these innovations",
45
+ "these findings",
46
+ "these results",
47
+ "these developments",
48
+ "these advances",
49
+ "these changes",
50
+ "these approaches",
51
+ "these strategies",
52
+ "these improvements",
53
+ "these efforts",
54
+ "these factors",
55
+ "these technologies",
56
+ "these methods",
57
+ "these tools",
58
+ ]
59
+
60
+
61
+ class OpeningPatternAnalyzer:
62
+ """Detects repetitive and formulaic sentence opening patterns.
63
+
64
+ Checks:
65
+ 1. 3+ sentences (globally) starting with the same first word.
66
+ 2. 2+ consecutive sentences within the same paragraph starting the same way.
67
+ 3. Formulaic openers such as "It is", "This is", "There are/is",
68
+ and "This [verb]" constructions.
69
+
70
+ Each finding is returned as an instruction dict that the rewriting stage
71
+ can act on.
72
+ """
73
+
74
+ def __init__(self) -> None:
75
+ # Pre-lowercase the formulaic openers once for speed.
76
+ self._formulaic: list[str] = [o.lower() for o in FORMULAIC_OPENERS]
77
+
78
+ # ------------------------------------------------------------------
79
+ # Public API
80
+ # ------------------------------------------------------------------
81
+
82
+ def analyze(self, sentences: list[str]) -> list[dict]:
83
+ """Detect repetitive and formulaic sentence opening patterns.
84
+
85
+ Checks:
86
+ 1. 3+ sentences starting with the same word (e.g. "The").
87
+ 2. 2+ sentences in a paragraph starting the same way.
88
+ 3. Formulaic openers: "It is", "This is", "There are", "There is",
89
+ "This shows", "This demonstrates", "This indicates",
90
+ "This suggests", "This means", "This highlights", and others.
91
+
92
+ Args:
93
+ sentences: Pre-split list of sentence strings.
94
+
95
+ Returns:
96
+ List of instruction dicts with type='sentence_opening',
97
+ sentence_index, affected_sentences, pattern, severity,
98
+ instruction.
99
+ """
100
+ if not sentences:
101
+ return []
102
+
103
+ instructions: list[dict] = []
104
+
105
+ # Track which sentence indices have already been flagged to avoid
106
+ # duplicate instructions for the same sentence.
107
+ flagged: set[int] = set()
108
+
109
+ # -- Check 1 & 2: repetitive first-word patterns ----------------
110
+ first_word_instructions = self._check_first_word_repetition(sentences, flagged)
111
+ instructions.extend(first_word_instructions)
112
+
113
+ # -- Check 3: formulaic openers ---------------------------------
114
+ formulaic_instructions = self._check_formulaic_openers(sentences, flagged)
115
+ instructions.extend(formulaic_instructions)
116
+
117
+ # -- Check 4: "The [noun] of ..." AI structural pattern ---------
118
+ the_of_instructions = self._check_the_noun_of_pattern(sentences, flagged)
119
+ instructions.extend(the_of_instructions)
120
+
121
+ return instructions
122
+
123
+ # ------------------------------------------------------------------
124
+ # Private helpers
125
+ # ------------------------------------------------------------------
126
+
127
+ def _get_first_word(self, sentence: str) -> str:
128
+ """Return the lowercase first word of *sentence*, stripped of punctuation."""
129
+ stripped = sentence.strip()
130
+ if not stripped:
131
+ return ""
132
+ # Split on whitespace and take the first token, removing leading
133
+ # non-alpha characters (e.g. quote marks, parentheses).
134
+ first_token = stripped.split()[0]
135
+ # Remove leading/trailing punctuation but keep the word itself.
136
+ word = re.sub(r'^[^a-zA-Z]+|[^a-zA-Z]+$', '', first_token)
137
+ return word.lower()
138
+
139
+ def _check_first_word_repetition(
140
+ self,
141
+ sentences: list[str],
142
+ flagged: set[int],
143
+ ) -> list[dict]:
144
+ """Generate instructions for repeated first-word patterns.
145
+
146
+ Two sub-checks:
147
+ a) 3+ sentences globally that share the same first word → one
148
+ consolidated instruction listing all affected indices.
149
+ b) 2+ consecutive sentences in the same paragraph that share the
150
+ same first word (even if the global count is below 3).
151
+
152
+ Paragraph boundaries are estimated by looking for sentence indices
153
+ where a new paragraph starts. Since only ``sentences`` is available
154
+ (no raw text here), paragraphs are approximated by grouping
155
+ consecutive sentences that do not begin with a blank string.
156
+ The paragraph detection for check (b) relies on the caller having
157
+ split on paragraph breaks — if not, the whole list is treated as one
158
+ paragraph for check (b) and check (a) still applies globally.
159
+ """
160
+ instructions: list[dict] = []
161
+
162
+ # ---- Global first-word counts (check a) -----------------------
163
+ first_words: list[str] = [self._get_first_word(s) for s in sentences]
164
+
165
+ # Map: first_word → list of sentence indices
166
+ word_to_indices: dict[str, list[int]] = defaultdict(list)
167
+ for idx, fw in enumerate(first_words):
168
+ if fw:
169
+ word_to_indices[fw].append(idx)
170
+
171
+ globally_flagged_words: set[str] = set()
172
+
173
+ for word, indices in word_to_indices.items():
174
+ if len(indices) >= 2:
175
+ globally_flagged_words.add(word)
176
+ severity = 'high' if len(indices) >= 4 else 'medium'
177
+ instruction = (
178
+ f'Sentences {indices} all begin with "{word.capitalize()}". '
179
+ f'This repetitive opening is a hallmark of AI-generated text. '
180
+ f'Vary the sentence starters: restructure some sentences so they '
181
+ f'open with a different subject, an adverb, a dependent clause, '
182
+ f'or a prepositional phrase.'
183
+ )
184
+ # Use the first index as the primary sentence_index.
185
+ instructions.append({
186
+ 'type': 'sentence_opening',
187
+ 'sentence_index': indices[0],
188
+ 'affected_sentences': indices,
189
+ 'pattern': f'repeated_first_word:"{word}"',
190
+ 'severity': severity,
191
+ 'instruction': instruction,
192
+ })
193
+ for idx in indices:
194
+ flagged.add(idx)
195
+
196
+ # ---- Consecutive same-start within a paragraph (check b) ------
197
+ # Treat the entire sentence list as one paragraph for consecutive
198
+ # scanning. Already-flagged global repeats are still reported here
199
+ # if they form consecutive pairs not already covered.
200
+ i = 0
201
+ while i < len(sentences) - 1:
202
+ fw_i = first_words[i]
203
+ fw_next = first_words[i + 1]
204
+
205
+ if (
206
+ fw_i
207
+ and fw_i == fw_next
208
+ # Skip if this word was already handled by the global check
209
+ and fw_i not in globally_flagged_words
210
+ # Skip if both are already flagged
211
+ and not (i in flagged and (i + 1) in flagged)
212
+ ):
213
+ affected = [i, i + 1]
214
+ # Extend the run if more consecutive sentences match.
215
+ j = i + 2
216
+ while j < len(sentences) and first_words[j] == fw_i:
217
+ affected.append(j)
218
+ j += 1
219
+
220
+ instruction = (
221
+ f'Sentences {affected} (consecutive) all open with '
222
+ f'"{fw_i.capitalize()}". Vary the paragraph rhythm by starting '
223
+ f'at least one of these sentences differently — use an adverb, '
224
+ f'a subordinate clause, or invert the subject-verb order.'
225
+ )
226
+ instructions.append({
227
+ 'type': 'sentence_opening',
228
+ 'sentence_index': i,
229
+ 'affected_sentences': affected,
230
+ 'pattern': f'consecutive_same_opener:"{fw_i}"',
231
+ 'severity': 'medium',
232
+ 'instruction': instruction,
233
+ })
234
+ for idx in affected:
235
+ flagged.add(idx)
236
+ # Jump past the whole run.
237
+ i = affected[-1] + 1
238
+ else:
239
+ i += 1
240
+
241
+ return instructions
242
+
243
+ def _check_formulaic_openers(
244
+ self,
245
+ sentences: list[str],
246
+ flagged: set[int],
247
+ ) -> list[dict]:
248
+ """Flag individual sentences that begin with a formulaic opener.
249
+
250
+ Each formulaic match generates its own medium-severity instruction
251
+ regardless of whether the sentence was already flagged by the
252
+ repetition check — formulaic openers are a distinct signal.
253
+
254
+ Args:
255
+ sentences: Full list of sentence strings.
256
+ flagged: Set of indices already flagged (modified in place to
257
+ record newly flagged indices).
258
+
259
+ Returns:
260
+ List of instruction dicts.
261
+ """
262
+ instructions: list[dict] = []
263
+
264
+ for idx, sentence in enumerate(sentences):
265
+ sent_lower = sentence.strip().lower()
266
+ matched_opener = self._match_formulaic(sent_lower)
267
+ if matched_opener:
268
+ instruction = (
269
+ f'This sentence opens with the formulaic phrase '
270
+ f'"{matched_opener.capitalize()}...", which is strongly associated '
271
+ f'with AI writing. Rewrite the sentence so it opens with a more '
272
+ f'specific subject or a concrete detail rather than a generic '
273
+ f'placeholder construction.'
274
+ )
275
+ instructions.append({
276
+ 'type': 'sentence_opening',
277
+ 'sentence_index': idx,
278
+ 'affected_sentences': [idx],
279
+ 'pattern': f'formulaic_opener:"{matched_opener}"',
280
+ 'severity': 'medium',
281
+ 'instruction': instruction,
282
+ })
283
+ flagged.add(idx)
284
+
285
+ return instructions
286
+
287
+ def _check_the_noun_of_pattern(
288
+ self,
289
+ sentences: list[str],
290
+ flagged: set[int],
291
+ ) -> list[dict]:
292
+ """Flag 'The [noun] of ...' openings — a common AI structural marker.
293
+
294
+ Pattern: sentence starts with 'the ', followed by 1-2 words, then 'of '.
295
+ Examples: 'The integration of...', 'The advancement of...', 'The impact of...'
296
+ These abstract nominalization openings are heavily overused in AI text.
297
+
298
+ Args:
299
+ sentences: Full list of sentence strings.
300
+ flagged: Set of indices already flagged (modified in place).
301
+
302
+ Returns:
303
+ List of instruction dicts.
304
+ """
305
+ instructions: list[dict] = []
306
+
307
+ for idx, sentence in enumerate(sentences):
308
+ sent_lower = sentence.strip().lower()
309
+ if not sent_lower.startswith("the "):
310
+ continue
311
+ # Check if "of " appears within the first ~35 characters
312
+ # after "the " — catches "The X of" and "The X Y of" patterns.
313
+ prefix = sent_lower[4:35] # skip "the "
314
+ if " of " in prefix:
315
+ # Avoid re-flagging if already covered by formulaic check.
316
+ if idx in flagged:
317
+ continue
318
+ # Extract the noun phrase for the instruction.
319
+ end = sent_lower.find(" of ")
320
+ noun_phrase = sent_lower[:end + 4].strip() # "the X of"
321
+
322
+ instruction = (
323
+ f'This sentence opens with "{noun_phrase}..." — an abstract '
324
+ f'nominalization structure ("The [noun] of") that is heavily '
325
+ f'overused in AI text. Rewrite to lead with a verb or a more '
326
+ f'concrete subject: e.g. instead of "The integration of AI..." '
327
+ f'try "AI has been integrated into..." or "Clinicians now use AI..."'
328
+ )
329
+ instructions.append({
330
+ 'type': 'sentence_opening',
331
+ 'sentence_index': idx,
332
+ 'affected_sentences': [idx],
333
+ 'pattern': f'the_noun_of:"{noun_phrase}"',
334
+ 'severity': 'medium',
335
+ 'instruction': instruction,
336
+ })
337
+ flagged.add(idx)
338
+
339
+ return instructions
340
+
341
+ def _match_formulaic(self, sentence_lower: str) -> str | None:
342
+ """Return the matched formulaic opener string, or None.
343
+
344
+ Sorts by length descending so that longer/more-specific openers
345
+ (e.g. "this demonstrates") are matched before shorter substrings
346
+ (e.g. "this").
347
+
348
+ Args:
349
+ sentence_lower: Lowercase sentence text.
350
+
351
+ Returns:
352
+ The matched opener string (lowercase) or None.
353
+ """
354
+ # Sort longest first to prefer specific matches.
355
+ for opener in sorted(self._formulaic, key=len, reverse=True):
356
+ if sentence_lower.startswith(opener):
357
+ # Ensure it is followed by a word boundary (space, comma, etc.)
358
+ # to avoid false positives on e.g. "These are" matching "there".
359
+ end_pos = len(opener)
360
+ if end_pos >= len(sentence_lower) or not sentence_lower[end_pos].isalpha():
361
+ return opener
362
+ return None
app/core/analyzers/perplexity.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Perplexity Analyzer — Stage 1 sub-analyzer.
3
+
4
+ Uses Qwen2.5-0.5B to score sentence perplexity, with a fast heuristic
5
+ pre-filter to reduce unnecessary model calls by ~50%.
6
+
7
+ The pre-filter (<10ms) flags sentences that LOOK AI-like based on:
8
+ 1. Starts with a known transition word.
9
+ 2. Length is within ±3 words of the mean (too uniform).
10
+ 3. Contains 2+ AI vocabulary trigger words.
11
+ 4. Contains known AI phrase patterns.
12
+
13
+ Only pre-flagged sentences (~50-60%) are sent through Qwen2.5 for scoring.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import logging
20
+ import re
21
+ import statistics
22
+ from pathlib import Path
23
+ from typing import TYPE_CHECKING
24
+
25
+ if TYPE_CHECKING:
26
+ from app.core.perplexity_scorer import PerplexityScorer, SentencePerplexityResult
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # Hardcoded fallback heuristic data (used when JSON file is not found)
33
+ # ---------------------------------------------------------------------------
34
+
35
+ _FALLBACK_TRANSITION_STARTERS: list[str] = [
36
+ "furthermore",
37
+ "moreover",
38
+ "additionally",
39
+ "consequently",
40
+ "nevertheless",
41
+ "however",
42
+ "therefore",
43
+ "thus",
44
+ "hence",
45
+ "subsequently",
46
+ "notably",
47
+ "importantly",
48
+ "significantly",
49
+ "evidently",
50
+ "clearly",
51
+ "essentially",
52
+ "ultimately",
53
+ "in addition",
54
+ "as a result",
55
+ "on the other hand",
56
+ "in contrast",
57
+ "in conclusion",
58
+ "to summarize",
59
+ "in summary",
60
+ ]
61
+
62
+ _FALLBACK_AI_VOCABULARY_TRIGGERS: list[str] = [
63
+ "utilize",
64
+ "leverage",
65
+ "facilitate",
66
+ "robust",
67
+ "paradigm",
68
+ "unprecedented",
69
+ "multifaceted",
70
+ "holistic",
71
+ "synergy",
72
+ "comprehensive",
73
+ "nuanced",
74
+ "pivotal",
75
+ "crucial",
76
+ "transformative",
77
+ "innovative",
78
+ "sophisticated",
79
+ "delve",
80
+ "underscore",
81
+ "highlight",
82
+ "demonstrate",
83
+ "encompass",
84
+ "mitigate",
85
+ "optimize",
86
+ "paramount",
87
+ "salient",
88
+ "endeavor",
89
+ "aforementioned",
90
+ ]
91
+
92
+ _FALLBACK_AI_PHRASE_PATTERNS: list[str] = [
93
+ "it is important to note that",
94
+ "it is worth noting that",
95
+ "it should be noted that",
96
+ "it goes without saying",
97
+ "as previously mentioned",
98
+ "in the context of",
99
+ "plays a crucial role",
100
+ "plays a pivotal role",
101
+ "of paramount importance",
102
+ "cannot be overstated",
103
+ "first and foremost",
104
+ "last but not least",
105
+ "in order to",
106
+ "a myriad of",
107
+ "a plethora of",
108
+ ]
109
+
110
+
111
+ class PerplexityAnalyzer:
112
+ """Combines a fast heuristic pre-filter with Qwen2.5-0.5B perplexity scoring.
113
+
114
+ The heuristic pre-filter runs in <10ms and decides which sentences are
115
+ worth sending to the (slower) language model for perplexity evaluation.
116
+ Only pre-flagged sentences (~50-60% of input) are scored by Qwen2.5.
117
+
118
+ Sentences classified as high_risk or medium_risk by the model receive an
119
+ instruction dict in the returned list. low_risk sentences are silently
120
+ omitted.
121
+
122
+ Args:
123
+ scorer: An already-loaded PerplexityScorer instance (shared from app
124
+ startup). If None, perplexity scoring is skipped entirely
125
+ and an empty list is returned (graceful degradation).
126
+ heuristic_path: Path to heuristic_patterns.json.
127
+ """
128
+
129
+ def __init__(
130
+ self,
131
+ scorer: "PerplexityScorer | None" = None,
132
+ heuristic_path: str = "app/data/heuristic_patterns.json",
133
+ ) -> None:
134
+ self.scorer = scorer
135
+ self.heuristic_path = heuristic_path
136
+
137
+ # Heuristic data (populated by _load_heuristics).
138
+ self._transition_starters: list[str] = []
139
+ self._ai_vocab_triggers: list[str] = []
140
+ self._ai_phrase_patterns: list[str] = []
141
+
142
+ self._load_heuristics()
143
+
144
+ # ------------------------------------------------------------------
145
+ # Heuristic data loading
146
+ # ------------------------------------------------------------------
147
+
148
+ def _load_heuristics(self) -> None:
149
+ """Load heuristic pattern data from JSON, with fallback to hardcoded lists.
150
+
151
+ Tries the provided path first, then a path relative to this file's
152
+ location in the package (``../../data/heuristic_patterns.json``).
153
+ Falls back to hardcoded lists if neither file is found.
154
+ """
155
+ path = Path(self.heuristic_path)
156
+ if not path.exists():
157
+ # Try path relative to this source file.
158
+ alt = Path(__file__).parent.parent.parent / "data" / "heuristic_patterns.json"
159
+ path = alt if alt.exists() else path
160
+
161
+ if path.exists():
162
+ try:
163
+ with open(path, 'r', encoding='utf-8') as fh:
164
+ data: dict = json.load(fh)
165
+
166
+ self._transition_starters = [
167
+ s.lower() for s in data.get('transition_starters', [])
168
+ ]
169
+ self._ai_vocab_triggers = [
170
+ w.lower() for w in data.get('ai_vocabulary_triggers', [])
171
+ ]
172
+ self._ai_phrase_patterns = [
173
+ p.lower() for p in data.get('ai_phrase_patterns', [])
174
+ ]
175
+ logger.debug(
176
+ "PerplexityAnalyzer loaded heuristics from '%s': "
177
+ "%d transition starters, %d vocab triggers, %d phrase patterns.",
178
+ path,
179
+ len(self._transition_starters),
180
+ len(self._ai_vocab_triggers),
181
+ len(self._ai_phrase_patterns),
182
+ )
183
+ return
184
+ except (json.JSONDecodeError, OSError) as exc:
185
+ logger.warning(
186
+ "Failed to load heuristic_patterns.json from '%s': %s. "
187
+ "Falling back to hardcoded lists.",
188
+ path, exc,
189
+ )
190
+
191
+ # Fallback to hardcoded lists.
192
+ logger.warning(
193
+ "heuristic_patterns.json not found at '%s'. "
194
+ "Using built-in fallback heuristics.",
195
+ self.heuristic_path,
196
+ )
197
+ self._transition_starters = [s.lower() for s in _FALLBACK_TRANSITION_STARTERS]
198
+ self._ai_vocab_triggers = [w.lower() for w in _FALLBACK_AI_VOCABULARY_TRIGGERS]
199
+ self._ai_phrase_patterns = [p.lower() for p in _FALLBACK_AI_PHRASE_PATTERNS]
200
+
201
+ # ------------------------------------------------------------------
202
+ # Public API
203
+ # ------------------------------------------------------------------
204
+
205
+ def heuristic_prefilter(self, sentences: list[str]) -> list[bool]:
206
+ """Fast heuristic pre-filter (<10ms).
207
+
208
+ Evaluates each sentence against four AI-likelihood criteria and
209
+ returns True for any sentence that matches at least one criterion.
210
+
211
+ Criteria (any one match → True):
212
+ 1. Starts with a transition word from the transition_starters list.
213
+ 2. Sentence length (word count) is within ±3 words of the mean
214
+ sentence length across all input sentences.
215
+ 3. Contains 2+ words from ai_vocabulary_triggers list.
216
+ 4. Contains any phrase from ai_phrase_patterns list.
217
+
218
+ Args:
219
+ sentences: List of sentence strings to evaluate.
220
+
221
+ Returns:
222
+ List of booleans of the same length as *sentences*. True means
223
+ the sentence should be scored by Qwen2.5.
224
+ """
225
+ if not sentences:
226
+ return []
227
+
228
+ # Pre-compute word counts for criterion 2.
229
+ word_counts = [len(s.split()) for s in sentences]
230
+ if len(word_counts) >= 2:
231
+ mean_wc = statistics.mean(word_counts)
232
+ else:
233
+ mean_wc = float(word_counts[0]) if word_counts else 0.0
234
+
235
+ results: list[bool] = []
236
+
237
+ for idx, sentence in enumerate(sentences):
238
+ sent_lower = sentence.lower().strip()
239
+ wc = word_counts[idx]
240
+ flag = False
241
+
242
+ # Criterion 1: starts with a known transition word/phrase.
243
+ if not flag:
244
+ for starter in self._transition_starters:
245
+ if sent_lower.startswith(starter):
246
+ # Ensure it's a true word boundary (not a substring).
247
+ end_pos = len(starter)
248
+ if end_pos >= len(sent_lower) or not sent_lower[end_pos].isalpha():
249
+ flag = True
250
+ break
251
+
252
+ # Criterion 2: length within ±3 words of the mean.
253
+ if not flag:
254
+ if abs(wc - mean_wc) <= 3:
255
+ flag = True
256
+
257
+ # Criterion 3: 2+ AI vocabulary trigger words.
258
+ if not flag:
259
+ trigger_hits = 0
260
+ for trigger in self._ai_vocab_triggers:
261
+ # Word-boundary match to avoid partial hits.
262
+ if re.search(r'\b' + re.escape(trigger) + r'\b', sent_lower):
263
+ trigger_hits += 1
264
+ if trigger_hits >= 2:
265
+ flag = True
266
+ break
267
+
268
+ # Criterion 4: contains a known AI phrase pattern.
269
+ if not flag:
270
+ for phrase in self._ai_phrase_patterns:
271
+ if phrase in sent_lower:
272
+ flag = True
273
+ break
274
+
275
+ results.append(flag)
276
+
277
+ return results
278
+
279
+ def analyze(self, sentences: list[str]) -> list[dict]:
280
+ """Run heuristic pre-filter, then score flagged sentences with Qwen2.5.
281
+
282
+ Sentences that pass the pre-filter are sent to the PerplexityScorer.
283
+ Those that do not pass are implicitly treated as low_risk and omitted
284
+ from the output.
285
+
286
+ For scored sentences:
287
+ - high_risk → instruction with severity='high'.
288
+ - medium_risk → instruction with severity='medium'.
289
+ - low_risk → silently omitted.
290
+
291
+ Args:
292
+ sentences: List of sentence strings.
293
+
294
+ Returns:
295
+ List of instruction dicts for high_risk and medium_risk sentences.
296
+ Each dict: {'type': 'perplexity', 'sentence_index': int,
297
+ 'severity': str, 'mean_perplexity': float,
298
+ 'instruction': str}.
299
+ """
300
+ # Graceful degradation: if no scorer is available, return nothing.
301
+ if self.scorer is None:
302
+ logger.debug(
303
+ "PerplexityAnalyzer: no scorer provided — skipping perplexity scoring."
304
+ )
305
+ return []
306
+
307
+ if not sentences:
308
+ return []
309
+
310
+ # Score all sentences directly — no pre-filter, full accuracy.
311
+ # The heuristic_prefilter() method is kept for potential future use.
312
+ scored_results: list["SentencePerplexityResult"] = (
313
+ self.scorer.score_sentences(sentences)
314
+ )
315
+
316
+ # Build instruction list for high_risk and medium_risk results.
317
+ instructions: list[dict] = []
318
+
319
+ for original_idx, result in enumerate(scored_results):
320
+ ppl = result.mean_perplexity
321
+ classification = result.classification
322
+
323
+ if classification == 'high_risk':
324
+ instructions.append({
325
+ 'type': 'perplexity',
326
+ 'sentence_index': original_idx,
327
+ 'severity': 'high',
328
+ 'mean_perplexity': ppl,
329
+ 'instruction': (
330
+ f"This sentence has very low perplexity ({ppl:.1f}) — "
331
+ f"highly predictable AI text. Restructure significantly: "
332
+ f"change sentence structure, not just vocabulary."
333
+ ),
334
+ })
335
+ elif classification == 'medium_risk':
336
+ instructions.append({
337
+ 'type': 'perplexity',
338
+ 'sentence_index': original_idx,
339
+ 'severity': 'medium',
340
+ 'mean_perplexity': ppl,
341
+ 'instruction': (
342
+ f"Moderate perplexity ({ppl:.1f}) — somewhat predictable. "
343
+ f"Make targeted changes: vary the structure or replace the "
344
+ f"most common phrasing."
345
+ ),
346
+ })
347
+ # low_risk → skip silently.
348
+
349
+ return instructions
app/core/analyzers/structure.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Structural Analyzer — Stage 1 sub-analyzer.
3
+
4
+ Analyzes paragraph-level structure to detect AI-like uniformity:
5
+ - Paragraphs of identical or near-identical length.
6
+ - Over-predictable claim→evidence→conclusion patterns.
7
+ - Missing paragraph breaks (wall of text).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ from collections import Counter
14
+
15
+
16
+ class StructuralAnalyzer:
17
+ """Analyzes paragraph structure for AI uniformity patterns.
18
+
19
+ Checks:
20
+ - 2+ paragraphs with identical sentence count where each is 3-5 sentences.
21
+ - A single paragraph with more than 7 sentences (wall of text).
22
+ - All paragraphs having exactly the same sentence count.
23
+
24
+ Args:
25
+ long_paragraph_threshold: Paragraphs with more sentences than this
26
+ are flagged as "wall of text". Default 7.
27
+ uniform_length_min: Minimum sentence count per paragraph for the
28
+ identical-length uniformity check. Default 3.
29
+ uniform_length_max: Maximum sentence count per paragraph for the
30
+ identical-length uniformity check. Default 5.
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ long_paragraph_threshold: int = 7,
36
+ uniform_length_min: int = 3,
37
+ uniform_length_max: int = 5,
38
+ ) -> None:
39
+ self.long_paragraph_threshold = long_paragraph_threshold
40
+ self.uniform_length_min = uniform_length_min
41
+ self.uniform_length_max = uniform_length_max
42
+
43
+ # ------------------------------------------------------------------
44
+ # Public API
45
+ # ------------------------------------------------------------------
46
+
47
+ def analyze(self, text: str, sentences: list[str]) -> list[dict]:
48
+ """Analyze paragraph structure for AI uniformity patterns.
49
+
50
+ Args:
51
+ text: Full original text (used to detect paragraph breaks via
52
+ double-newline or single newline).
53
+ sentences: Pre-split list of sentences (used for sentence counts
54
+ when the paragraph break approach yields no structure).
55
+
56
+ Returns:
57
+ List of instruction dicts with type='structural'.
58
+ """
59
+ if not text.strip():
60
+ return []
61
+
62
+ paragraphs = self._split_paragraphs(text)
63
+
64
+ # Fall back: if no paragraph boundaries found, treat each 4-sentence
65
+ # window as a synthetic paragraph so the checks still run.
66
+ if len(paragraphs) <= 1:
67
+ paragraphs = self._synthetic_paragraphs(sentences)
68
+
69
+ if not paragraphs:
70
+ return []
71
+
72
+ instructions: list[dict] = []
73
+
74
+ sentence_counts = [self._count_sentences(p) for p in paragraphs]
75
+
76
+ # -- Check 1: wall of text (single long paragraph) --------------
77
+ wall_instructions = self._check_wall_of_text(paragraphs, sentence_counts)
78
+ instructions.extend(wall_instructions)
79
+
80
+ # -- Check 2: identical sentence counts in 3-5 sentence paras --
81
+ uniformity_instructions = self._check_uniform_paragraph_lengths(
82
+ paragraphs, sentence_counts
83
+ )
84
+ instructions.extend(uniformity_instructions)
85
+
86
+ # -- Check 3: all paragraphs have exactly the same length -------
87
+ all_same_instructions = self._check_all_same_length(
88
+ paragraphs, sentence_counts
89
+ )
90
+ instructions.extend(all_same_instructions)
91
+
92
+ return instructions
93
+
94
+ # ------------------------------------------------------------------
95
+ # Private helpers: paragraph splitting
96
+ # ------------------------------------------------------------------
97
+
98
+ def _split_paragraphs(self, text: str) -> list[str]:
99
+ """Split *text* into paragraphs using double or single newlines.
100
+
101
+ Strategy:
102
+ 1. Try splitting on two or more consecutive newlines first.
103
+ 2. If that produces only one chunk, fall back to single newlines.
104
+ 3. Strip each chunk and discard empty ones.
105
+
106
+ Args:
107
+ text: Raw input text.
108
+
109
+ Returns:
110
+ List of non-empty paragraph strings.
111
+ """
112
+ # Try double-newline split first.
113
+ chunks = re.split(r'\n{2,}', text.strip())
114
+ non_empty = [c.strip() for c in chunks if c.strip()]
115
+
116
+ if len(non_empty) >= 2:
117
+ return non_empty
118
+
119
+ # Fall back to single-newline split.
120
+ chunks = re.split(r'\n', text.strip())
121
+ non_empty = [c.strip() for c in chunks if c.strip()]
122
+
123
+ return non_empty if len(non_empty) >= 2 else [text.strip()]
124
+
125
+ def _synthetic_paragraphs(self, sentences: list[str]) -> list[str]:
126
+ """Create synthetic paragraphs from a flat sentence list.
127
+
128
+ When no paragraph breaks exist in the text, group sentences into
129
+ windows of 4 so structural checks still have something to evaluate.
130
+
131
+ Args:
132
+ sentences: All sentences from the document.
133
+
134
+ Returns:
135
+ List of synthetic paragraph strings (each is 4 sentences joined
136
+ by a space, or fewer for the last chunk).
137
+ """
138
+ window = 4
139
+ paragraphs = []
140
+ for i in range(0, len(sentences), window):
141
+ chunk = sentences[i: i + window]
142
+ paragraphs.append(' '.join(chunk))
143
+ return paragraphs
144
+
145
+ # ------------------------------------------------------------------
146
+ # Private helpers: sentence counting
147
+ # ------------------------------------------------------------------
148
+
149
+ def _count_sentences(self, paragraph: str) -> int:
150
+ """Count the number of sentences in *paragraph*.
151
+
152
+ Uses a simple regex boundary detector (terminal punctuation followed
153
+ by whitespace or end-of-string). Accurate enough for structural
154
+ uniformity detection.
155
+
156
+ Args:
157
+ paragraph: A paragraph string.
158
+
159
+ Returns:
160
+ Integer count of sentences (minimum 1 for non-empty text).
161
+ """
162
+ if not paragraph.strip():
163
+ return 0
164
+ # Split on sentence-ending punctuation followed by whitespace or EOS.
165
+ parts = re.split(r'(?<=[.!?])\s+', paragraph.strip())
166
+ non_empty = [p for p in parts if p.strip()]
167
+ return max(1, len(non_empty))
168
+
169
+ # ------------------------------------------------------------------
170
+ # Private helpers: structural checks
171
+ # ------------------------------------------------------------------
172
+
173
+ def _check_wall_of_text(
174
+ self,
175
+ paragraphs: list[str],
176
+ sentence_counts: list[int],
177
+ ) -> list[dict]:
178
+ """Flag any paragraph with more than *long_paragraph_threshold* sentences.
179
+
180
+ Args:
181
+ paragraphs: List of paragraph strings.
182
+ sentence_counts: Corresponding sentence count per paragraph.
183
+
184
+ Returns:
185
+ List of instruction dicts.
186
+ """
187
+ instructions = []
188
+ for para_idx, (para, count) in enumerate(zip(paragraphs, sentence_counts)):
189
+ if count > self.long_paragraph_threshold:
190
+ instructions.append({
191
+ 'type': 'structural',
192
+ 'severity': 'high',
193
+ 'instruction': (
194
+ f'Paragraph {para_idx + 1} contains {count} sentences with no '
195
+ f'break — a wall of text that reads as AI-generated. '
196
+ f'Split it into 2-3 shorter paragraphs at logical topic '
197
+ f'transitions. Each resulting paragraph should cover a single '
198
+ f'sub-point.'
199
+ ),
200
+ })
201
+ return instructions
202
+
203
+ def _check_uniform_paragraph_lengths(
204
+ self,
205
+ paragraphs: list[str],
206
+ sentence_counts: list[int],
207
+ ) -> list[dict]:
208
+ """Flag when 2+ paragraphs share an identical sentence count in [3, 5].
209
+
210
+ AI text tends to produce paragraphs that all have the same number of
211
+ sentences (claim, evidence, conclusion = 3 sentences, etc.).
212
+
213
+ Args:
214
+ paragraphs: List of paragraph strings.
215
+ sentence_counts: Corresponding sentence count per paragraph.
216
+
217
+ Returns:
218
+ List of instruction dicts.
219
+ """
220
+ instructions = []
221
+
222
+ # Count how many paragraphs have each sentence count in range [3, 5].
223
+ count_freq: Counter[int] = Counter()
224
+ for c in sentence_counts:
225
+ if self.uniform_length_min <= c <= self.uniform_length_max:
226
+ count_freq[c] += 1
227
+
228
+ for sent_count, freq in count_freq.items():
229
+ if freq >= 2:
230
+ affected_indices = [
231
+ i + 1 # 1-based paragraph numbers for human-readable output
232
+ for i, c in enumerate(sentence_counts)
233
+ if c == sent_count
234
+ ]
235
+ instructions.append({
236
+ 'type': 'structural',
237
+ 'severity': 'medium',
238
+ 'instruction': (
239
+ f'Paragraphs {affected_indices} each contain exactly '
240
+ f'{sent_count} sentences. This rigid uniformity -- '
241
+ f'{"claim / evidence / conclusion" if sent_count == 3 else "uniform block"} '
242
+ f'repeated {freq} times -- is a strong AI marker. '
243
+ f'Vary paragraph length: expand one paragraph with additional '
244
+ f'detail or examples, and compress another to 1-2 punchy '
245
+ f'sentences for rhythm contrast.'
246
+ ),
247
+ })
248
+
249
+ return instructions
250
+
251
+ def _check_all_same_length(
252
+ self,
253
+ paragraphs: list[str],
254
+ sentence_counts: list[int],
255
+ ) -> list[dict]:
256
+ """Flag when every paragraph in the document has the same sentence count.
257
+
258
+ This check is only meaningful with 3+ paragraphs; it catches the
259
+ case where uniform length falls outside the [3, 5] range targeted by
260
+ the previous check.
261
+
262
+ Args:
263
+ paragraphs: List of paragraph strings.
264
+ sentence_counts: Corresponding sentence count per paragraph.
265
+
266
+ Returns:
267
+ List of instruction dicts (at most one).
268
+ """
269
+ # Need at least 3 paragraphs for this signal to be meaningful.
270
+ if len(sentence_counts) < 3:
271
+ return []
272
+
273
+ non_zero = [c for c in sentence_counts if c > 0]
274
+ if not non_zero:
275
+ return []
276
+
277
+ if len(set(non_zero)) == 1:
278
+ uniform_count = non_zero[0]
279
+ # Skip if this was already covered by _check_uniform_paragraph_lengths
280
+ # (i.e. the count is in [3, 5] — that check already generates an
281
+ # instruction, so avoid duplication).
282
+ if self.uniform_length_min <= uniform_count <= self.uniform_length_max:
283
+ return []
284
+
285
+ return [{
286
+ 'type': 'structural',
287
+ 'severity': 'high',
288
+ 'instruction': (
289
+ f'Every paragraph in the text contains exactly {uniform_count} '
290
+ f'sentences. Perfect structural uniformity across all '
291
+ f'{len(non_zero)} paragraphs is a clear AI writing pattern. '
292
+ f'Deliberately vary the length: write at least one short '
293
+ f'(1-2 sentence) paragraph for emphasis and at least one longer '
294
+ f'paragraph that develops an idea with more depth.'
295
+ ),
296
+ }]
297
+
298
+ return []
app/core/analyzers/transitions.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Transition Pattern Analyzer -- Stage 1 sub-analyzer.
3
+
4
+ Detects AI-like use of formulaic transitions at sentence/paragraph beginnings.
5
+
6
+ Severity tiers:
7
+ - HIGH (always flag): Furthermore, Moreover, Additionally, Consequently, Therefore,
8
+ Thus, Hence, In addition, In conclusion, Notably, Importantly, etc.
9
+ - LOW (only flag when 2+ low-severity appear OR 2+ other transitions already found):
10
+ However, But, Still, Yet, Although, While, Whereas, Despite, That said, etc.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import re
17
+ from pathlib import Path
18
+
19
+
20
+ # ---------------------------------------------------------------------------
21
+ # Low-severity transitions: natural contrast words that humans use freely.
22
+ # Only flagged when overused (2+ in the same text) or context-dependent.
23
+ # ---------------------------------------------------------------------------
24
+
25
+ _LOW_SEVERITY_STARTERS: set[str] = {
26
+ "however",
27
+ "but",
28
+ "still",
29
+ "yet",
30
+ "although",
31
+ "while",
32
+ "whereas",
33
+ "despite",
34
+ "though",
35
+ "admittedly",
36
+ "granted",
37
+ "that said",
38
+ "on the other hand",
39
+ "then again",
40
+ "at the same time",
41
+ "even so",
42
+ "nonetheless",
43
+ "nevertheless",
44
+ "notwithstanding",
45
+ }
46
+
47
+
48
+ class TransitionAnalyzer:
49
+ """Detects problematic transition words/phrases that mark AI writing.
50
+
51
+ Args:
52
+ transition_path: Path to transition_words.json data file.
53
+ """
54
+
55
+ def __init__(
56
+ self,
57
+ transition_path: str = "app/data/transition_words.json",
58
+ ) -> None:
59
+ self.transition_path = transition_path
60
+ self._starters: list[str] = []
61
+ self._connectors: list[str] = []
62
+ self._formulaic: list[str] = []
63
+ self._load_transitions()
64
+
65
+ def _load_transitions(self) -> None:
66
+ """Load transition word lists from JSON file."""
67
+ path = Path(self.transition_path)
68
+ if not path.exists():
69
+ alt = Path(__file__).parent.parent.parent / "data" / "transition_words.json"
70
+ path = alt if alt.exists() else path
71
+
72
+ if path.exists():
73
+ with open(path, 'r', encoding='utf-8') as f:
74
+ data = json.load(f)
75
+ self._starters = [s.lower() for s in data.get('sentence_starters', [])]
76
+ self._connectors = [s.lower() for s in data.get('connector_phrases', [])]
77
+ self._formulaic = [s.lower() for s in data.get('formulaic_openers', [])]
78
+ else:
79
+ # Hardcoded fallback
80
+ self._starters = [
81
+ 'furthermore', 'moreover', 'additionally', 'consequently',
82
+ 'nevertheless', 'however', 'therefore', 'thus', 'hence',
83
+ 'subsequently', 'notably', 'importantly',
84
+ ]
85
+
86
+ def analyze(self, sentences: list[str]) -> list[dict]:
87
+ """Detect transition pattern problems across all sentences.
88
+
89
+ High-severity transitions are always flagged.
90
+ Low-severity transitions (however, but, while, etc.) are only flagged
91
+ when they appear 2+ times in the text OR when there are already 2+
92
+ high-severity transition flags -- since low-severity transitions are
93
+ natural in human writing and only become a problem when overused.
94
+
95
+ Args:
96
+ sentences: List of sentence strings.
97
+
98
+ Returns:
99
+ List of instruction dicts.
100
+ """
101
+ instructions: list[dict] = []
102
+
103
+ # First pass: detect all transition matches with their severity.
104
+ matches: list[tuple[int, str, str]] = [] # (sent_idx, matched_word, severity)
105
+
106
+ for idx, sentence in enumerate(sentences):
107
+ sent_lower = sentence.strip().lower()
108
+ matched = self._find_transition_match(sent_lower)
109
+ if matched:
110
+ severity = self._get_severity(matched)
111
+ matches.append((idx, matched, severity))
112
+
113
+ # Count high-severity and low-severity matches.
114
+ high_count = sum(1 for _, _, sev in matches if sev == 'high')
115
+ low_severity_words: dict[str, int] = {}
116
+ for _, word, sev in matches:
117
+ if sev == 'low':
118
+ low_severity_words[word] = low_severity_words.get(word, 0) + 1
119
+
120
+ # Second pass: build instructions using the severity rules.
121
+ for sent_idx, matched, severity in matches:
122
+ if severity == 'high':
123
+ instructions.append(self._build_instruction(sent_idx, matched, 'high'))
124
+ else:
125
+ # Low-severity: only flag if:
126
+ # (a) this specific low-severity word appears 2+ times, OR
127
+ # (b) there are already 2+ high-severity flags in the text.
128
+ word_count = low_severity_words.get(matched, 1)
129
+ if word_count >= 2 or high_count >= 2:
130
+ instructions.append(
131
+ self._build_instruction(sent_idx, matched, 'low')
132
+ )
133
+
134
+ # Check for consecutive same-start patterns (independent of severity).
135
+ consecutive_instructions = self._check_consecutive_patterns(sentences)
136
+ instructions.extend(consecutive_instructions)
137
+
138
+ return instructions
139
+
140
+ def _get_severity(self, transition: str) -> str:
141
+ """Return 'low' if the transition is a natural contrast word, else 'high'."""
142
+ # Normalize: strip trailing comma/space that may appear in matched text.
143
+ normalized = transition.rstrip(', ').lower()
144
+ if normalized in _LOW_SEVERITY_STARTERS:
145
+ return 'low'
146
+ return 'high'
147
+
148
+ def _build_instruction(
149
+ self,
150
+ sentence_index: int,
151
+ matched: str,
152
+ severity: str,
153
+ ) -> dict:
154
+ """Build an instruction dict for a flagged transition."""
155
+ if severity == 'high':
156
+ instruction = (
157
+ f'Remove or replace the transition "{matched}" at the start of this sentence. '
158
+ f'Either restructure to flow naturally from the previous sentence, '
159
+ f'or use a less formulaic connector. '
160
+ f'Starting directly with the subject is often strongest.'
161
+ )
162
+ else:
163
+ instruction = (
164
+ f'"{matched.capitalize()}" at the start of this sentence is a low-severity '
165
+ f'transition -- natural in moderation, but it appears multiple times here. '
166
+ f'Vary how you signal contrast: restructure one of these sentences to flow '
167
+ f'without a connector, or use more specific phrasing ("The data tell a '
168
+ f'different story:", "That optimism has limits:", etc.).'
169
+ )
170
+ return {
171
+ 'type': 'transition',
172
+ 'sentence_index': sentence_index,
173
+ 'severity': severity,
174
+ 'current_opening': matched,
175
+ 'instruction': instruction,
176
+ }
177
+
178
+ def _find_transition_match(self, sentence_lower: str) -> str | None:
179
+ """Return the transition word/phrase if sentence starts with one."""
180
+ # Check formulaic openers first (longer patterns)
181
+ for phrase in self._formulaic:
182
+ if sentence_lower.startswith(phrase):
183
+ return phrase
184
+ # Check connectors
185
+ for phrase in self._connectors:
186
+ if sentence_lower.startswith(phrase):
187
+ return phrase
188
+ # Check single-word starters
189
+ for word in self._starters:
190
+ # Match word at start, optionally followed by comma or space
191
+ pattern = r'^' + re.escape(word) + r'[,\s]'
192
+ if re.match(pattern, sentence_lower):
193
+ return word
194
+ return None
195
+
196
+ def _check_consecutive_patterns(
197
+ self,
198
+ sentences: list[str],
199
+ ) -> list[dict]:
200
+ """Detect 2+ consecutive sentences with the same opening pattern."""
201
+ instructions = []
202
+ i = 0
203
+ while i < len(sentences) - 1:
204
+ # Check first 1-3 words for repetition
205
+ first_words_i = ' '.join(sentences[i].split()[:3]).lower().rstrip('.,;:')
206
+ first_words_next = ' '.join(sentences[i + 1].split()[:3]).lower().rstrip('.,;:')
207
+
208
+ if (
209
+ first_words_i == first_words_next
210
+ and len(first_words_i) > 2
211
+ ):
212
+ instructions.append({
213
+ 'type': 'transition',
214
+ 'sentence_index': i,
215
+ 'severity': 'medium',
216
+ 'current_opening': first_words_i,
217
+ 'instruction': (
218
+ f'Sentences {i} and {i+1} both start with "{first_words_i}". '
219
+ f'Vary the opening of one of them -- start with a different subject, '
220
+ f'a time phrase, or an adverbial clause.'
221
+ ),
222
+ })
223
+ i += 1
224
+ return instructions
app/core/analyzers/vocabulary.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Vocabulary Analyzer — Stage 1 sub-analyzer.
3
+
4
+ Scans text for AI-overused words and phrases, generating replacement instructions
5
+ for each match found.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+
16
+ class VocabularyAnalyzer:
17
+ """Detects AI-vocabulary words/phrases and generates replacement instructions.
18
+
19
+ Args:
20
+ vocab_path: Path to ai_vocabulary.json data file.
21
+ """
22
+
23
+ def __init__(self, vocab_path: str = "app/data/ai_vocabulary.json") -> None:
24
+ self.vocab_path = vocab_path
25
+ self._db: dict[str, Any] = {}
26
+ self._load_vocabulary()
27
+
28
+ def _load_vocabulary(self) -> None:
29
+ """Load AI vocabulary database from JSON file."""
30
+ path = Path(self.vocab_path)
31
+ if not path.exists():
32
+ # Try relative to project root
33
+ alt = Path(__file__).parent.parent.parent / "data" / "ai_vocabulary.json"
34
+ path = alt if alt.exists() else path
35
+
36
+ if path.exists():
37
+ with open(path, 'r', encoding='utf-8') as f:
38
+ self._db = json.load(f)
39
+ else:
40
+ self._db = {'single_words': {}, 'phrases': {}}
41
+
42
+ def analyze(self, sentences: list[str]) -> list[dict]:
43
+ """Scan all sentences for AI vocabulary matches.
44
+
45
+ Args:
46
+ sentences: List of sentence strings (from spaCy or text_utils).
47
+
48
+ Returns:
49
+ List of instruction dicts, one per match found.
50
+ """
51
+ instructions = []
52
+ single_words = self._db.get('single_words', {})
53
+ phrases = self._db.get('phrases', {})
54
+
55
+ for sent_idx, sentence in enumerate(sentences):
56
+ sentence_lower = sentence.lower()
57
+
58
+ # Check phrases first (longer matches take priority)
59
+ for phrase, meta in phrases.items():
60
+ if phrase.lower() in sentence_lower:
61
+ position = _get_position(sentence_lower, phrase.lower())
62
+ instructions.append({
63
+ 'type': 'vocabulary',
64
+ 'sentence_index': sent_idx,
65
+ 'severity': meta.get('severity', 'medium'),
66
+ 'word_or_phrase': phrase,
67
+ 'position_in_sentence': position,
68
+ 'suggestions': meta.get('suggestions', []),
69
+ 'instruction': (
70
+ f"Replace phrase \"{phrase}\" — AI overuse detected. "
71
+ f"Options: {', '.join(repr(s) for s in meta.get('suggestions', [])[:3])}"
72
+ ),
73
+ })
74
+
75
+ # Check single words (word-boundary match to avoid partial hits)
76
+ for word, meta in single_words.items():
77
+ pattern = r'\b' + re.escape(word.lower()) + r'\b'
78
+ if re.search(pattern, sentence_lower):
79
+ position = _get_position(sentence_lower, word.lower())
80
+ instructions.append({
81
+ 'type': 'vocabulary',
82
+ 'sentence_index': sent_idx,
83
+ 'severity': meta.get('severity', 'medium'),
84
+ 'word_or_phrase': word,
85
+ 'position_in_sentence': position,
86
+ 'suggestions': meta.get('suggestions', []),
87
+ 'instruction': (
88
+ f"Replace \"{word}\" — flagged AI vocabulary. "
89
+ f"Options: {', '.join(repr(s) for s in meta.get('suggestions', [])[:3])}"
90
+ ),
91
+ })
92
+
93
+ return instructions
94
+
95
+ def get_banned_words(self, text: str) -> list[str]:
96
+ """Return all AI vocabulary words/phrases found in *text*.
97
+
98
+ Used to build the banned_words list passed to Stage 2.
99
+
100
+ Args:
101
+ text: The full input text.
102
+
103
+ Returns:
104
+ Deduplicated list of flagged words/phrases found.
105
+ """
106
+ found = []
107
+ text_lower = text.lower()
108
+
109
+ for phrase in self._db.get('phrases', {}):
110
+ if phrase.lower() in text_lower:
111
+ found.append(phrase)
112
+
113
+ for word in self._db.get('single_words', {}):
114
+ pattern = r'\b' + re.escape(word.lower()) + r'\b'
115
+ if re.search(pattern, text_lower):
116
+ found.append(word)
117
+
118
+ return list(dict.fromkeys(found)) # deduplicate preserving order
119
+
120
+ def get_suggestions(self, word_or_phrase: str) -> list[str]:
121
+ """Look up replacement suggestions for a given word or phrase.
122
+
123
+ Args:
124
+ word_or_phrase: The word/phrase to look up.
125
+
126
+ Returns:
127
+ List of suggestion strings, or empty list if not found.
128
+ """
129
+ key = word_or_phrase.lower()
130
+ single = self._db.get('single_words', {})
131
+ phrases = self._db.get('phrases', {})
132
+
133
+ if key in single:
134
+ return single[key].get('suggestions', [])
135
+ if key in phrases:
136
+ return phrases[key].get('suggestions', [])
137
+ return []
138
+
139
+
140
+ def _get_position(sentence_lower: str, target_lower: str) -> str:
141
+ """Return 'start', 'middle', or 'end' position of target in sentence."""
142
+ idx = sentence_lower.find(target_lower)
143
+ if idx == -1:
144
+ return 'middle'
145
+ ratio = idx / max(1, len(sentence_lower))
146
+ if ratio < 0.20:
147
+ return 'start'
148
+ if ratio > 0.75:
149
+ return 'end'
150
+ return 'middle'
app/core/perplexity_scorer.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Qwen2.5-0.5B perplexity scorer.
3
+
4
+ This module wraps the Qwen2.5-0.5B causal language model for fast,
5
+ CPU-based perplexity scoring of individual sentences.
6
+
7
+ Design decisions:
8
+ - Model is loaded once at application startup (PerplexityScorer.__init__)
9
+ and shared across all requests.
10
+ - All inference is wrapped in @torch.no_grad() to reduce memory pressure.
11
+ - torch_dtype=torch.float32 and device_map="cpu" for reliable CPU deployment.
12
+ - Sentence-level scoring is used (not token-level) to produce a single
13
+ mean perplexity value per sentence.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ import math
20
+ from dataclasses import dataclass, field
21
+ from typing import Optional
22
+
23
+ import torch # type: ignore
24
+ from transformers import AutoModelForCausalLM, AutoTokenizer # type: ignore
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ # ---------------------------------------------------------------------------
30
+ # Result dataclasses
31
+ # ---------------------------------------------------------------------------
32
+
33
+
34
+ @dataclass
35
+ class TokenPerplexitySpan:
36
+ """A contiguous span of tokens with an associated perplexity score."""
37
+
38
+ tokens: str
39
+ perplexity: float
40
+
41
+
42
+ @dataclass
43
+ class SentencePerplexityResult:
44
+ """Perplexity analysis result for a single sentence."""
45
+
46
+ sentence_index: int
47
+ sentence_text: str
48
+ mean_perplexity: float
49
+ classification: str # "high_risk" | "medium_risk" | "low_risk"
50
+ low_perplexity_spans: list[TokenPerplexitySpan] = field(default_factory=list)
51
+
52
+
53
+ @dataclass
54
+ class PerplexityResult:
55
+ """Aggregate perplexity result for an entire piece of text."""
56
+
57
+ mean_perplexity: float
58
+ sentence_results: list[SentencePerplexityResult]
59
+
60
+
61
+ # ---------------------------------------------------------------------------
62
+ # PerplexityScorer
63
+ # ---------------------------------------------------------------------------
64
+
65
+
66
+ class PerplexityScorer:
67
+ """Wrapper around Qwen2.5-0.5B for fast, CPU-based perplexity scoring.
68
+
69
+ Usage::
70
+
71
+ scorer = PerplexityScorer() # load once at startup
72
+ result = scorer.score_sentence("Some text.") # per-sentence scoring
73
+ results = scorer.score_sentences(["S1.", "S2."])
74
+
75
+ Thresholds (configurable via constructor):
76
+ high_risk : mean_perplexity < 30
77
+ medium_risk: 30 ≤ mean_perplexity < 60
78
+ low_risk : mean_perplexity ≥ 60
79
+ """
80
+
81
+ def __init__(
82
+ self,
83
+ model_id: str = "Qwen/Qwen2.5-0.5B",
84
+ high_risk_threshold: float = 30.0,
85
+ medium_risk_threshold: float = 60.0,
86
+ ) -> None:
87
+ """Load the Qwen2.5-0.5B model and tokeniser.
88
+
89
+ Args:
90
+ model_id: HuggingFace model identifier.
91
+ high_risk_threshold: Sentences below this perplexity are 'high_risk'.
92
+ medium_risk_threshold: Sentences below this (and above high) are 'medium_risk'.
93
+ """
94
+ self.model_id = model_id
95
+ self.high_risk_threshold = high_risk_threshold
96
+ self.medium_risk_threshold = medium_risk_threshold
97
+
98
+ logger.info("Loading tokeniser for '%s' …", model_id)
99
+ self.tokenizer = AutoTokenizer.from_pretrained(model_id)
100
+
101
+ logger.info("Loading model '%s' (float32, CPU) …", model_id)
102
+ self.model = AutoModelForCausalLM.from_pretrained(
103
+ model_id,
104
+ dtype=torch.float32,
105
+ device_map="cpu",
106
+ )
107
+ self.model.eval()
108
+ logger.info("PerplexityScorer ready.")
109
+
110
+ # ------------------------------------------------------------------
111
+ # Public API
112
+ # ------------------------------------------------------------------
113
+
114
+ def score_sentence(
115
+ self,
116
+ sentence: str,
117
+ sentence_index: int = 0,
118
+ compute_spans: bool = False,
119
+ ) -> SentencePerplexityResult:
120
+ """Score a single sentence.
121
+
122
+ Args:
123
+ sentence: Text of the sentence to score.
124
+ sentence_index: Index of the sentence in the parent document
125
+ (used for downstream instruction generation).
126
+ compute_spans: If True, run sliding-window span detection to find
127
+ low-perplexity token subsequences. Disabled by
128
+ default because it adds ~900ms per sentence
129
+ (16 extra forward passes). Enable only for
130
+ debugging or the /analyze debug endpoint.
131
+
132
+ Returns:
133
+ SentencePerplexityResult with mean_perplexity and classification.
134
+ """
135
+ mean_ppl = self._compute_mean_perplexity(sentence)
136
+ classification = self._classify(mean_ppl)
137
+ low_spans = (
138
+ self._find_low_perplexity_spans(sentence) if compute_spans else []
139
+ )
140
+
141
+ return SentencePerplexityResult(
142
+ sentence_index=sentence_index,
143
+ sentence_text=sentence,
144
+ mean_perplexity=round(mean_ppl, 2),
145
+ classification=classification,
146
+ low_perplexity_spans=low_spans,
147
+ )
148
+
149
+ def score_sentences(
150
+ self, sentences: list[str]
151
+ ) -> list[SentencePerplexityResult]:
152
+ """Score multiple sentences.
153
+
154
+ Args:
155
+ sentences: List of sentence strings.
156
+
157
+ Returns:
158
+ List of SentencePerplexityResult in the same order.
159
+ """
160
+ results: list[SentencePerplexityResult] = []
161
+ for idx, sent in enumerate(sentences):
162
+ if not sent.strip():
163
+ # Skip empty sentences — assign low risk
164
+ results.append(
165
+ SentencePerplexityResult(
166
+ sentence_index=idx,
167
+ sentence_text=sent,
168
+ mean_perplexity=100.0,
169
+ classification="low_risk",
170
+ )
171
+ )
172
+ continue
173
+ results.append(self.score_sentence(sent, sentence_index=idx))
174
+ return results
175
+
176
+ def score_text(self, text: str) -> PerplexityResult:
177
+ """Score an entire text by splitting on newlines and spaces.
178
+
179
+ Convenience method when sentence splitting is not needed.
180
+
181
+ Args:
182
+ text: Any string.
183
+
184
+ Returns:
185
+ PerplexityResult with per-sentence breakdown and overall mean.
186
+ """
187
+ # Basic sentence split for standalone usage
188
+ import re
189
+
190
+ raw_sentences = re.split(r"(?<=[.!?])\s+", text.strip())
191
+ sentences = [s.strip() for s in raw_sentences if s.strip()]
192
+ sentence_results = self.score_sentences(sentences)
193
+
194
+ all_ppls = [r.mean_perplexity for r in sentence_results]
195
+ overall_mean = sum(all_ppls) / len(all_ppls) if all_ppls else 0.0
196
+
197
+ return PerplexityResult(
198
+ mean_perplexity=round(overall_mean, 2),
199
+ sentence_results=sentence_results,
200
+ )
201
+
202
+ # ------------------------------------------------------------------
203
+ # Private helpers
204
+ # ------------------------------------------------------------------
205
+
206
+ @torch.no_grad()
207
+ def _compute_mean_perplexity(self, text: str) -> float:
208
+ """Compute mean token-level perplexity for *text* using Qwen2.5-0.5B.
209
+
210
+ Args:
211
+ text: Any string (typically one sentence).
212
+
213
+ Returns:
214
+ Float perplexity value. Returns 100.0 on error.
215
+ """
216
+ try:
217
+ encodings = self.tokenizer(
218
+ text,
219
+ return_tensors="pt",
220
+ truncation=True,
221
+ max_length=512,
222
+ )
223
+ input_ids: torch.Tensor = encodings["input_ids"]
224
+
225
+ if input_ids.shape[1] < 2:
226
+ # Single-token text — cannot compute meaningful perplexity
227
+ return 100.0
228
+
229
+ labels = input_ids.clone()
230
+ outputs = self.model(input_ids=input_ids, labels=labels)
231
+ # outputs.loss is the mean negative log-likelihood over tokens
232
+ loss: torch.Tensor = outputs.loss
233
+ return float(math.exp(loss.item()))
234
+
235
+ except Exception as exc:
236
+ logger.warning("Perplexity computation failed for text '%s…': %s", text[:40], exc)
237
+ return 100.0
238
+
239
+ def _classify(self, mean_perplexity: float) -> str:
240
+ """Map a perplexity value to a risk classification string.
241
+
242
+ Args:
243
+ mean_perplexity: The computed perplexity score.
244
+
245
+ Returns:
246
+ 'high_risk', 'medium_risk', or 'low_risk'.
247
+ """
248
+ if mean_perplexity < self.high_risk_threshold:
249
+ return "high_risk"
250
+ if mean_perplexity < self.medium_risk_threshold:
251
+ return "medium_risk"
252
+ return "low_risk"
253
+
254
+ @torch.no_grad()
255
+ def _find_low_perplexity_spans(
256
+ self,
257
+ sentence: str,
258
+ window_size: int = 4,
259
+ threshold: float = 15.0,
260
+ ) -> list[TokenPerplexitySpan]:
261
+ """Identify low-perplexity token spans within a sentence.
262
+
263
+ Uses a sliding window over tokens to find subsequences that are
264
+ particularly predictable (i.e. likely AI-generated).
265
+
266
+ Args:
267
+ sentence: The sentence to scan.
268
+ window_size: Number of tokens per window.
269
+ threshold: Perplexity below this is considered a 'low' span.
270
+
271
+ Returns:
272
+ List of TokenPerplexitySpan objects (may be empty).
273
+ """
274
+ spans: list[TokenPerplexitySpan] = []
275
+ try:
276
+ encodings = self.tokenizer(
277
+ sentence,
278
+ return_tensors="pt",
279
+ truncation=True,
280
+ max_length=512,
281
+ )
282
+ input_ids: torch.Tensor = encodings["input_ids"]
283
+ n_tokens = input_ids.shape[1]
284
+
285
+ if n_tokens < window_size + 1:
286
+ return spans
287
+
288
+ for start in range(1, n_tokens - window_size):
289
+ window_ids = input_ids[:, start : start + window_size]
290
+ context_ids = input_ids[:, :start]
291
+
292
+ # Score the window given the full context
293
+ full_ids = torch.cat([context_ids, window_ids], dim=1)
294
+ labels = full_ids.clone()
295
+ # Mask context labels so only window tokens contribute to loss
296
+ labels[:, : context_ids.shape[1]] = -100
297
+
298
+ outputs = self.model(input_ids=full_ids, labels=labels)
299
+ window_ppl = float(math.exp(outputs.loss.item()))
300
+
301
+ if window_ppl < threshold:
302
+ token_str = self.tokenizer.decode(
303
+ window_ids[0], skip_special_tokens=True
304
+ ).strip()
305
+ if token_str:
306
+ spans.append(
307
+ TokenPerplexitySpan(
308
+ tokens=token_str,
309
+ perplexity=round(window_ppl, 2),
310
+ )
311
+ )
312
+
313
+ except Exception as exc:
314
+ logger.debug("Low-perplexity span detection failed: %s", exc)
315
+
316
+ return spans
app/data/.gitkeep ADDED
File without changes
app/data/ai_vocabulary.json ADDED
@@ -0,0 +1,2210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "single_words": {
3
+ "furthermore": {
4
+ "severity": "high",
5
+ "suggestions": [
6
+ "also",
7
+ "besides",
8
+ "plus",
9
+ "and",
10
+ "on top of that"
11
+ ]
12
+ },
13
+ "moreover": {
14
+ "severity": "high",
15
+ "suggestions": [
16
+ "also",
17
+ "besides",
18
+ "what's more",
19
+ "in addition",
20
+ "and"
21
+ ]
22
+ },
23
+ "additionally": {
24
+ "severity": "high",
25
+ "suggestions": [
26
+ "also",
27
+ "plus",
28
+ "on top of that",
29
+ "and",
30
+ "in addition"
31
+ ]
32
+ },
33
+ "consequently": {
34
+ "severity": "medium",
35
+ "suggestions": [
36
+ "so",
37
+ "as a result",
38
+ "because of this",
39
+ "therefore",
40
+ "which means"
41
+ ]
42
+ },
43
+ "significantly": {
44
+ "severity": "high",
45
+ "suggestions": [
46
+ "greatly",
47
+ "a lot",
48
+ "much",
49
+ "noticeably",
50
+ "considerably"
51
+ ]
52
+ },
53
+ "demonstrates": {
54
+ "severity": "high",
55
+ "suggestions": [
56
+ "shows",
57
+ "proves",
58
+ "reveals",
59
+ "makes clear",
60
+ "points to"
61
+ ]
62
+ },
63
+ "utilize": {
64
+ "severity": "high",
65
+ "suggestions": [
66
+ "use",
67
+ "apply",
68
+ "work with",
69
+ "make use of",
70
+ "employ"
71
+ ]
72
+ },
73
+ "implement": {
74
+ "severity": "medium",
75
+ "suggestions": [
76
+ "use",
77
+ "put in place",
78
+ "apply",
79
+ "carry out",
80
+ "set up"
81
+ ]
82
+ },
83
+ "comprehensive": {
84
+ "severity": "high",
85
+ "suggestions": [
86
+ "thorough",
87
+ "complete",
88
+ "full",
89
+ "detailed",
90
+ "wide-ranging"
91
+ ]
92
+ },
93
+ "facilitate": {
94
+ "severity": "high",
95
+ "suggestions": [
96
+ "help",
97
+ "make easier",
98
+ "support",
99
+ "aid",
100
+ "enable"
101
+ ]
102
+ },
103
+ "leverage": {
104
+ "severity": "high",
105
+ "suggestions": [
106
+ "use",
107
+ "take advantage of",
108
+ "build on",
109
+ "draw on",
110
+ "apply"
111
+ ]
112
+ },
113
+ "robust": {
114
+ "severity": "high",
115
+ "suggestions": [
116
+ "strong",
117
+ "solid",
118
+ "reliable",
119
+ "sturdy",
120
+ "dependable"
121
+ ]
122
+ },
123
+ "paradigm": {
124
+ "severity": "high",
125
+ "suggestions": [
126
+ "model",
127
+ "approach",
128
+ "framework",
129
+ "system",
130
+ "way of thinking"
131
+ ]
132
+ },
133
+ "unprecedented": {
134
+ "severity": "high",
135
+ "suggestions": [
136
+ "never seen before",
137
+ "new",
138
+ "unheard of",
139
+ "first-ever",
140
+ "unique"
141
+ ]
142
+ },
143
+ "transformative": {
144
+ "severity": "high",
145
+ "suggestions": [
146
+ "game-changing",
147
+ "life-changing",
148
+ "major",
149
+ "powerful",
150
+ "impactful"
151
+ ]
152
+ },
153
+ "optimize": {
154
+ "severity": "high",
155
+ "suggestions": [
156
+ "improve",
157
+ "fine-tune",
158
+ "make better",
159
+ "refine",
160
+ "boost"
161
+ ]
162
+ },
163
+ "streamline": {
164
+ "severity": "high",
165
+ "suggestions": [
166
+ "simplify",
167
+ "speed up",
168
+ "make more efficient",
169
+ "cut down",
170
+ "smooth out"
171
+ ]
172
+ },
173
+ "innovative": {
174
+ "severity": "high",
175
+ "suggestions": [
176
+ "new",
177
+ "fresh",
178
+ "creative",
179
+ "original",
180
+ "groundbreaking"
181
+ ]
182
+ },
183
+ "crucial": {
184
+ "severity": "high",
185
+ "suggestions": [
186
+ "key",
187
+ "vital",
188
+ "essential",
189
+ "important",
190
+ "necessary"
191
+ ]
192
+ },
193
+ "delve": {
194
+ "severity": "high",
195
+ "suggestions": [
196
+ "look into",
197
+ "explore",
198
+ "dig into",
199
+ "examine",
200
+ "go deeper"
201
+ ]
202
+ },
203
+ "multifaceted": {
204
+ "severity": "high",
205
+ "suggestions": [
206
+ "complex",
207
+ "many-sided",
208
+ "varied",
209
+ "layered",
210
+ "complicated"
211
+ ]
212
+ },
213
+ "underscore": {
214
+ "severity": "high",
215
+ "suggestions": [
216
+ "highlight",
217
+ "stress",
218
+ "show",
219
+ "point out",
220
+ "emphasize"
221
+ ]
222
+ },
223
+ "overarching": {
224
+ "severity": "high",
225
+ "suggestions": [
226
+ "main",
227
+ "overall",
228
+ "central",
229
+ "broad",
230
+ "general"
231
+ ]
232
+ },
233
+ "spearheaded": {
234
+ "severity": "medium",
235
+ "suggestions": [
236
+ "led",
237
+ "drove",
238
+ "started",
239
+ "launched",
240
+ "headed"
241
+ ]
242
+ },
243
+ "encompass": {
244
+ "severity": "medium",
245
+ "suggestions": [
246
+ "include",
247
+ "cover",
248
+ "contain",
249
+ "take in",
250
+ "involve"
251
+ ]
252
+ },
253
+ "pivotal": {
254
+ "severity": "high",
255
+ "suggestions": [
256
+ "key",
257
+ "crucial",
258
+ "critical",
259
+ "important",
260
+ "central"
261
+ ]
262
+ },
263
+ "landscape": {
264
+ "severity": "high",
265
+ "suggestions": [
266
+ "field",
267
+ "area",
268
+ "scene",
269
+ "space",
270
+ "environment"
271
+ ]
272
+ },
273
+ "realm": {
274
+ "severity": "high",
275
+ "suggestions": [
276
+ "field",
277
+ "area",
278
+ "world",
279
+ "domain",
280
+ "sphere"
281
+ ]
282
+ },
283
+ "embark": {
284
+ "severity": "medium",
285
+ "suggestions": [
286
+ "start",
287
+ "begin",
288
+ "set out on",
289
+ "undertake",
290
+ "launch"
291
+ ]
292
+ },
293
+ "foster": {
294
+ "severity": "medium",
295
+ "suggestions": [
296
+ "encourage",
297
+ "support",
298
+ "build",
299
+ "nurture",
300
+ "promote"
301
+ ]
302
+ },
303
+ "navigate": {
304
+ "severity": "medium",
305
+ "suggestions": [
306
+ "handle",
307
+ "work through",
308
+ "manage",
309
+ "deal with",
310
+ "get through"
311
+ ]
312
+ },
313
+ "tapestry": {
314
+ "severity": "high",
315
+ "suggestions": [
316
+ "mix",
317
+ "blend",
318
+ "combination",
319
+ "range",
320
+ "variety"
321
+ ]
322
+ },
323
+ "testament": {
324
+ "severity": "medium",
325
+ "suggestions": [
326
+ "proof",
327
+ "sign",
328
+ "evidence",
329
+ "example",
330
+ "reflection"
331
+ ]
332
+ },
333
+ "endeavor": {
334
+ "severity": "medium",
335
+ "suggestions": [
336
+ "effort",
337
+ "attempt",
338
+ "try",
339
+ "work",
340
+ "project"
341
+ ]
342
+ },
343
+ "commendable": {
344
+ "severity": "medium",
345
+ "suggestions": [
346
+ "impressive",
347
+ "good",
348
+ "praiseworthy",
349
+ "admirable",
350
+ "worthy"
351
+ ]
352
+ },
353
+ "intricate": {
354
+ "severity": "medium",
355
+ "suggestions": [
356
+ "complex",
357
+ "detailed",
358
+ "involved",
359
+ "elaborate",
360
+ "complicated"
361
+ ]
362
+ },
363
+ "noteworthy": {
364
+ "severity": "high",
365
+ "suggestions": [
366
+ "notable",
367
+ "interesting",
368
+ "worth mentioning",
369
+ "important",
370
+ "significant"
371
+ ]
372
+ },
373
+ "myriad": {
374
+ "severity": "high",
375
+ "suggestions": [
376
+ "many",
377
+ "countless",
378
+ "a wide range of",
379
+ "numerous",
380
+ "various"
381
+ ]
382
+ },
383
+ "aforementioned": {
384
+ "severity": "high",
385
+ "suggestions": [
386
+ "this",
387
+ "the above",
388
+ "the previous",
389
+ "the earlier",
390
+ "what was mentioned"
391
+ ]
392
+ },
393
+ "paramount": {
394
+ "severity": "medium",
395
+ "suggestions": [
396
+ "most important",
397
+ "top priority",
398
+ "above all",
399
+ "critical",
400
+ "essential"
401
+ ]
402
+ },
403
+ "adept": {
404
+ "severity": "medium",
405
+ "suggestions": [
406
+ "skilled",
407
+ "good at",
408
+ "expert",
409
+ "capable",
410
+ "experienced"
411
+ ]
412
+ },
413
+ "burgeoning": {
414
+ "severity": "high",
415
+ "suggestions": [
416
+ "growing",
417
+ "expanding",
418
+ "rising",
419
+ "emerging",
420
+ "booming"
421
+ ]
422
+ },
423
+ "highlight": {
424
+ "severity": "medium",
425
+ "suggestions": [
426
+ "show",
427
+ "point out",
428
+ "note",
429
+ "stress",
430
+ "draw attention to"
431
+ ]
432
+ },
433
+ "showcase": {
434
+ "severity": "medium",
435
+ "suggestions": [
436
+ "show",
437
+ "display",
438
+ "present",
439
+ "feature",
440
+ "demonstrate"
441
+ ]
442
+ },
443
+ "essential": {
444
+ "severity": "medium",
445
+ "suggestions": [
446
+ "needed",
447
+ "key",
448
+ "necessary",
449
+ "vital",
450
+ "important"
451
+ ]
452
+ },
453
+ "vital": {
454
+ "severity": "medium",
455
+ "suggestions": [
456
+ "key",
457
+ "necessary",
458
+ "essential",
459
+ "important",
460
+ "needed"
461
+ ]
462
+ },
463
+ "important": {
464
+ "severity": "low",
465
+ "suggestions": [
466
+ "key",
467
+ "major",
468
+ "notable",
469
+ "significant",
470
+ "worthwhile"
471
+ ]
472
+ },
473
+ "significant": {
474
+ "severity": "high",
475
+ "suggestions": [
476
+ "major",
477
+ "notable",
478
+ "meaningful",
479
+ "considerable",
480
+ "real"
481
+ ]
482
+ },
483
+ "notable": {
484
+ "severity": "medium",
485
+ "suggestions": [
486
+ "noteworthy",
487
+ "worth mentioning",
488
+ "interesting",
489
+ "relevant",
490
+ "key"
491
+ ]
492
+ },
493
+ "remarkable": {
494
+ "severity": "medium",
495
+ "suggestions": [
496
+ "impressive",
497
+ "striking",
498
+ "surprising",
499
+ "standout",
500
+ "unusual"
501
+ ]
502
+ },
503
+ "extraordinary": {
504
+ "severity": "medium",
505
+ "suggestions": [
506
+ "exceptional",
507
+ "outstanding",
508
+ "rare",
509
+ "uncommon",
510
+ "incredible"
511
+ ]
512
+ },
513
+ "exceptional": {
514
+ "severity": "medium",
515
+ "suggestions": [
516
+ "outstanding",
517
+ "excellent",
518
+ "rare",
519
+ "above average",
520
+ "impressive"
521
+ ]
522
+ },
523
+ "substantial": {
524
+ "severity": "medium",
525
+ "suggestions": [
526
+ "large",
527
+ "considerable",
528
+ "major",
529
+ "sizable",
530
+ "big"
531
+ ]
532
+ },
533
+ "considerable": {
534
+ "severity": "medium",
535
+ "suggestions": [
536
+ "large",
537
+ "sizable",
538
+ "major",
539
+ "meaningful",
540
+ "significant"
541
+ ]
542
+ },
543
+ "profound": {
544
+ "severity": "medium",
545
+ "suggestions": [
546
+ "deep",
547
+ "major",
548
+ "strong",
549
+ "serious",
550
+ "significant"
551
+ ]
552
+ },
553
+ "extensive": {
554
+ "severity": "medium",
555
+ "suggestions": [
556
+ "wide",
557
+ "broad",
558
+ "large",
559
+ "thorough",
560
+ "long"
561
+ ]
562
+ },
563
+ "diverse": {
564
+ "severity": "low",
565
+ "suggestions": [
566
+ "varied",
567
+ "different",
568
+ "wide-ranging",
569
+ "mixed",
570
+ "various"
571
+ ]
572
+ },
573
+ "various": {
574
+ "severity": "low",
575
+ "suggestions": [
576
+ "different",
577
+ "several",
578
+ "many",
579
+ "a number of",
580
+ "assorted"
581
+ ]
582
+ },
583
+ "numerous": {
584
+ "severity": "medium",
585
+ "suggestions": [
586
+ "many",
587
+ "a lot of",
588
+ "several",
589
+ "countless",
590
+ "multiple"
591
+ ]
592
+ },
593
+ "multiple": {
594
+ "severity": "low",
595
+ "suggestions": [
596
+ "many",
597
+ "several",
598
+ "a number of",
599
+ "various",
600
+ "different"
601
+ ]
602
+ },
603
+ "several": {
604
+ "severity": "low",
605
+ "suggestions": [
606
+ "a few",
607
+ "many",
608
+ "some",
609
+ "a number of",
610
+ "various"
611
+ ]
612
+ },
613
+ "particular": {
614
+ "severity": "low",
615
+ "suggestions": [
616
+ "specific",
617
+ "certain",
618
+ "given",
619
+ "this",
620
+ "that"
621
+ ]
622
+ },
623
+ "specific": {
624
+ "severity": "low",
625
+ "suggestions": [
626
+ "exact",
627
+ "particular",
628
+ "clear",
629
+ "defined",
630
+ "precise"
631
+ ]
632
+ },
633
+ "overall": {
634
+ "severity": "low",
635
+ "suggestions": [
636
+ "in general",
637
+ "broadly",
638
+ "all in all",
639
+ "on the whole",
640
+ "generally"
641
+ ]
642
+ },
643
+ "fundamental": {
644
+ "severity": "medium",
645
+ "suggestions": [
646
+ "basic",
647
+ "core",
648
+ "key",
649
+ "essential",
650
+ "central"
651
+ ]
652
+ },
653
+ "primary": {
654
+ "severity": "low",
655
+ "suggestions": [
656
+ "main",
657
+ "first",
658
+ "top",
659
+ "chief",
660
+ "leading"
661
+ ]
662
+ },
663
+ "initial": {
664
+ "severity": "low",
665
+ "suggestions": [
666
+ "first",
667
+ "early",
668
+ "starting",
669
+ "opening",
670
+ "original"
671
+ ]
672
+ },
673
+ "subsequent": {
674
+ "severity": "medium",
675
+ "suggestions": [
676
+ "later",
677
+ "following",
678
+ "next",
679
+ "then",
680
+ "after that"
681
+ ]
682
+ },
683
+ "ultimate": {
684
+ "severity": "low",
685
+ "suggestions": [
686
+ "final",
687
+ "last",
688
+ "top",
689
+ "greatest",
690
+ "best"
691
+ ]
692
+ },
693
+ "inherent": {
694
+ "severity": "medium",
695
+ "suggestions": [
696
+ "built-in",
697
+ "natural",
698
+ "inbuilt",
699
+ "part of",
700
+ "core"
701
+ ]
702
+ },
703
+ "integral": {
704
+ "severity": "medium",
705
+ "suggestions": [
706
+ "essential",
707
+ "key",
708
+ "central",
709
+ "core",
710
+ "necessary"
711
+ ]
712
+ },
713
+ "central": {
714
+ "severity": "low",
715
+ "suggestions": [
716
+ "main",
717
+ "key",
718
+ "core",
719
+ "primary",
720
+ "leading"
721
+ ]
722
+ },
723
+ "holistic": {
724
+ "severity": "high",
725
+ "suggestions": [
726
+ "whole-picture",
727
+ "broad",
728
+ "all-around",
729
+ "big-picture",
730
+ "complete"
731
+ ]
732
+ },
733
+ "dynamic": {
734
+ "severity": "medium",
735
+ "suggestions": [
736
+ "active",
737
+ "changing",
738
+ "lively",
739
+ "flexible",
740
+ "evolving"
741
+ ]
742
+ },
743
+ "creative": {
744
+ "severity": "low",
745
+ "suggestions": [
746
+ "original",
747
+ "imaginative",
748
+ "inventive",
749
+ "fresh",
750
+ "new"
751
+ ]
752
+ },
753
+ "unique": {
754
+ "severity": "medium",
755
+ "suggestions": [
756
+ "one-of-a-kind",
757
+ "distinct",
758
+ "original",
759
+ "special",
760
+ "different"
761
+ ]
762
+ },
763
+ "novel": {
764
+ "severity": "medium",
765
+ "suggestions": [
766
+ "new",
767
+ "fresh",
768
+ "original",
769
+ "first-of-its-kind",
770
+ "inventive"
771
+ ]
772
+ },
773
+ "contemporary": {
774
+ "severity": "medium",
775
+ "suggestions": [
776
+ "modern",
777
+ "current",
778
+ "today's",
779
+ "present-day",
780
+ "recent"
781
+ ]
782
+ },
783
+ "emerging": {
784
+ "severity": "medium",
785
+ "suggestions": [
786
+ "new",
787
+ "growing",
788
+ "rising",
789
+ "up-and-coming",
790
+ "developing"
791
+ ]
792
+ },
793
+ "evolving": {
794
+ "severity": "medium",
795
+ "suggestions": [
796
+ "changing",
797
+ "growing",
798
+ "developing",
799
+ "shifting",
800
+ "advancing"
801
+ ]
802
+ },
803
+ "enhancing": {
804
+ "severity": "medium",
805
+ "suggestions": [
806
+ "improving",
807
+ "boosting",
808
+ "strengthening",
809
+ "adding to",
810
+ "building on"
811
+ ]
812
+ },
813
+ "advancing": {
814
+ "severity": "low",
815
+ "suggestions": [
816
+ "moving forward",
817
+ "progressing",
818
+ "improving",
819
+ "pushing ahead",
820
+ "developing"
821
+ ]
822
+ },
823
+ "promoting": {
824
+ "severity": "low",
825
+ "suggestions": [
826
+ "supporting",
827
+ "encouraging",
828
+ "pushing for",
829
+ "backing",
830
+ "advocating"
831
+ ]
832
+ },
833
+ "enabling": {
834
+ "severity": "low",
835
+ "suggestions": [
836
+ "allowing",
837
+ "making possible",
838
+ "helping",
839
+ "giving rise to",
840
+ "supporting"
841
+ ]
842
+ },
843
+ "ensuring": {
844
+ "severity": "low",
845
+ "suggestions": [
846
+ "making sure",
847
+ "guaranteeing",
848
+ "securing",
849
+ "confirming",
850
+ "seeing to it"
851
+ ]
852
+ },
853
+ "emphasizing": {
854
+ "severity": "medium",
855
+ "suggestions": [
856
+ "stressing",
857
+ "highlighting",
858
+ "pointing out",
859
+ "underscoring",
860
+ "making clear"
861
+ ]
862
+ },
863
+ "addressing": {
864
+ "severity": "low",
865
+ "suggestions": [
866
+ "tackling",
867
+ "dealing with",
868
+ "handling",
869
+ "looking at",
870
+ "working on"
871
+ ]
872
+ },
873
+ "examining": {
874
+ "severity": "low",
875
+ "suggestions": [
876
+ "looking at",
877
+ "studying",
878
+ "reviewing",
879
+ "checking",
880
+ "analyzing"
881
+ ]
882
+ },
883
+ "exploring": {
884
+ "severity": "low",
885
+ "suggestions": [
886
+ "looking into",
887
+ "examining",
888
+ "studying",
889
+ "investigating",
890
+ "digging into"
891
+ ]
892
+ },
893
+ "investigating": {
894
+ "severity": "low",
895
+ "suggestions": [
896
+ "looking into",
897
+ "studying",
898
+ "examining",
899
+ "researching",
900
+ "exploring"
901
+ ]
902
+ },
903
+ "analyzing": {
904
+ "severity": "low",
905
+ "suggestions": [
906
+ "studying",
907
+ "examining",
908
+ "breaking down",
909
+ "reviewing",
910
+ "assessing"
911
+ ]
912
+ },
913
+ "evaluating": {
914
+ "severity": "low",
915
+ "suggestions": [
916
+ "assessing",
917
+ "judging",
918
+ "reviewing",
919
+ "weighing",
920
+ "measuring"
921
+ ]
922
+ },
923
+ "assessing": {
924
+ "severity": "low",
925
+ "suggestions": [
926
+ "evaluating",
927
+ "judging",
928
+ "measuring",
929
+ "reviewing",
930
+ "gauging"
931
+ ]
932
+ },
933
+ "identifying": {
934
+ "severity": "low",
935
+ "suggestions": [
936
+ "finding",
937
+ "spotting",
938
+ "pinpointing",
939
+ "noting",
940
+ "recognizing"
941
+ ]
942
+ },
943
+ "acknowledging": {
944
+ "severity": "low",
945
+ "suggestions": [
946
+ "recognizing",
947
+ "admitting",
948
+ "noting",
949
+ "accepting",
950
+ "accepting"
951
+ ]
952
+ },
953
+ "illustrating": {
954
+ "severity": "low",
955
+ "suggestions": [
956
+ "showing",
957
+ "demonstrating",
958
+ "presenting",
959
+ "explaining",
960
+ "clarifying"
961
+ ]
962
+ },
963
+ "representing": {
964
+ "severity": "low",
965
+ "suggestions": [
966
+ "showing",
967
+ "standing for",
968
+ "depicting",
969
+ "reflecting",
970
+ "conveying"
971
+ ]
972
+ },
973
+ "contributing": {
974
+ "severity": "low",
975
+ "suggestions": [
976
+ "adding to",
977
+ "helping with",
978
+ "playing a part in",
979
+ "feeding into",
980
+ "supporting"
981
+ ]
982
+ },
983
+ "impacting": {
984
+ "severity": "low",
985
+ "suggestions": [
986
+ "affecting",
987
+ "influencing",
988
+ "shaping",
989
+ "changing",
990
+ "having an effect on"
991
+ ]
992
+ },
993
+ "systematic": {
994
+ "severity": "medium",
995
+ "suggestions": [
996
+ "organized",
997
+ "structured",
998
+ "methodical",
999
+ "step-by-step",
1000
+ "orderly"
1001
+ ]
1002
+ },
1003
+ "strategic": {
1004
+ "severity": "medium",
1005
+ "suggestions": [
1006
+ "planned",
1007
+ "deliberate",
1008
+ "thoughtful",
1009
+ "purposeful",
1010
+ "calculated"
1011
+ ]
1012
+ },
1013
+ "empirical": {
1014
+ "severity": "medium",
1015
+ "suggestions": [
1016
+ "evidence-based",
1017
+ "data-driven",
1018
+ "observed",
1019
+ "tested",
1020
+ "practical"
1021
+ ]
1022
+ },
1023
+ "analytical": {
1024
+ "severity": "low",
1025
+ "suggestions": [
1026
+ "data-based",
1027
+ "logical",
1028
+ "structured",
1029
+ "methodical",
1030
+ "reasoned"
1031
+ ]
1032
+ },
1033
+ "theoretical": {
1034
+ "severity": "low",
1035
+ "suggestions": [
1036
+ "conceptual",
1037
+ "abstract",
1038
+ "idea-based",
1039
+ "model-based",
1040
+ "hypothetical"
1041
+ ]
1042
+ },
1043
+ "effective": {
1044
+ "severity": "low",
1045
+ "suggestions": [
1046
+ "working",
1047
+ "useful",
1048
+ "successful",
1049
+ "good",
1050
+ "productive"
1051
+ ]
1052
+ },
1053
+ "efficient": {
1054
+ "severity": "low",
1055
+ "suggestions": [
1056
+ "quick",
1057
+ "fast",
1058
+ "lean",
1059
+ "smooth",
1060
+ "productive"
1061
+ ]
1062
+ },
1063
+ "productive": {
1064
+ "severity": "low",
1065
+ "suggestions": [
1066
+ "useful",
1067
+ "effective",
1068
+ "fruitful",
1069
+ "worthwhile",
1070
+ "valuable"
1071
+ ]
1072
+ },
1073
+ "critical": {
1074
+ "severity": "medium",
1075
+ "suggestions": [
1076
+ "key",
1077
+ "important",
1078
+ "essential",
1079
+ "decisive",
1080
+ "necessary"
1081
+ ]
1082
+ },
1083
+ "evident": {
1084
+ "severity": "medium",
1085
+ "suggestions": [
1086
+ "clear",
1087
+ "obvious",
1088
+ "plain",
1089
+ "visible",
1090
+ "apparent"
1091
+ ]
1092
+ },
1093
+ "apparent": {
1094
+ "severity": "medium",
1095
+ "suggestions": [
1096
+ "clear",
1097
+ "obvious",
1098
+ "visible",
1099
+ "plain",
1100
+ "noticeable"
1101
+ ]
1102
+ },
1103
+ "explicit": {
1104
+ "severity": "low",
1105
+ "suggestions": [
1106
+ "clear",
1107
+ "direct",
1108
+ "stated",
1109
+ "plain",
1110
+ "obvious"
1111
+ ]
1112
+ },
1113
+ "complex": {
1114
+ "severity": "low",
1115
+ "suggestions": [
1116
+ "complicated",
1117
+ "involved",
1118
+ "tricky",
1119
+ "layered",
1120
+ "intricate"
1121
+ ]
1122
+ },
1123
+ "advanced": {
1124
+ "severity": "low",
1125
+ "suggestions": [
1126
+ "higher-level",
1127
+ "sophisticated",
1128
+ "complex",
1129
+ "developed",
1130
+ "expert-level"
1131
+ ]
1132
+ },
1133
+ "modern": {
1134
+ "severity": "low",
1135
+ "suggestions": [
1136
+ "current",
1137
+ "today's",
1138
+ "recent",
1139
+ "up-to-date",
1140
+ "present-day"
1141
+ ]
1142
+ },
1143
+ "current": {
1144
+ "severity": "low",
1145
+ "suggestions": [
1146
+ "today's",
1147
+ "present",
1148
+ "recent",
1149
+ "existing",
1150
+ "now"
1151
+ ]
1152
+ },
1153
+ "recent": {
1154
+ "severity": "low",
1155
+ "suggestions": [
1156
+ "new",
1157
+ "latest",
1158
+ "just-released",
1159
+ "newly published",
1160
+ "fresh"
1161
+ ]
1162
+ },
1163
+ "expanding": {
1164
+ "severity": "low",
1165
+ "suggestions": [
1166
+ "growing",
1167
+ "widening",
1168
+ "spreading",
1169
+ "increasing",
1170
+ "building"
1171
+ ]
1172
+ },
1173
+ "developing": {
1174
+ "severity": "low",
1175
+ "suggestions": [
1176
+ "growing",
1177
+ "building",
1178
+ "emerging",
1179
+ "evolving",
1180
+ "taking shape"
1181
+ ]
1182
+ },
1183
+ "changing": {
1184
+ "severity": "low",
1185
+ "suggestions": [
1186
+ "shifting",
1187
+ "evolving",
1188
+ "transforming",
1189
+ "adapting",
1190
+ "moving"
1191
+ ]
1192
+ },
1193
+ "improving": {
1194
+ "severity": "low",
1195
+ "suggestions": [
1196
+ "getting better",
1197
+ "advancing",
1198
+ "progressing",
1199
+ "growing",
1200
+ "developing"
1201
+ ]
1202
+ },
1203
+ "providing": {
1204
+ "severity": "low",
1205
+ "suggestions": [
1206
+ "giving",
1207
+ "offering",
1208
+ "supplying",
1209
+ "delivering",
1210
+ "presenting"
1211
+ ]
1212
+ },
1213
+ "requiring": {
1214
+ "severity": "low",
1215
+ "suggestions": [
1216
+ "needing",
1217
+ "calling for",
1218
+ "depending on",
1219
+ "demanding",
1220
+ "asking for"
1221
+ ]
1222
+ },
1223
+ "indicating": {
1224
+ "severity": "low",
1225
+ "suggestions": [
1226
+ "showing",
1227
+ "suggesting",
1228
+ "pointing to",
1229
+ "signaling",
1230
+ "revealing"
1231
+ ]
1232
+ },
1233
+ "suggesting": {
1234
+ "severity": "low",
1235
+ "suggestions": [
1236
+ "hinting",
1237
+ "pointing to",
1238
+ "implying",
1239
+ "showing",
1240
+ "indicating"
1241
+ ]
1242
+ },
1243
+ "focusing": {
1244
+ "severity": "low",
1245
+ "suggestions": [
1246
+ "concentrating on",
1247
+ "targeting",
1248
+ "zeroing in on",
1249
+ "looking at",
1250
+ "centering on"
1251
+ ]
1252
+ },
1253
+ "understanding": {
1254
+ "severity": "low",
1255
+ "suggestions": [
1256
+ "grasping",
1257
+ "recognizing",
1258
+ "knowing",
1259
+ "seeing",
1260
+ "realizing"
1261
+ ]
1262
+ },
1263
+ "recognizing": {
1264
+ "severity": "low",
1265
+ "suggestions": [
1266
+ "seeing",
1267
+ "noticing",
1268
+ "knowing",
1269
+ "understanding",
1270
+ "being aware of"
1271
+ ]
1272
+ },
1273
+ "implementation": {
1274
+ "severity": "high",
1275
+ "suggestions": [
1276
+ "use",
1277
+ "rollout",
1278
+ "adoption",
1279
+ "deployment",
1280
+ "setup"
1281
+ ]
1282
+ },
1283
+ "sophisticated": {
1284
+ "severity": "high",
1285
+ "suggestions": [
1286
+ "advanced",
1287
+ "complex",
1288
+ "clever",
1289
+ "smart",
1290
+ "capable"
1291
+ ]
1292
+ },
1293
+ "capabilities": {
1294
+ "severity": "medium",
1295
+ "suggestions": [
1296
+ "abilities",
1297
+ "features",
1298
+ "functions",
1299
+ "strengths",
1300
+ "skills"
1301
+ ]
1302
+ },
1303
+ "integration": {
1304
+ "severity": "medium",
1305
+ "suggestions": [
1306
+ "inclusion",
1307
+ "adoption",
1308
+ "use",
1309
+ "merging",
1310
+ "combining"
1311
+ ]
1312
+ },
1313
+ "demonstrate": {
1314
+ "severity": "high",
1315
+ "suggestions": [
1316
+ "show",
1317
+ "reveal",
1318
+ "prove",
1319
+ "make clear",
1320
+ "point to"
1321
+ ]
1322
+ },
1323
+ "proactive": {
1324
+ "severity": "high",
1325
+ "suggestions": [
1326
+ "ahead-of-the-curve",
1327
+ "forward-thinking",
1328
+ "early",
1329
+ "preventive",
1330
+ "anticipatory"
1331
+ ]
1332
+ },
1333
+ "advancement": {
1334
+ "severity": "medium",
1335
+ "suggestions": [
1336
+ "progress",
1337
+ "growth",
1338
+ "development",
1339
+ "step forward",
1340
+ "improvement"
1341
+ ]
1342
+ },
1343
+ "revolutionized": {
1344
+ "severity": "medium",
1345
+ "suggestions": [
1346
+ "transformed",
1347
+ "changed dramatically",
1348
+ "overhauled",
1349
+ "reshaped",
1350
+ "upended"
1351
+ ]
1352
+ },
1353
+ "personalized": {
1354
+ "severity": "low",
1355
+ "suggestions": [
1356
+ "tailored",
1357
+ "custom",
1358
+ "individual",
1359
+ "adapted",
1360
+ "specific"
1361
+ ]
1362
+ },
1363
+ "collectively": {
1364
+ "severity": "medium",
1365
+ "suggestions": [
1366
+ "together",
1367
+ "as a whole",
1368
+ "combined",
1369
+ "jointly",
1370
+ "all in all"
1371
+ ]
1372
+ },
1373
+ "synergy": {
1374
+ "severity": "high",
1375
+ "suggestions": [
1376
+ "combined effect",
1377
+ "working together",
1378
+ "joint benefit",
1379
+ "mutual gain",
1380
+ "teamwork"
1381
+ ]
1382
+ },
1383
+ "actionable": {
1384
+ "severity": "high",
1385
+ "suggestions": [
1386
+ "practical",
1387
+ "useful",
1388
+ "workable",
1389
+ "concrete",
1390
+ "hands-on"
1391
+ ]
1392
+ },
1393
+ "scalable": {
1394
+ "severity": "high",
1395
+ "suggestions": [
1396
+ "expandable",
1397
+ "flexible",
1398
+ "adaptable",
1399
+ "growable",
1400
+ "extensible"
1401
+ ]
1402
+ },
1403
+ "cutting-edge": {
1404
+ "severity": "high",
1405
+ "suggestions": [
1406
+ "latest",
1407
+ "newest",
1408
+ "state-of-the-art",
1409
+ "modern",
1410
+ "advanced"
1411
+ ]
1412
+ },
1413
+ "seamless": {
1414
+ "severity": "high",
1415
+ "suggestions": [
1416
+ "smooth",
1417
+ "effortless",
1418
+ "easy",
1419
+ "uninterrupted",
1420
+ "clean"
1421
+ ]
1422
+ },
1423
+ "nuanced": {
1424
+ "severity": "medium",
1425
+ "suggestions": [
1426
+ "subtle",
1427
+ "layered",
1428
+ "complex",
1429
+ "detailed",
1430
+ "refined"
1431
+ ]
1432
+ },
1433
+ "empower": {
1434
+ "severity": "high",
1435
+ "suggestions": [
1436
+ "give power to",
1437
+ "enable",
1438
+ "help",
1439
+ "allow",
1440
+ "free up"
1441
+ ]
1442
+ },
1443
+ "mitigate": {
1444
+ "severity": "high",
1445
+ "suggestions": [
1446
+ "reduce",
1447
+ "lessen",
1448
+ "limit",
1449
+ "ease",
1450
+ "cut down"
1451
+ ]
1452
+ },
1453
+ "elucidate": {
1454
+ "severity": "high",
1455
+ "suggestions": [
1456
+ "explain",
1457
+ "clarify",
1458
+ "show",
1459
+ "make clear",
1460
+ "spell out"
1461
+ ]
1462
+ },
1463
+ "intersect": {
1464
+ "severity": "medium",
1465
+ "suggestions": [
1466
+ "meet",
1467
+ "overlap",
1468
+ "connect",
1469
+ "cross",
1470
+ "link"
1471
+ ]
1472
+ },
1473
+ "redefine": {
1474
+ "severity": "medium",
1475
+ "suggestions": [
1476
+ "change",
1477
+ "reshape",
1478
+ "rethink",
1479
+ "alter",
1480
+ "shift"
1481
+ ]
1482
+ },
1483
+ "impactful": {
1484
+ "severity": "high",
1485
+ "suggestions": [
1486
+ "effective",
1487
+ "meaningful",
1488
+ "powerful",
1489
+ "significant",
1490
+ "strong"
1491
+ ]
1492
+ }
1493
+ },
1494
+ "phrases": {
1495
+ "it is important to note": {
1496
+ "severity": "high",
1497
+ "suggestions": [
1498
+ "note that",
1499
+ "keep in mind",
1500
+ "worth knowing",
1501
+ "remember that"
1502
+ ]
1503
+ },
1504
+ "in today's world": {
1505
+ "severity": "high",
1506
+ "suggestions": [
1507
+ "today",
1508
+ "now",
1509
+ "these days",
1510
+ "at this point",
1511
+ "in our time"
1512
+ ]
1513
+ },
1514
+ "in the realm of": {
1515
+ "severity": "high",
1516
+ "suggestions": [
1517
+ "in",
1518
+ "within",
1519
+ "in the field of",
1520
+ "across",
1521
+ "in the area of"
1522
+ ]
1523
+ },
1524
+ "plays a crucial role": {
1525
+ "severity": "high",
1526
+ "suggestions": [
1527
+ "matters a lot",
1528
+ "is key",
1529
+ "is central to",
1530
+ "shapes",
1531
+ "drives"
1532
+ ]
1533
+ },
1534
+ "it is worth noting": {
1535
+ "severity": "high",
1536
+ "suggestions": [
1537
+ "note that",
1538
+ "importantly",
1539
+ "worth knowing",
1540
+ "also",
1541
+ "keep in mind"
1542
+ ]
1543
+ },
1544
+ "a wide range of": {
1545
+ "severity": "high",
1546
+ "suggestions": [
1547
+ "many",
1548
+ "various",
1549
+ "a variety of",
1550
+ "different",
1551
+ "numerous"
1552
+ ]
1553
+ },
1554
+ "in order to": {
1555
+ "severity": "high",
1556
+ "suggestions": [
1557
+ "to",
1558
+ "so that",
1559
+ "for",
1560
+ "with the aim of",
1561
+ "aiming to"
1562
+ ]
1563
+ },
1564
+ "due to the fact that": {
1565
+ "severity": "high",
1566
+ "suggestions": [
1567
+ "because",
1568
+ "since",
1569
+ "as",
1570
+ "given that",
1571
+ "owing to"
1572
+ ]
1573
+ },
1574
+ "at the end of the day": {
1575
+ "severity": "high",
1576
+ "suggestions": [
1577
+ "ultimately",
1578
+ "in the end",
1579
+ "when all is said and done",
1580
+ "finally",
1581
+ "overall"
1582
+ ]
1583
+ },
1584
+ "on the other hand": {
1585
+ "severity": "medium",
1586
+ "suggestions": [
1587
+ "but",
1588
+ "however",
1589
+ "yet",
1590
+ "alternatively",
1591
+ "in contrast"
1592
+ ]
1593
+ },
1594
+ "in light of": {
1595
+ "severity": "medium",
1596
+ "suggestions": [
1597
+ "given",
1598
+ "considering",
1599
+ "because of",
1600
+ "in view of",
1601
+ "with"
1602
+ ]
1603
+ },
1604
+ "it goes without saying": {
1605
+ "severity": "high",
1606
+ "suggestions": [
1607
+ "clearly",
1608
+ "obviously",
1609
+ "of course",
1610
+ "naturally",
1611
+ "as expected"
1612
+ ]
1613
+ },
1614
+ "serves as a": {
1615
+ "severity": "high",
1616
+ "suggestions": [
1617
+ "is a",
1618
+ "acts as a",
1619
+ "works as a",
1620
+ "functions as a",
1621
+ "acts like a"
1622
+ ]
1623
+ },
1624
+ "in conclusion": {
1625
+ "severity": "high",
1626
+ "suggestions": [
1627
+ "overall",
1628
+ "to sum up",
1629
+ "in short",
1630
+ "all in all",
1631
+ "to wrap up"
1632
+ ]
1633
+ },
1634
+ "as a result": {
1635
+ "severity": "medium",
1636
+ "suggestions": [
1637
+ "so",
1638
+ "therefore",
1639
+ "which means",
1640
+ "because of this",
1641
+ "thus"
1642
+ ]
1643
+ },
1644
+ "in addition to": {
1645
+ "severity": "medium",
1646
+ "suggestions": [
1647
+ "besides",
1648
+ "along with",
1649
+ "on top of",
1650
+ "as well as",
1651
+ "plus"
1652
+ ]
1653
+ },
1654
+ "has the potential to": {
1655
+ "severity": "high",
1656
+ "suggestions": [
1657
+ "could",
1658
+ "might",
1659
+ "can",
1660
+ "may be able to",
1661
+ "is able to"
1662
+ ]
1663
+ },
1664
+ "there is no doubt that": {
1665
+ "severity": "high",
1666
+ "suggestions": [
1667
+ "clearly",
1668
+ "without question",
1669
+ "certainly",
1670
+ "obviously",
1671
+ "undeniably"
1672
+ ]
1673
+ },
1674
+ "this highlights the": {
1675
+ "severity": "high",
1676
+ "suggestions": [
1677
+ "this shows the",
1678
+ "this reveals the",
1679
+ "this points to the",
1680
+ "this makes clear the",
1681
+ "this demonstrates the"
1682
+ ]
1683
+ },
1684
+ "the fact that": {
1685
+ "severity": "medium",
1686
+ "suggestions": [
1687
+ "that",
1688
+ "how",
1689
+ "the reality that",
1690
+ "because",
1691
+ "since"
1692
+ ]
1693
+ },
1694
+ "in terms of": {
1695
+ "severity": "high",
1696
+ "suggestions": [
1697
+ "regarding",
1698
+ "on",
1699
+ "for",
1700
+ "when it comes to",
1701
+ "about"
1702
+ ]
1703
+ },
1704
+ "lends credence to": {
1705
+ "severity": "high",
1706
+ "suggestions": [
1707
+ "supports",
1708
+ "backs up",
1709
+ "strengthens",
1710
+ "validates",
1711
+ "confirms"
1712
+ ]
1713
+ },
1714
+ "is imperative that": {
1715
+ "severity": "high",
1716
+ "suggestions": [
1717
+ "must",
1718
+ "needs to",
1719
+ "is essential that",
1720
+ "is necessary that",
1721
+ "requires that"
1722
+ ]
1723
+ },
1724
+ "it is essential to": {
1725
+ "severity": "high",
1726
+ "suggestions": [
1727
+ "you must",
1728
+ "it is key to",
1729
+ "you need to",
1730
+ "it is critical to",
1731
+ "it is vital to"
1732
+ ]
1733
+ },
1734
+ "it is crucial that": {
1735
+ "severity": "high",
1736
+ "suggestions": [
1737
+ "it is key that",
1738
+ "it is necessary that",
1739
+ "you must",
1740
+ "it matters that",
1741
+ "it is important that"
1742
+ ]
1743
+ },
1744
+ "it should be noted that": {
1745
+ "severity": "high",
1746
+ "suggestions": [
1747
+ "note that",
1748
+ "keep in mind that",
1749
+ "it is worth knowing that",
1750
+ "remember that",
1751
+ "importantly"
1752
+ ]
1753
+ },
1754
+ "it can be argued that": {
1755
+ "severity": "medium",
1756
+ "suggestions": [
1757
+ "one could say that",
1758
+ "some might argue that",
1759
+ "arguably",
1760
+ "it seems that",
1761
+ "a case can be made that"
1762
+ ]
1763
+ },
1764
+ "it is evident that": {
1765
+ "severity": "high",
1766
+ "suggestions": [
1767
+ "clearly",
1768
+ "it is clear that",
1769
+ "obviously",
1770
+ "plainly",
1771
+ "it is apparent that"
1772
+ ]
1773
+ },
1774
+ "it is clear that": {
1775
+ "severity": "high",
1776
+ "suggestions": [
1777
+ "clearly",
1778
+ "obviously",
1779
+ "plainly",
1780
+ "without doubt",
1781
+ "as is plain"
1782
+ ]
1783
+ },
1784
+ "this is due to": {
1785
+ "severity": "medium",
1786
+ "suggestions": [
1787
+ "this is because",
1788
+ "this comes from",
1789
+ "this results from",
1790
+ "this stems from",
1791
+ "the reason is"
1792
+ ]
1793
+ },
1794
+ "this can be attributed to": {
1795
+ "severity": "high",
1796
+ "suggestions": [
1797
+ "this is because of",
1798
+ "this comes from",
1799
+ "the cause is",
1800
+ "this stems from",
1801
+ "this is due to"
1802
+ ]
1803
+ },
1804
+ "when considering": {
1805
+ "severity": "medium",
1806
+ "suggestions": [
1807
+ "when looking at",
1808
+ "when thinking about",
1809
+ "given",
1810
+ "with",
1811
+ "if we look at"
1812
+ ]
1813
+ },
1814
+ "taking into account": {
1815
+ "severity": "medium",
1816
+ "suggestions": [
1817
+ "considering",
1818
+ "given",
1819
+ "keeping in mind",
1820
+ "factoring in",
1821
+ "with"
1822
+ ]
1823
+ },
1824
+ "with regard to": {
1825
+ "severity": "high",
1826
+ "suggestions": [
1827
+ "on",
1828
+ "about",
1829
+ "regarding",
1830
+ "when it comes to",
1831
+ "for"
1832
+ ]
1833
+ },
1834
+ "with respect to": {
1835
+ "severity": "high",
1836
+ "suggestions": [
1837
+ "on",
1838
+ "about",
1839
+ "regarding",
1840
+ "concerning",
1841
+ "for"
1842
+ ]
1843
+ },
1844
+ "in relation to": {
1845
+ "severity": "medium",
1846
+ "suggestions": [
1847
+ "about",
1848
+ "regarding",
1849
+ "compared to",
1850
+ "relative to",
1851
+ "linked to"
1852
+ ]
1853
+ },
1854
+ "in the context of": {
1855
+ "severity": "high",
1856
+ "suggestions": [
1857
+ "within",
1858
+ "in",
1859
+ "given",
1860
+ "under",
1861
+ "as part of"
1862
+ ]
1863
+ },
1864
+ "from this perspective": {
1865
+ "severity": "medium",
1866
+ "suggestions": [
1867
+ "from this view",
1868
+ "seen this way",
1869
+ "from this angle",
1870
+ "with this in mind",
1871
+ "looking at it this way"
1872
+ ]
1873
+ },
1874
+ "in this regard": {
1875
+ "severity": "high",
1876
+ "suggestions": [
1877
+ "here",
1878
+ "in this case",
1879
+ "on this point",
1880
+ "about this",
1881
+ "with this in mind"
1882
+ ]
1883
+ },
1884
+ "as mentioned above": {
1885
+ "severity": "high",
1886
+ "suggestions": [
1887
+ "as noted earlier",
1888
+ "as I said",
1889
+ "as shown above",
1890
+ "as we saw",
1891
+ "earlier"
1892
+ ]
1893
+ },
1894
+ "as previously stated": {
1895
+ "severity": "high",
1896
+ "suggestions": [
1897
+ "as noted earlier",
1898
+ "as I said",
1899
+ "as mentioned",
1900
+ "as discussed",
1901
+ "earlier"
1902
+ ]
1903
+ },
1904
+ "as discussed earlier": {
1905
+ "severity": "medium",
1906
+ "suggestions": [
1907
+ "as noted",
1908
+ "as I mentioned",
1909
+ "earlier",
1910
+ "as shown above",
1911
+ "as we covered"
1912
+ ]
1913
+ },
1914
+ "it is worth mentioning": {
1915
+ "severity": "high",
1916
+ "suggestions": [
1917
+ "note that",
1918
+ "also",
1919
+ "worth knowing",
1920
+ "I should add",
1921
+ "it helps to know"
1922
+ ]
1923
+ },
1924
+ "needless to say": {
1925
+ "severity": "high",
1926
+ "suggestions": [
1927
+ "obviously",
1928
+ "clearly",
1929
+ "of course",
1930
+ "naturally",
1931
+ "as expected"
1932
+ ]
1933
+ },
1934
+ "of particular importance": {
1935
+ "severity": "high",
1936
+ "suggestions": [
1937
+ "especially important",
1938
+ "most importantly",
1939
+ "notably",
1940
+ "crucially",
1941
+ "key to this is"
1942
+ ]
1943
+ },
1944
+ "of great significance": {
1945
+ "severity": "high",
1946
+ "suggestions": [
1947
+ "very important",
1948
+ "highly significant",
1949
+ "very meaningful",
1950
+ "quite relevant",
1951
+ "especially notable"
1952
+ ]
1953
+ },
1954
+ "plays an important role": {
1955
+ "severity": "high",
1956
+ "suggestions": [
1957
+ "matters",
1958
+ "is important to",
1959
+ "is key to",
1960
+ "shapes",
1961
+ "affects"
1962
+ ]
1963
+ },
1964
+ "plays a significant role": {
1965
+ "severity": "high",
1966
+ "suggestions": [
1967
+ "matters a lot",
1968
+ "has a big effect",
1969
+ "is key to",
1970
+ "heavily influences",
1971
+ "greatly affects"
1972
+ ]
1973
+ },
1974
+ "plays a key role": {
1975
+ "severity": "high",
1976
+ "suggestions": [
1977
+ "is central to",
1978
+ "is key to",
1979
+ "drives",
1980
+ "is critical for",
1981
+ "shapes"
1982
+ ]
1983
+ },
1984
+ "has a significant impact": {
1985
+ "severity": "high",
1986
+ "suggestions": [
1987
+ "greatly affects",
1988
+ "has a big effect on",
1989
+ "strongly influences",
1990
+ "shapes",
1991
+ "matters greatly to"
1992
+ ]
1993
+ },
1994
+ "has a profound impact": {
1995
+ "severity": "high",
1996
+ "suggestions": [
1997
+ "deeply affects",
1998
+ "has a deep effect on",
1999
+ "strongly shapes",
2000
+ "greatly changes",
2001
+ "transforms"
2002
+ ]
2003
+ },
2004
+ "leads to": {
2005
+ "severity": "low",
2006
+ "suggestions": [
2007
+ "causes",
2008
+ "results in",
2009
+ "brings about",
2010
+ "creates",
2011
+ "produces"
2012
+ ]
2013
+ },
2014
+ "results in": {
2015
+ "severity": "low",
2016
+ "suggestions": [
2017
+ "causes",
2018
+ "leads to",
2019
+ "creates",
2020
+ "produces",
2021
+ "brings about"
2022
+ ]
2023
+ },
2024
+ "gives rise to": {
2025
+ "severity": "medium",
2026
+ "suggestions": [
2027
+ "causes",
2028
+ "leads to",
2029
+ "creates",
2030
+ "produces",
2031
+ "brings about"
2032
+ ]
2033
+ },
2034
+ "shed light on": {
2035
+ "severity": "high",
2036
+ "suggestions": [
2037
+ "explain",
2038
+ "clarify",
2039
+ "reveal",
2040
+ "show",
2041
+ "make clearer"
2042
+ ]
2043
+ },
2044
+ "pave the way for": {
2045
+ "severity": "high",
2046
+ "suggestions": [
2047
+ "open the door to",
2048
+ "prepare for",
2049
+ "make possible",
2050
+ "enable",
2051
+ "set the stage for"
2052
+ ]
2053
+ },
2054
+ "in the field of": {
2055
+ "severity": "medium",
2056
+ "suggestions": [
2057
+ "in",
2058
+ "within",
2059
+ "across",
2060
+ "in the area of",
2061
+ "in the world of"
2062
+ ]
2063
+ },
2064
+ "in the area of": {
2065
+ "severity": "medium",
2066
+ "suggestions": [
2067
+ "in",
2068
+ "within",
2069
+ "across",
2070
+ "in",
2071
+ "around"
2072
+ ]
2073
+ },
2074
+ "within the scope of": {
2075
+ "severity": "medium",
2076
+ "suggestions": [
2077
+ "within",
2078
+ "as part of",
2079
+ "included in",
2080
+ "under",
2081
+ "covered by"
2082
+ ]
2083
+ },
2084
+ "across a range of": {
2085
+ "severity": "medium",
2086
+ "suggestions": [
2087
+ "across many",
2088
+ "in various",
2089
+ "throughout",
2090
+ "in different",
2091
+ "across different"
2092
+ ]
2093
+ },
2094
+ "in a variety of": {
2095
+ "severity": "medium",
2096
+ "suggestions": [
2097
+ "in many",
2098
+ "across different",
2099
+ "in various",
2100
+ "in several",
2101
+ "in numerous"
2102
+ ]
2103
+ },
2104
+ "to a large extent": {
2105
+ "severity": "medium",
2106
+ "suggestions": [
2107
+ "largely",
2108
+ "mostly",
2109
+ "for the most part",
2110
+ "mainly",
2111
+ "in large part"
2112
+ ]
2113
+ },
2114
+ "to a great extent": {
2115
+ "severity": "medium",
2116
+ "suggestions": [
2117
+ "largely",
2118
+ "greatly",
2119
+ "mostly",
2120
+ "significantly",
2121
+ "to a significant degree"
2122
+ ]
2123
+ },
2124
+ "to some extent": {
2125
+ "severity": "low",
2126
+ "suggestions": [
2127
+ "partly",
2128
+ "somewhat",
2129
+ "in part",
2130
+ "partially",
2131
+ "to a degree"
2132
+ ]
2133
+ },
2134
+ "in many ways": {
2135
+ "severity": "low",
2136
+ "suggestions": [
2137
+ "in several respects",
2138
+ "on many levels",
2139
+ "across multiple dimensions",
2140
+ "in various ways",
2141
+ "broadly"
2142
+ ]
2143
+ },
2144
+ "in some ways": {
2145
+ "severity": "low",
2146
+ "suggestions": [
2147
+ "partly",
2148
+ "in part",
2149
+ "to some degree",
2150
+ "in certain respects",
2151
+ "somewhat"
2152
+ ]
2153
+ },
2154
+ "paradigm shift": {
2155
+ "severity": "high",
2156
+ "suggestions": [
2157
+ "major change",
2158
+ "fundamental shift",
2159
+ "big change",
2160
+ "turning point",
2161
+ "new direction"
2162
+ ]
2163
+ },
2164
+ "in a holistic manner": {
2165
+ "severity": "high",
2166
+ "suggestions": [
2167
+ "as a whole",
2168
+ "broadly",
2169
+ "altogether",
2170
+ "[remove — just say the thing directly]"
2171
+ ]
2172
+ },
2173
+ "going forward": {
2174
+ "severity": "high",
2175
+ "suggestions": [
2176
+ "from now on",
2177
+ "in the future",
2178
+ "next",
2179
+ "[remove — often redundant]"
2180
+ ]
2181
+ },
2182
+ "moving forward": {
2183
+ "severity": "high",
2184
+ "suggestions": [
2185
+ "from now on",
2186
+ "going ahead",
2187
+ "next",
2188
+ "[remove — often redundant]"
2189
+ ]
2190
+ },
2191
+ "stands as a testament": {
2192
+ "severity": "high",
2193
+ "suggestions": [
2194
+ "proves",
2195
+ "shows",
2196
+ "is proof of",
2197
+ "demonstrates"
2198
+ ]
2199
+ },
2200
+ "offers a unique opportunity": {
2201
+ "severity": "high",
2202
+ "suggestions": [
2203
+ "gives us a chance to",
2204
+ "lets us",
2205
+ "opens the door to",
2206
+ "makes it possible to"
2207
+ ]
2208
+ }
2209
+ }
2210
+ }
app/data/heuristic_patterns.json ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "transition_starters": [
3
+ "Furthermore",
4
+ "Moreover",
5
+ "Additionally",
6
+ "Consequently",
7
+ "Nevertheless",
8
+ "However",
9
+ "Therefore",
10
+ "Thus",
11
+ "Hence",
12
+ "Subsequently",
13
+ "Conversely",
14
+ "Similarly",
15
+ "Likewise",
16
+ "Notably",
17
+ "Importantly",
18
+ "Significantly",
19
+ "Evidently",
20
+ "Clearly",
21
+ "Essentially",
22
+ "Ultimately",
23
+ "Generally",
24
+ "Typically",
25
+ "Traditionally",
26
+ "Historically",
27
+ "Currently",
28
+ "Recently",
29
+ "Previously",
30
+ "Initially",
31
+ "Finally",
32
+ "Meanwhile",
33
+ "Simultaneously",
34
+ "Otherwise",
35
+ "Alternatively",
36
+ "Indeed",
37
+ "Certainly",
38
+ "Undoubtedly",
39
+ "Apparently",
40
+ "Presumably",
41
+ "Arguably",
42
+ "Admittedly",
43
+ "Fortunately",
44
+ "Unfortunately",
45
+ "Surprisingly",
46
+ "Interestingly",
47
+ "Remarkably",
48
+ "Specifically",
49
+ "Particularly",
50
+ "Accordingly",
51
+ "Nonetheless",
52
+ "Notwithstanding",
53
+ "Correspondingly",
54
+ "Ostensibly",
55
+ "Henceforth",
56
+ "Thereupon",
57
+ "In addition",
58
+ "As a result",
59
+ "On the other hand",
60
+ "In contrast",
61
+ "In fact",
62
+ "In particular",
63
+ "In conclusion",
64
+ "To summarize",
65
+ "In summary",
66
+ "In brief",
67
+ "With this in mind",
68
+ "In light of this",
69
+ "Building on this",
70
+ "It is important to note that",
71
+ "It is worth noting that",
72
+ "It should be noted that",
73
+ "It can be argued that",
74
+ "It is clear that",
75
+ "It goes without saying that",
76
+ "It is well known that",
77
+ "There is no doubt that",
78
+ "As mentioned above",
79
+ "As discussed previously"
80
+ ],
81
+ "ai_vocabulary_triggers": [
82
+ "utilize",
83
+ "utilizes",
84
+ "utilized",
85
+ "utilizing",
86
+ "leverage",
87
+ "leverages",
88
+ "leveraged",
89
+ "leveraging",
90
+ "facilitate",
91
+ "facilitates",
92
+ "facilitated",
93
+ "facilitating",
94
+ "robust",
95
+ "paradigm",
96
+ "paradigms",
97
+ "paradigmatic",
98
+ "unprecedented",
99
+ "multifaceted",
100
+ "holistic",
101
+ "synergy",
102
+ "synergistic",
103
+ "synergies",
104
+ "comprehensive",
105
+ "nuanced",
106
+ "nuances",
107
+ "pivotal",
108
+ "crucial",
109
+ "critical",
110
+ "imperative",
111
+ "vital",
112
+ "essential",
113
+ "fundamental",
114
+ "foundational",
115
+ "transformative",
116
+ "groundbreaking",
117
+ "innovative",
118
+ "revolutionary",
119
+ "cutting-edge",
120
+ "state-of-the-art",
121
+ "sophisticated",
122
+ "intricate",
123
+ "complex",
124
+ "delve",
125
+ "delves",
126
+ "delved",
127
+ "delving",
128
+ "underscore",
129
+ "underscores",
130
+ "underscored",
131
+ "underscoring",
132
+ "highlight",
133
+ "highlights",
134
+ "highlighted",
135
+ "highlighting",
136
+ "demonstrate",
137
+ "demonstrates",
138
+ "demonstrated",
139
+ "demonstrating",
140
+ "elucidate",
141
+ "elucidates",
142
+ "elucidated",
143
+ "elucidating",
144
+ "encompass",
145
+ "encompasses",
146
+ "encompassed",
147
+ "encompassing",
148
+ "pertain",
149
+ "pertains",
150
+ "pertaining",
151
+ "constitute",
152
+ "constitutes",
153
+ "constituting",
154
+ "delineate",
155
+ "delineates",
156
+ "delineating",
157
+ "propagate",
158
+ "propagates",
159
+ "propagating",
160
+ "mitigate",
161
+ "mitigates",
162
+ "mitigated",
163
+ "mitigating",
164
+ "optimize",
165
+ "optimizes",
166
+ "optimized",
167
+ "optimizing",
168
+ "streamline",
169
+ "streamlines",
170
+ "streamlined",
171
+ "streamlining",
172
+ "paramount",
173
+ "quintessential",
174
+ "salient",
175
+ "pertinent",
176
+ "endeavor",
177
+ "endeavors",
178
+ "endeavored",
179
+ "endeavoring",
180
+ "ascertain",
181
+ "ascertains",
182
+ "ascertained",
183
+ "ascertaining",
184
+ "inception",
185
+ "implementation",
186
+ "instantiation",
187
+ "manifestation",
188
+ "ramification",
189
+ "ramifications",
190
+ "implications",
191
+ "aforementioned",
192
+ "herein",
193
+ "thereof",
194
+ "thereby",
195
+ "wherein",
196
+ "whereby",
197
+ "henceforth",
198
+ "thereupon",
199
+ "heretofore"
200
+ ],
201
+ "ai_phrase_patterns": [
202
+ "it is important to note that",
203
+ "it is worth noting that",
204
+ "it should be noted that",
205
+ "it is crucial to understand",
206
+ "it goes without saying",
207
+ "it is well established that",
208
+ "it has been demonstrated that",
209
+ "it has been shown that",
210
+ "it is widely recognized that",
211
+ "it is generally accepted that",
212
+ "needless to say",
213
+ "as previously mentioned",
214
+ "as discussed above",
215
+ "as outlined above",
216
+ "as noted earlier",
217
+ "in the context of",
218
+ "in the realm of",
219
+ "in the domain of",
220
+ "in the field of",
221
+ "across a wide range of",
222
+ "across a variety of",
223
+ "a wide array of",
224
+ "a myriad of",
225
+ "a plethora of",
226
+ "a multitude of",
227
+ "plays a crucial role",
228
+ "plays a pivotal role",
229
+ "plays a vital role",
230
+ "plays an important role",
231
+ "plays a key role",
232
+ "serves as a foundation",
233
+ "serves as a cornerstone",
234
+ "of paramount importance",
235
+ "of utmost importance",
236
+ "of critical importance",
237
+ "cannot be overstated",
238
+ "it is worth emphasizing",
239
+ "it must be emphasized",
240
+ "it is essential to recognize",
241
+ "it bears mentioning",
242
+ "it stands to reason",
243
+ "one cannot overlook",
244
+ "it is becoming increasingly",
245
+ "in today's rapidly changing",
246
+ "in the modern era",
247
+ "in an ever-changing landscape",
248
+ "in today's fast-paced world",
249
+ "at its core",
250
+ "at the heart of",
251
+ "the fact that",
252
+ "by the same token",
253
+ "to a certain extent",
254
+ "to a large extent",
255
+ "to a significant extent",
256
+ "from a holistic perspective",
257
+ "from a comprehensive standpoint",
258
+ "in and of itself",
259
+ "first and foremost",
260
+ "last but not least",
261
+ "above and beyond",
262
+ "each and every",
263
+ "time and again",
264
+ "due to the fact that",
265
+ "in order to",
266
+ "for the purpose of",
267
+ "with the aim of",
268
+ "with a view to",
269
+ "in an effort to"
270
+ ],
271
+ "structural_patterns": {
272
+ "description": "Rules describing sentence-level structural characteristics that strongly correlate with AI-generated text. These are applied heuristically across a paragraph or document window rather than on individual sentences in isolation.",
273
+ "rules": [
274
+ {
275
+ "rule": "uniform_length",
276
+ "description": "Sentences cluster tightly around the paragraph mean length. AI text exhibits low variance in sentence length, with most sentences falling within plus or minus 3 words of the mean word count for the surrounding paragraph.",
277
+ "threshold": 3,
278
+ "unit": "words",
279
+ "window": "paragraph",
280
+ "flag_if": "stddev_sentence_length < 3 AND sentence_count >= 4"
281
+ },
282
+ {
283
+ "rule": "passive_voice_heavy",
284
+ "description": "Overuse of passive voice constructions. AI text frequently uses passive structures such as 'is/are/was/were + past participle' and 'has/have been + past participle', often to maintain a formal or impersonal register.",
285
+ "indicators": [
286
+ "is [verb]ed",
287
+ "are [verb]ed",
288
+ "was [verb]ed",
289
+ "were [verb]ed",
290
+ "has been [verb]ed",
291
+ "have been [verb]ed",
292
+ "had been [verb]ed",
293
+ "will be [verb]ed",
294
+ "can be [verb]ed",
295
+ "should be [verb]ed",
296
+ "must be [verb]ed",
297
+ "may be [verb]ed"
298
+ ],
299
+ "threshold_ratio": 0.35,
300
+ "flag_if": "passive_sentence_ratio > 0.35 AND sentence_count >= 3"
301
+ },
302
+ {
303
+ "rule": "nominalization_heavy",
304
+ "description": "Excessive conversion of verbs or adjectives into abstract nouns (nominalization). AI text frequently uses abstract noun forms ending in -tion, -ment, -ance, -ence, -ity, -ness, -ism, -al instead of the more direct verb or adjective form.",
305
+ "suffixes": [
306
+ "-tion",
307
+ "-ation",
308
+ "-ition",
309
+ "-ment",
310
+ "-ance",
311
+ "-ence",
312
+ "-ity",
313
+ "-ness",
314
+ "-ism",
315
+ "-ization",
316
+ "-isation",
317
+ "-ification",
318
+ "-al"
319
+ ],
320
+ "examples": [
321
+ "implementation (instead of: implement)",
322
+ "utilization (instead of: use)",
323
+ "facilitation (instead of: help)",
324
+ "enhancement (instead of: improve)",
325
+ "assessment (instead of: assess)",
326
+ "development (instead of: develop)",
327
+ "establishment (instead of: establish)",
328
+ "improvement (instead of: improve)",
329
+ "achievement (instead of: achieve)",
330
+ "consideration (instead of: consider)"
331
+ ],
332
+ "threshold_ratio": 0.12,
333
+ "flag_if": "nominalization_token_ratio > 0.12 AND sentence_count >= 3"
334
+ },
335
+ {
336
+ "rule": "parallel_list_overuse",
337
+ "description": "AI text frequently constructs sentences as enumerations of three or more parallel items, often with identical grammatical structure, contributing to a formulaic and mechanical rhythm.",
338
+ "flag_if": "parallel_items_per_sentence > 2.5 averaged over paragraph"
339
+ },
340
+ {
341
+ "rule": "hedge_phrase_density",
342
+ "description": "High density of epistemic hedging phrases. While hedging is normal in academic writing, AI text overuses hedges uniformly across all sentences rather than selectively.",
343
+ "indicators": [
344
+ "may",
345
+ "might",
346
+ "could",
347
+ "would",
348
+ "arguably",
349
+ "potentially",
350
+ "possibly",
351
+ "perhaps",
352
+ "seemingly",
353
+ "apparently",
354
+ "presumably",
355
+ "ostensibly",
356
+ "to some extent",
357
+ "in some cases",
358
+ "under certain circumstances"
359
+ ],
360
+ "threshold_ratio": 0.40,
361
+ "flag_if": "hedged_sentence_ratio > 0.40 AND sentence_count >= 4"
362
+ }
363
+ ]
364
+ }
365
+ }
app/data/transition_words.json ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sentence_starters": [
3
+ "Furthermore",
4
+ "Moreover",
5
+ "Additionally",
6
+ "Consequently",
7
+ "Nevertheless",
8
+ "However",
9
+ "Therefore",
10
+ "Thus",
11
+ "Hence",
12
+ "Subsequently",
13
+ "Conversely",
14
+ "Similarly",
15
+ "Likewise",
16
+ "Notably",
17
+ "Importantly",
18
+ "Significantly",
19
+ "Evidently",
20
+ "Clearly",
21
+ "Essentially",
22
+ "Ultimately",
23
+ "Generally",
24
+ "Typically",
25
+ "Traditionally",
26
+ "Historically",
27
+ "Currently",
28
+ "Recently",
29
+ "Previously",
30
+ "Initially",
31
+ "Finally",
32
+ "Meanwhile",
33
+ "Simultaneously",
34
+ "Otherwise",
35
+ "Alternatively",
36
+ "Indeed",
37
+ "Certainly",
38
+ "Undoubtedly",
39
+ "Apparently",
40
+ "Presumably",
41
+ "Arguably",
42
+ "Supposedly",
43
+ "Admittedly",
44
+ "Fortunately",
45
+ "Unfortunately",
46
+ "Surprisingly",
47
+ "Interestingly",
48
+ "Remarkably",
49
+ "Specifically",
50
+ "Particularly",
51
+ "Notably",
52
+ "Accordingly",
53
+ "Nonetheless",
54
+ "Notwithstanding",
55
+ "Albeit",
56
+ "Henceforth",
57
+ "Thereupon",
58
+ "Thereafter",
59
+ "Correspondingly",
60
+ "Proportionally",
61
+ "Ostensibly"
62
+ ],
63
+ "connector_phrases": [
64
+ "In addition",
65
+ "As a result",
66
+ "On the other hand",
67
+ "In contrast",
68
+ "At the same time",
69
+ "In fact",
70
+ "In particular",
71
+ "For example",
72
+ "For instance",
73
+ "In other words",
74
+ "That is to say",
75
+ "In conclusion",
76
+ "To summarize",
77
+ "To sum up",
78
+ "In summary",
79
+ "In brief",
80
+ "To this end",
81
+ "With this in mind",
82
+ "In this regard",
83
+ "In this context",
84
+ "In light of this",
85
+ "Given this",
86
+ "Building on this",
87
+ "Expanding on this",
88
+ "Taking this further",
89
+ "On the contrary",
90
+ "By contrast",
91
+ "By comparison",
92
+ "As a consequence",
93
+ "As such",
94
+ "In turn",
95
+ "As a whole",
96
+ "On balance",
97
+ "All things considered",
98
+ "Taken together"
99
+ ],
100
+ "formulaic_openers": [
101
+ "It is important to note that",
102
+ "It is worth noting that",
103
+ "It should be noted that",
104
+ "It can be argued that",
105
+ "It is clear that",
106
+ "It is evident that",
107
+ "It goes without saying that",
108
+ "It is well known that",
109
+ "It is widely recognized that",
110
+ "There is no doubt that",
111
+ "There is a growing consensus that",
112
+ "As mentioned above",
113
+ "As discussed previously",
114
+ "As outlined above",
115
+ "It is crucial to understand that",
116
+ "It must be emphasized that",
117
+ "It is essential to recognize that",
118
+ "It is worth considering that",
119
+ "It is reasonable to suggest that",
120
+ "It is generally accepted that",
121
+ "It has been observed that",
122
+ "It has been established that",
123
+ "It has been demonstrated that",
124
+ "It has been shown that",
125
+ "It is widely understood that",
126
+ "It bears mentioning that",
127
+ "It is often the case that",
128
+ "It stands to reason that",
129
+ "It is becoming increasingly clear that",
130
+ "It is universally acknowledged that",
131
+ "One must consider that",
132
+ "One could argue that",
133
+ "One cannot overlook the fact that",
134
+ "This highlights the fact that",
135
+ "This underscores the importance of"
136
+ ]
137
+ }
app/main.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ import time
12
+ from contextlib import asynccontextmanager
13
+ from typing import AsyncGenerator
14
+
15
+ from fastapi import FastAPI
16
+ from fastapi.middleware.cors import CORSMiddleware
17
+ from fastapi.staticfiles import StaticFiles
18
+
19
+ from app.config import get_settings
20
+
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
28
+ _models_loaded: bool = False
29
+
30
+
31
+ @asynccontextmanager
32
+ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
33
+ """Load all heavyweight resources once at startup, release on shutdown."""
34
+ global _start_time, _models_loaded
35
+
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' …", settings.spacy_model)
46
+ nlp = spacy.load(settings.spacy_model)
47
+ app.state.nlp = nlp
48
+ logger.info("spaCy loaded.")
49
+ except Exception as exc:
50
+ logger.error("Failed to load spaCy model: %s", exc)
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.")
61
+ except Exception as exc:
62
+ logger.error("Failed to load perplexity scorer: %s", exc)
63
+ app.state.perplexity_scorer = None
64
+
65
+ # ---- 3. Data files (vocabulary, transitions, heuristics) ----
66
+ try:
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.")
84
+ except Exception as exc:
85
+ logger.error("Failed to initialise LanguageTool: %s", exc)
86
+ app.state.language_tool = None
87
+
88
+ # ---- 5. Warm up Qwen2.5 with a dummy inference ----
89
+ if app.state.perplexity_scorer is not None:
90
+ try:
91
+ logger.info("Warming up Qwen2.5-0.5B …")
92
+ app.state.perplexity_scorer.score_sentence("This is a warm-up sentence.")
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 hasattr(app.state, "perplexity_scorer") and app.state.perplexity_scorer:
105
+ del app.state.perplexity_scorer
106
+ if hasattr(app.state, "language_tool") and app.state.language_tool:
107
+ app.state.language_tool.close()
108
+ logger.info("Shutdown complete.")
109
+
110
+
111
+ # ---------------------------------------------------------------------------
112
+ # FastAPI application
113
+ # ---------------------------------------------------------------------------
114
+
115
+ def create_app() -> FastAPI:
116
+ """Factory function that creates and configures the FastAPI application."""
117
+ settings = get_settings()
118
+
119
+ logging.basicConfig(
120
+ level=getattr(logging, settings.log_level),
121
+ format="%(asctime)s %(levelname)-8s %(name)s %(message)s",
122
+ )
123
+
124
+ application = FastAPI(
125
+ title="Humanization Engine",
126
+ description=(
127
+ "Analysis-Guided LLM Rewrite — bypasses AI detection while "
128
+ "preserving academic quality."
129
+ ),
130
+ version="1.0.0",
131
+ lifespan=lifespan,
132
+ )
133
+
134
+ # CORS — allow all origins for development
135
+ application.add_middleware(
136
+ CORSMiddleware,
137
+ allow_origins=["*"],
138
+ allow_credentials=True,
139
+ allow_methods=["*"],
140
+ allow_headers=["*"],
141
+ )
142
+
143
+ # API routes
144
+ from app.api.routes import router as api_router # noqa: E402
145
+
146
+ application.include_router(api_router)
147
+
148
+ # Serve frontend as static files
149
+ try:
150
+ application.mount(
151
+ "/",
152
+ StaticFiles(directory="frontend", html=True),
153
+ name="frontend",
154
+ )
155
+ except Exception:
156
+ # frontend directory may not exist yet during testing
157
+ pass
158
+
159
+ return application
160
+
161
+
162
+ app = create_app()
163
+
164
+
165
+ # ---------------------------------------------------------------------------
166
+ # Expose startup time and model status for the /health endpoint
167
+ # ---------------------------------------------------------------------------
168
+
169
+ def get_start_time() -> float:
170
+ return _start_time
171
+
172
+
173
+ def get_models_loaded() -> bool:
174
+ return _models_loaded
app/prompts/__init__.py ADDED
File without changes
app/utils/__init__.py ADDED
File without changes
app/utils/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (151 Bytes). View file
 
app/utils/__pycache__/text_utils.cpython-313.pyc ADDED
Binary file (4.6 kB). View file
 
app/utils/text_utils.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Text utility functions used across all pipeline stages.
3
+
4
+ All functions are pure (no side effects) and operate on plain strings.
5
+ spaCy is used for sentence splitting to ensure accuracy; callers must pass
6
+ the loaded nlp object rather than importing it here (keeps this module
7
+ side-effect free and testable without spaCy installed).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ import statistics
14
+ from typing import TYPE_CHECKING
15
+
16
+ if TYPE_CHECKING:
17
+ import spacy # type: ignore
18
+
19
+
20
+ # ---------------------------------------------------------------------------
21
+ # Word counting
22
+ # ---------------------------------------------------------------------------
23
+
24
+
25
+ def count_words(text: str) -> int:
26
+ """Return the number of whitespace-delimited tokens in *text*.
27
+
28
+ Args:
29
+ text: Input string (any length).
30
+
31
+ Returns:
32
+ Integer word count. Empty or whitespace-only strings return 0.
33
+ """
34
+ return len(text.split())
35
+
36
+
37
+ # ---------------------------------------------------------------------------
38
+ # Sentence splitting
39
+ # ---------------------------------------------------------------------------
40
+
41
+
42
+ def split_sentences(text: str, nlp: "spacy.Language | None" = None) -> list[str]:
43
+ """Split *text* into a list of sentence strings.
44
+
45
+ Uses spaCy's sentenciser when *nlp* is provided for high accuracy.
46
+ Falls back to a simple regex-based splitter when spaCy is unavailable
47
+ (e.g. in unit tests that do not load the model).
48
+
49
+ Args:
50
+ text: The input text to split.
51
+ nlp: An already-loaded spaCy Language model, or None.
52
+
53
+ Returns:
54
+ List of sentence strings with leading/trailing whitespace stripped.
55
+ Empty sentences are excluded.
56
+ """
57
+ if nlp is not None:
58
+ doc = nlp(text)
59
+ return [sent.text.strip() for sent in doc.sents if sent.text.strip()]
60
+
61
+ # Fallback: split on ". ", "! ", "? " boundaries
62
+ raw = re.split(r"(?<=[.!?])\s+", text.strip())
63
+ return [s.strip() for s in raw if s.strip()]
64
+
65
+
66
+ # ---------------------------------------------------------------------------
67
+ # Burstiness / sentence-length statistics
68
+ # ---------------------------------------------------------------------------
69
+
70
+
71
+ def calculate_burstiness(sentence_lengths: list[int]) -> dict[str, float]:
72
+ """Calculate burstiness statistics for a list of sentence word-counts.
73
+
74
+ Burstiness is measured by the coefficient of variation (CV = std / mean).
75
+ Human writing typically has CV ≥ 0.45; AI text tends to cluster around
76
+ CV 0.15-0.30.
77
+
78
+ Args:
79
+ sentence_lengths: List of word counts, one per sentence.
80
+
81
+ Returns:
82
+ Dict with keys: mean, std, cv, min_length, max_length.
83
+ If fewer than 2 sentences are provided all values are 0.0.
84
+ """
85
+ if len(sentence_lengths) < 2:
86
+ single = float(sentence_lengths[0]) if sentence_lengths else 0.0
87
+ return {
88
+ "mean": single,
89
+ "std": 0.0,
90
+ "cv": 0.0,
91
+ "min_length": single,
92
+ "max_length": single,
93
+ }
94
+
95
+ mean = statistics.mean(sentence_lengths)
96
+ std = statistics.stdev(sentence_lengths)
97
+ cv = std / mean if mean > 0 else 0.0
98
+
99
+ return {
100
+ "mean": round(mean, 2),
101
+ "std": round(std, 2),
102
+ "cv": round(cv, 4),
103
+ "min_length": float(min(sentence_lengths)),
104
+ "max_length": float(max(sentence_lengths)),
105
+ }
106
+
107
+
108
+ # ---------------------------------------------------------------------------
109
+ # Expansion / length comparison
110
+ # ---------------------------------------------------------------------------
111
+
112
+
113
+ def calculate_expansion_percentage(input_count: int, output_count: int) -> float:
114
+ """Return how much longer (as a percentage) the output is vs the input.
115
+
116
+ Args:
117
+ input_count: Word count of the original text.
118
+ output_count: Word count of the rewritten text.
119
+
120
+ Returns:
121
+ Positive value means expansion; negative means contraction.
122
+ Returns 0.0 when input_count is 0.
123
+ """
124
+ if input_count == 0:
125
+ return 0.0
126
+ return round((output_count - input_count) / input_count * 100, 2)
127
+
128
+
129
+ # ---------------------------------------------------------------------------
130
+ # Sentence word-count helper
131
+ # ---------------------------------------------------------------------------
132
+
133
+
134
+ def sentence_word_counts(sentences: list[str]) -> list[int]:
135
+ """Return a list of word counts for each sentence.
136
+
137
+ Args:
138
+ sentences: List of sentence strings.
139
+
140
+ Returns:
141
+ List of integers, same length as *sentences*.
142
+ """
143
+ return [count_words(s) for s in sentences]
app/utils/token_utils.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Token counting and max_tokens calculation utilities.
3
+
4
+ We deliberately avoid importing a tokeniser here to keep this module
5
+ dependency-free. Token counts are approximated using a conservative
6
+ words-to-tokens ratio (1 word ≈ 1.4 tokens for English prose).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ # Empirical words-to-tokens ratio for English prose.
12
+ # Claude/GPT tokenisers typically produce ~1.3-1.5 tokens per word.
13
+ _WORDS_TO_TOKENS: float = 1.4
14
+
15
+
16
+ def count_tokens(text: str, model: str = "") -> int: # noqa: ARG001
17
+ """Approximate the number of tokens in *text*.
18
+
19
+ Args:
20
+ text: Any string.
21
+ model: LLM model name (currently unused — kept for future exact counting
22
+ via tiktoken or the Anthropic token-counting API).
23
+
24
+ Returns:
25
+ Estimated integer token count.
26
+ """
27
+ word_count = len(text.split())
28
+ return int(word_count * _WORDS_TO_TOKENS)
29
+
30
+
31
+ def calculate_max_tokens(
32
+ input_word_count: int,
33
+ max_expansion: float = 0.40,
34
+ token_ratio: float = _WORDS_TO_TOKENS,
35
+ safety_buffer: float = 1.5,
36
+ ) -> int:
37
+ """Calculate the max_tokens parameter to pass to the LLM.
38
+
39
+ Formula: input_word_count × (1 + max_expansion) × token_ratio × safety_buffer
40
+
41
+ Args:
42
+ input_word_count: Number of words in the original text.
43
+ max_expansion: Maximum allowed length increase as a fraction (e.g. 0.40 = 40%).
44
+ token_ratio: Tokens-per-word ratio for the target model.
45
+ safety_buffer: Multiplier to ensure we never hard-truncate the output.
46
+
47
+ Returns:
48
+ Integer value suitable for the ``max_tokens`` parameter of any LLM API call.
49
+ """
50
+ expanded_words = input_word_count * (1.0 + max_expansion)
51
+ tokens = expanded_words * token_ratio * safety_buffer
52
+ # Clamp to a sensible minimum so short inputs still get a reasonable budget
53
+ return max(256, int(tokens))
err.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.
2
+
3
+ Traceback (most recent call last):
4
+ File "<string>", line 20, in <module>
5
+ result = analyzer.analyze(text)
6
+ File "D:\Workspace\humanization-engine\app\core\analyzer.py", line 104, in analyze
7
+ structure_instructions = self._structure.analyze(text, sentences)
8
+ File "D:\Workspace\humanization-engine\app\core\analyzers\structure.py", line 68, in analyze
9
+ instructions.extend(self._check_single_dense_paragraph(sentences))
10
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
11
+ AttributeError: 'StructuralAnalyzer' object has no attribute '_check_single_dense_paragraph'
errors.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ spacy ok
2
+ scorer ok
3
+ analyzer ok
4
+ result ok {'total_sentences': 2, 'high_risk_sentences': 0, 'medium_risk_sentences': 0, 'low_risk_sentences': 2, 'burstiness_cv': 0.1571, 'burstiness_rating': 'high_uniformity', 'ai_vocabulary_count': 0, 'transition_flags': 0, 'opening_pattern_flags': 0, 'overall_risk': 'low', 'analysis_time_ms': 384.6}
frontend/.gitkeep ADDED
File without changes
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi>=0.104.0
2
+ uvicorn>=0.24.0
3
+ httpx>=0.25.0
4
+ torch>=2.1.0
5
+ transformers>=4.36.0
6
+ accelerate>=0.25.0
7
+ spacy>=3.7.0
8
+ language-tool-python>=2.7.0
9
+ python-dotenv>=1.0.0
10
+ pydantic>=2.5.0
11
+ pydantic-settings>=2.1.0
test_ppl.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Perplexity scorer: measure main pass vs span detection cost."""
2
+ import sys, os
3
+ sys.path.insert(0, os.path.dirname(__file__))
4
+ os.environ['TRANSFORMERS_NO_ADVISORY_WARNINGS'] = '1'
5
+ import logging
6
+ logging.getLogger('transformers').setLevel(logging.ERROR)
7
+ logging.getLogger('app').setLevel(logging.ERROR)
8
+ import warnings; warnings.filterwarnings('ignore')
9
+ import time, math
10
+ import torch
11
+
12
+ print("Loading PerplexityScorer...", flush=True)
13
+ t_load = time.perf_counter()
14
+ from app.core.perplexity_scorer import PerplexityScorer
15
+ scorer = PerplexityScorer()
16
+ print(f"Loaded in {(time.perf_counter()-t_load)*1000:.0f}ms\n", flush=True)
17
+
18
+ sentences = [
19
+ "Furthermore, the implementation of sophisticated machine learning algorithms demonstrates unprecedented capabilities in facilitating proactive interventions.",
20
+ "The integration of these technologies into clinical workflows represents a significant paradigm shift.",
21
+ "The system actually works pretty well for detecting patterns that doctors might miss.",
22
+ "Consequently, nations worldwide have begun implementing comprehensive mitigation strategies.",
23
+ ]
24
+
25
+ # Measure ONLY the mean perplexity (single forward pass)
26
+ print("=== Single-pass mean perplexity only ===")
27
+ for sent in sentences:
28
+ t0 = time.perf_counter()
29
+ ppl = scorer._compute_mean_perplexity(sent)
30
+ ms = (time.perf_counter()-t0)*1000
31
+ cls = scorer._classify(ppl)
32
+ print(f" ppl={ppl:6.1f} {cls:<14} {ms:5.0f}ms {sent[:55]}")
33
+
34
+ print()
35
+
36
+ # Measure score_sentence WITH span detection (current default)
37
+ print("=== score_sentence WITH span detection (current) ===")
38
+ for sent in sentences:
39
+ t0 = time.perf_counter()
40
+ r = scorer.score_sentence(sent)
41
+ ms = (time.perf_counter()-t0)*1000
42
+ print(f" ppl={r.mean_perplexity:6.1f} {r.classification:<14} {ms:5.0f}ms spans={len(r.low_perplexity_spans)}")
43
+
44
+ print()
45
+ print("Span detection is the bottleneck. We'll disable it by default.")
test_stage1.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ test_stage1.py -- Full Stage 1 validation with spaCy + Qwen2.5-0.5B.
3
+
4
+ Runs TextAnalyzer on all 3 sample inputs from PROJECT_INSTRUCTIONS.md and
5
+ prints a detailed breakdown of every instruction the LLM would receive.
6
+
7
+ Usage (from project root):
8
+ python test_stage1.py
9
+
10
+ First run takes ~7 seconds to load Qwen2.5-0.5B into RAM (~1.1 GB).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import sys
17
+ import time
18
+ import warnings
19
+ import logging
20
+
21
+ # -- silence noisy library output ------------------------------------------
22
+ os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "1"
23
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
24
+ warnings.filterwarnings("ignore")
25
+ logging.getLogger("transformers").setLevel(logging.ERROR)
26
+ logging.getLogger("torch").setLevel(logging.ERROR)
27
+ logging.getLogger("app").setLevel(logging.WARNING)
28
+
29
+ sys.path.insert(0, os.path.dirname(__file__))
30
+
31
+ # -- sample inputs from PROJECT_INSTRUCTIONS.md ---------------------------
32
+
33
+ SAMPLES: dict[str, str] = {
34
+ "Healthcare": (
35
+ "Artificial intelligence has fundamentally transformed the landscape of modern healthcare. "
36
+ "Through the implementation of sophisticated machine learning algorithms, medical professionals "
37
+ "can now diagnose diseases with unprecedented accuracy. Furthermore, AI-powered systems have "
38
+ "demonstrated remarkable capabilities in predicting patient outcomes, enabling proactive "
39
+ "intervention strategies. The integration of these technologies into clinical workflows represents "
40
+ "a significant paradigm shift in how healthcare services are delivered and optimized."
41
+ ),
42
+ "Climate": (
43
+ "Climate change poses an existential threat to global ecosystems and human civilization. "
44
+ "The scientific consensus overwhelmingly supports the conclusion that anthropogenic greenhouse "
45
+ "gas emissions are the primary driver of observed warming trends. Consequently, nations worldwide "
46
+ "have begun implementing comprehensive mitigation strategies, including transitioning to renewable "
47
+ "energy sources and establishing carbon pricing mechanisms. However, the pace of these efforts "
48
+ "remains insufficient to meet the targets outlined in the Paris Agreement."
49
+ ),
50
+ "Education": (
51
+ "The rapid advancement of educational technology has revolutionized the way students engage with "
52
+ "learning materials. Digital platforms now offer personalized learning experiences that adapt to "
53
+ "individual student needs and learning styles. Moreover, the integration of artificial intelligence "
54
+ "into educational frameworks has enabled more efficient assessment methods and targeted feedback "
55
+ "mechanisms. These innovations collectively contribute to improved learning outcomes and greater "
56
+ "accessibility in education."
57
+ ),
58
+ }
59
+
60
+ # -- severity colour codes (ASCII-safe) -----------------------------------
61
+ SEV_LABEL = {"high": "[HIGH] ", "medium": "[MED] ", "low": "[low] ", "": "[---] "}
62
+
63
+ TYPE_ORDER = ["perplexity", "burstiness", "vocabulary", "transition",
64
+ "sentence_opening", "structural", "informality"]
65
+
66
+
67
+ def hr(char: str = "-", width: int = 72) -> str:
68
+ return char * width
69
+
70
+
71
+ def print_banner(title: str) -> None:
72
+ print()
73
+ print(hr("="))
74
+ print(f" {title}")
75
+ print(hr("="))
76
+
77
+
78
+ def format_instructions_for_llm(analysis: dict, sentences: list[str]) -> str:
79
+ """
80
+ Reproduce exactly what Stage 2 will see -- the human-readable instruction
81
+ block derived from Stage 1's AnalysisResult.
82
+ """
83
+ instructions = analysis["instructions"]
84
+ banned = analysis["banned_words"]
85
+
86
+ # Group instructions by sentence_index
87
+ by_sentence: dict[int | None, list[dict]] = {}
88
+ for instr in instructions:
89
+ idx = instr.get("sentence_index")
90
+ by_sentence.setdefault(idx, []).append(instr)
91
+
92
+ lines: list[str] = ["ANALYSIS -- Changes Required:", ""]
93
+
94
+ # Per-sentence block
95
+ for idx, sent in enumerate(sentences):
96
+ if idx not in by_sentence:
97
+ continue
98
+ lines.append(f'SENTENCE {idx + 1}: "{sent[:90]}{"..." if len(sent) > 90 else ""}"')
99
+ for instr in by_sentence[idx]:
100
+ itype = instr.get("type", "?").upper()
101
+ sev = instr.get("severity", "")
102
+ text = instr.get("instruction", "")
103
+ icon = "!!" if sev == "high" else ("! " if sev == "medium" else "* ")
104
+ lines.append(f" {icon} [{itype}] {text}")
105
+ lines.append("")
106
+
107
+ # Document-level (no sentence_index)
108
+ if None in by_sentence:
109
+ lines.append("DOCUMENT-LEVEL:")
110
+ for instr in by_sentence[None]:
111
+ itype = instr.get("type", "?").upper()
112
+ text = instr.get("instruction", "")
113
+ lines.append(f" * [{itype}] {text}")
114
+ lines.append("")
115
+
116
+ lines.append(f"BANNED WORDS (never use): {', '.join(banned)}")
117
+ return "\n".join(lines)
118
+
119
+
120
+ def main() -> None:
121
+ # -- 1. Load models ----------------------------------------------------
122
+ print(hr())
123
+ print(" STAGE 1 FULL VALIDATION (spaCy + Qwen2.5-0.5B)")
124
+ print(hr())
125
+
126
+ print("\n[1/2] Loading spaCy en_core_web_sm ... ", end="", flush=True)
127
+ import spacy
128
+ nlp = spacy.load("en_core_web_sm")
129
+ print("OK")
130
+
131
+ print("[2/2] Loading Qwen2.5-0.5B (first run ~7 s) ... ", end="", flush=True)
132
+ t0 = time.perf_counter()
133
+ from app.core.perplexity_scorer import PerplexityScorer
134
+ scorer = PerplexityScorer()
135
+ print(f"OK ({(time.perf_counter() - t0) * 1000:.0f} ms)")
136
+
137
+ # -- 2. Initialise TextAnalyzer ----------------------------------------
138
+ from app.core.analyzer import TextAnalyzer
139
+ analyzer = TextAnalyzer(nlp=nlp, perplexity_scorer=scorer)
140
+
141
+ # -- 3. Run each sample ------------------------------------------------
142
+ for sample_name, text in SAMPLES.items():
143
+ print_banner(f"SAMPLE: {sample_name}")
144
+
145
+ # split sentences for display
146
+ doc = nlp(text)
147
+ sentences = [s.text.strip() for s in doc.sents if s.text.strip()]
148
+
149
+ print(f"\nINPUT ({len(text.split())} words, {len(sentences)} sentences):")
150
+ for i, s in enumerate(sentences):
151
+ print(f" [{i}] {s}")
152
+
153
+ print()
154
+ t_start = time.perf_counter()
155
+ result = analyzer.analyze(text)
156
+ elapsed_ms = (time.perf_counter() - t_start) * 1000
157
+
158
+ summary = result["summary"]
159
+ instructions = result["instructions"]
160
+ banned = result["banned_words"]
161
+ sent_ppls = result["sentence_perplexities"]
162
+
163
+ # -- Summary block -------------------------------------------------
164
+ print(hr("-"))
165
+ print(" SUMMARY")
166
+ print(hr("-"))
167
+ print(f" Analysis time : {elapsed_ms:.1f} ms (target < 300 ms)")
168
+ print(f" Total sentences : {summary['total_sentences']}")
169
+ print(f" High-risk : {summary['high_risk_sentences']}")
170
+ print(f" Medium-risk : {summary['medium_risk_sentences']}")
171
+ print(f" Low-risk : {summary['low_risk_sentences']}")
172
+ print(f" Overall risk : {summary['overall_risk'].upper()}")
173
+ print(f" Burstiness CV : {summary['burstiness_cv']:.3f} ({summary['burstiness_rating']})")
174
+ print(f" AI vocab matches : {summary['ai_vocabulary_count']}")
175
+ print(f" Transition flags : {summary['transition_flags']}")
176
+ print(f" Opening flags : {summary['opening_pattern_flags']}")
177
+
178
+ # -- Per-sentence perplexity ---------------------------------------
179
+ print()
180
+ print(hr("-"))
181
+ print(" PERPLEXITY SCORES (Qwen2.5-0.5B)")
182
+ print(hr("-"))
183
+ for sp in sent_ppls:
184
+ ppl = sp["mean_ppl"]
185
+ risk = sp["risk"]
186
+ star = "**" if risk == "high_risk" else ("* " if risk == "medium_risk" else " ")
187
+ print(f" {star} [{sp['index']}] ppl={ppl:6.1f} {risk:<14} {sp['text'][:60]}")
188
+
189
+ # -- Instruction breakdown by type ---------------------------------
190
+ print()
191
+ print(hr("-"))
192
+ print(f" INSTRUCTIONS ({len(instructions)} total)")
193
+ print(hr("-"))
194
+
195
+ counts: dict[str, int] = {}
196
+ for instr in instructions:
197
+ counts[instr.get("type", "?")] = counts.get(instr.get("type", "?"), 0) + 1
198
+
199
+ print(" By type:")
200
+ for t in TYPE_ORDER:
201
+ n = counts.get(t, 0)
202
+ if n:
203
+ print(f" {t:<18} {n}")
204
+ for t, n in counts.items():
205
+ if t not in TYPE_ORDER:
206
+ print(f" {t:<18} {n}")
207
+
208
+ # -- Banned words --------------------------------------------------
209
+ print()
210
+ print(f" BANNED WORDS ({len(banned)}):")
211
+ row = []
212
+ for w in banned:
213
+ row.append(w)
214
+ if len(row) == 6:
215
+ print(" " + ", ".join(row))
216
+ row = []
217
+ if row:
218
+ print(" " + ", ".join(row))
219
+
220
+ # -- Full human-readable instruction block -------------------------
221
+ print()
222
+ print(hr("-"))
223
+ print(" FULL INSTRUCTION BLOCK (what the LLM sees)")
224
+ print(hr("-"))
225
+ block = format_instructions_for_llm(result, sentences)
226
+ for line in block.splitlines():
227
+ print(" " + line)
228
+
229
+ # -- Final summary -----------------------------------------------------
230
+ print()
231
+ print(hr("="))
232
+ print(" VALIDATION COMPLETE")
233
+ print(hr("="))
234
+ print()
235
+ print(" Checklist:")
236
+ print(" [ ] Analysis time < 300 ms per sample (excluding model load)")
237
+ print(" [ ] All transition words flagged (Furthermore / Consequently / Moreover / However)")
238
+ print(" [ ] Burstiness CV < 0.30 for all samples (AI uniformity confirmed)")
239
+ print(" [ ] high_risk or medium_risk sentences detected via Qwen2.5")
240
+ print(" [ ] overall_risk is 'high' or 'medium' (not 'low') for all samples")
241
+ print(" [ ] Banned words list is non-empty and accurate")
242
+ print(" [ ] Instruction block is specific and actionable")
243
+ print()
244
+
245
+
246
+ if __name__ == "__main__":
247
+ main()
tests/__init__.py ADDED
File without changes