Spaces:
Runtime error
Runtime error
Download test_stage1.py from digitalytics/humanizer-engine: direct link, hf CLI and curl.
- Browser
- Download file 10 kB
-
https://huggingface.co/spaces/digitalytics/humanizer-engine/resolve/main/test_stage1.py
- Command line
-
hf download hf://spaces/digitalytics/humanizer-engine/test_stage1.py
-
curl -L -o test_stage1.py https://huggingface.co/spaces/digitalytics/humanizer-engine/resolve/main/test_stage1.py
10 kB
| """ | |
| test_stage1.py -- Full Stage 1 validation with spaCy + Qwen2.5-0.5B. | |
| Runs TextAnalyzer on all 3 sample inputs from PROJECT_INSTRUCTIONS.md and | |
| prints a detailed breakdown of every instruction the LLM would receive. | |
| Usage (from project root): | |
| python test_stage1.py | |
| First run takes ~7 seconds to load Qwen2.5-0.5B into RAM (~1.1 GB). | |
| """ | |
| from __future__ import annotations | |
| import os | |
| import sys | |
| import time | |
| import warnings | |
| import logging | |
| # -- silence noisy library output ------------------------------------------ | |
| os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "1" | |
| os.environ["TOKENIZERS_PARALLELISM"] = "false" | |
| warnings.filterwarnings("ignore") | |
| logging.getLogger("transformers").setLevel(logging.ERROR) | |
| logging.getLogger("torch").setLevel(logging.ERROR) | |
| logging.getLogger("app").setLevel(logging.WARNING) | |
| sys.path.insert(0, os.path.dirname(__file__)) | |
| # -- sample inputs from PROJECT_INSTRUCTIONS.md --------------------------- | |
| SAMPLES: dict[str, str] = { | |
| "Healthcare": ( | |
| "Artificial intelligence has fundamentally transformed the landscape of modern healthcare. " | |
| "Through the implementation of sophisticated machine learning algorithms, medical professionals " | |
| "can now diagnose diseases with unprecedented accuracy. Furthermore, AI-powered systems have " | |
| "demonstrated remarkable capabilities in predicting patient outcomes, enabling proactive " | |
| "intervention strategies. The integration of these technologies into clinical workflows represents " | |
| "a significant paradigm shift in how healthcare services are delivered and optimized." | |
| ), | |
| "Climate": ( | |
| "Climate change poses an existential threat to global ecosystems and human civilization. " | |
| "The scientific consensus overwhelmingly supports the conclusion that anthropogenic greenhouse " | |
| "gas emissions are the primary driver of observed warming trends. Consequently, nations worldwide " | |
| "have begun implementing comprehensive mitigation strategies, including transitioning to renewable " | |
| "energy sources and establishing carbon pricing mechanisms. However, the pace of these efforts " | |
| "remains insufficient to meet the targets outlined in the Paris Agreement." | |
| ), | |
| "Education": ( | |
| "The rapid advancement of educational technology has revolutionized the way students engage with " | |
| "learning materials. Digital platforms now offer personalized learning experiences that adapt to " | |
| "individual student needs and learning styles. Moreover, the integration of artificial intelligence " | |
| "into educational frameworks has enabled more efficient assessment methods and targeted feedback " | |
| "mechanisms. These innovations collectively contribute to improved learning outcomes and greater " | |
| "accessibility in education." | |
| ), | |
| } | |
| # -- severity colour codes (ASCII-safe) ----------------------------------- | |
| SEV_LABEL = {"high": "[HIGH] ", "medium": "[MED] ", "low": "[low] ", "": "[---] "} | |
| TYPE_ORDER = ["perplexity", "burstiness", "vocabulary", "transition", | |
| "sentence_opening", "structural", "informality"] | |
| def hr(char: str = "-", width: int = 72) -> str: | |
| return char * width | |
| def print_banner(title: str) -> None: | |
| print() | |
| print(hr("=")) | |
| print(f" {title}") | |
| print(hr("=")) | |
| def format_instructions_for_llm(analysis: dict, sentences: list[str]) -> str: | |
| """ | |
| Reproduce exactly what Stage 2 will see -- the human-readable instruction | |
| block derived from Stage 1's AnalysisResult. | |
| """ | |
| instructions = analysis["instructions"] | |
| banned = analysis["banned_words"] | |
| # Group instructions by sentence_index | |
| by_sentence: dict[int | None, list[dict]] = {} | |
| for instr in instructions: | |
| idx = instr.get("sentence_index") | |
| by_sentence.setdefault(idx, []).append(instr) | |
| lines: list[str] = ["ANALYSIS -- Changes Required:", ""] | |
| # Per-sentence block | |
| for idx, sent in enumerate(sentences): | |
| if idx not in by_sentence: | |
| continue | |
| lines.append(f'SENTENCE {idx + 1}: "{sent[:90]}{"..." if len(sent) > 90 else ""}"') | |
| for instr in by_sentence[idx]: | |
| itype = instr.get("type", "?").upper() | |
| sev = instr.get("severity", "") | |
| text = instr.get("instruction", "") | |
| icon = "!!" if sev == "high" else ("! " if sev == "medium" else "* ") | |
| lines.append(f" {icon} [{itype}] {text}") | |
| lines.append("") | |
| # Document-level (no sentence_index) | |
| if None in by_sentence: | |
| lines.append("DOCUMENT-LEVEL:") | |
| for instr in by_sentence[None]: | |
| itype = instr.get("type", "?").upper() | |
| text = instr.get("instruction", "") | |
| lines.append(f" * [{itype}] {text}") | |
| lines.append("") | |
| lines.append(f"BANNED WORDS (never use): {', '.join(banned)}") | |
| return "\n".join(lines) | |
| def main() -> None: | |
| # -- 1. Load models ---------------------------------------------------- | |
| print(hr()) | |
| print(" STAGE 1 FULL VALIDATION (spaCy + Qwen2.5-0.5B)") | |
| print(hr()) | |
| print("\n[1/2] Loading spaCy en_core_web_sm ... ", end="", flush=True) | |
| import spacy | |
| nlp = spacy.load("en_core_web_sm") | |
| print("OK") | |
| print("[2/2] Loading Qwen2.5-0.5B (first run ~7 s) ... ", end="", flush=True) | |
| t0 = time.perf_counter() | |
| from app.core.perplexity_scorer import PerplexityScorer | |
| scorer = PerplexityScorer() | |
| print(f"OK ({(time.perf_counter() - t0) * 1000:.0f} ms)") | |
| # -- 2. Initialise TextAnalyzer ---------------------------------------- | |
| from app.core.analyzer import TextAnalyzer | |
| analyzer = TextAnalyzer(nlp=nlp, perplexity_scorer=scorer) | |
| # -- 3. Run each sample ------------------------------------------------ | |
| for sample_name, text in SAMPLES.items(): | |
| print_banner(f"SAMPLE: {sample_name}") | |
| # split sentences for display | |
| doc = nlp(text) | |
| sentences = [s.text.strip() for s in doc.sents if s.text.strip()] | |
| print(f"\nINPUT ({len(text.split())} words, {len(sentences)} sentences):") | |
| for i, s in enumerate(sentences): | |
| print(f" [{i}] {s}") | |
| print() | |
| t_start = time.perf_counter() | |
| result = analyzer.analyze(text) | |
| elapsed_ms = (time.perf_counter() - t_start) * 1000 | |
| summary = result["summary"] | |
| instructions = result["instructions"] | |
| banned = result["banned_words"] | |
| sent_ppls = result["sentence_perplexities"] | |
| # -- Summary block ------------------------------------------------- | |
| print(hr("-")) | |
| print(" SUMMARY") | |
| print(hr("-")) | |
| print(f" Analysis time : {elapsed_ms:.1f} ms (target < 300 ms)") | |
| print(f" Total sentences : {summary['total_sentences']}") | |
| print(f" High-risk : {summary['high_risk_sentences']}") | |
| print(f" Medium-risk : {summary['medium_risk_sentences']}") | |
| print(f" Low-risk : {summary['low_risk_sentences']}") | |
| print(f" Overall risk : {summary['overall_risk'].upper()}") | |
| print(f" Burstiness CV : {summary['burstiness_cv']:.3f} ({summary['burstiness_rating']})") | |
| print(f" AI vocab matches : {summary['ai_vocabulary_count']}") | |
| print(f" Transition flags : {summary['transition_flags']}") | |
| print(f" Opening flags : {summary['opening_pattern_flags']}") | |
| # -- Per-sentence perplexity --------------------------------------- | |
| print() | |
| print(hr("-")) | |
| print(" PERPLEXITY SCORES (Qwen2.5-0.5B)") | |
| print(hr("-")) | |
| for sp in sent_ppls: | |
| ppl = sp["mean_ppl"] | |
| risk = sp["risk"] | |
| star = "**" if risk == "high_risk" else ("* " if risk == "medium_risk" else " ") | |
| print(f" {star} [{sp['index']}] ppl={ppl:6.1f} {risk:<14} {sp['text'][:60]}") | |
| # -- Instruction breakdown by type --------------------------------- | |
| print() | |
| print(hr("-")) | |
| print(f" INSTRUCTIONS ({len(instructions)} total)") | |
| print(hr("-")) | |
| counts: dict[str, int] = {} | |
| for instr in instructions: | |
| counts[instr.get("type", "?")] = counts.get(instr.get("type", "?"), 0) + 1 | |
| print(" By type:") | |
| for t in TYPE_ORDER: | |
| n = counts.get(t, 0) | |
| if n: | |
| print(f" {t:<18} {n}") | |
| for t, n in counts.items(): | |
| if t not in TYPE_ORDER: | |
| print(f" {t:<18} {n}") | |
| # -- Banned words -------------------------------------------------- | |
| print() | |
| print(f" BANNED WORDS ({len(banned)}):") | |
| row = [] | |
| for w in banned: | |
| row.append(w) | |
| if len(row) == 6: | |
| print(" " + ", ".join(row)) | |
| row = [] | |
| if row: | |
| print(" " + ", ".join(row)) | |
| # -- Full human-readable instruction block ------------------------- | |
| print() | |
| print(hr("-")) | |
| print(" FULL INSTRUCTION BLOCK (what the LLM sees)") | |
| print(hr("-")) | |
| block = format_instructions_for_llm(result, sentences) | |
| for line in block.splitlines(): | |
| print(" " + line) | |
| # -- Final summary ----------------------------------------------------- | |
| print() | |
| print(hr("=")) | |
| print(" VALIDATION COMPLETE") | |
| print(hr("=")) | |
| print() | |
| print(" Checklist:") | |
| print(" [ ] Analysis time < 300 ms per sample (excluding model load)") | |
| print(" [ ] All transition words flagged (Furthermore / Consequently / Moreover / However)") | |
| print(" [ ] Burstiness CV < 0.30 for all samples (AI uniformity confirmed)") | |
| print(" [ ] high_risk or medium_risk sentences detected via Qwen2.5") | |
| print(" [ ] overall_risk is 'high' or 'medium' (not 'low') for all samples") | |
| print(" [ ] Banned words list is non-empty and accurate") | |
| print(" [ ] Instruction block is specific and actionable") | |
| print() | |
| if __name__ == "__main__": | |
| main() | |