### PHP Quick Start Examples Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Illustrates various ways to use the TextHumanize PHP library, including basic humanization, chunked processing, AI detection, batch processing, and tone adjustment. ```php processed; // Chunk processing for large texts $result = TextHumanize::humanizeChunked($longText, chunkSize: 5000); // AI detection $ai = TextHumanize::detectAI("Suspicious text", lang: 'en'); echo $ai['verdict']; // "ai_generated" // Batch processing $results = TextHumanize::humanizeBatch([$text1, $text2, $text3]); // Tone analysis & adjustment $tone = TextHumanize::analyzeTone("Formal text", lang: 'en'); $casual = TextHumanize::adjustTone("Formal text", target: 'casual'); ``` -------------------------------- ### Clone Repository and Setup Environment Source: https://github.com/ksanyok/texthumanize/blob/main/CONTRIBUTING.md Steps to clone the TextHumanize repository, set up a Python virtual environment, and install the package in editable mode with development dependencies. ```bash # Clone the repository git clone https://github.com/ksanyok/TextHumanize.git cd TextHumanize # Create a virtual environment python3 -m venv .venv source .venv/bin/activate # Install in editable mode with dev dependencies pip install -e ".[dev]" ``` -------------------------------- ### Install and Run Tests for PHP Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Commands to install PHP dependencies using Composer and run the unit tests with PHPUnit. ```bash cd php/ composer install php vendor/bin/phpunit # 223 tests, 825 assertions ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Set up pre-commit hooks for your project with a one-time installation command. This ensures code quality checks are run automatically before each commit. ```bash pre-commit install # one-time setup ``` -------------------------------- ### Install and Run Tests for JS/TS Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Commands to install dependencies and run tests for the JavaScript/TypeScript port of the library. Includes type checking. ```bash cd js/ npm install npx vitest run # 28 tests npx tsc --noEmit # type check ``` -------------------------------- ### Flask Integration Example Source: https://github.com/ksanyok/texthumanize/blob/main/CHANGELOG.md Example of integrating TextHumanize with Flask, demonstrating blueprint usage and caching. ```python examples/flask_integration.py ``` -------------------------------- ### Install TextHumanize with Optional Features Source: https://github.com/ksanyok/texthumanize/blob/main/ROADMAP.md Install the core package or specific features like language detection, paraphrasing, or API clients using pip. Neural models are downloaded on first use. ```bash pip install texthumanize # 5 MB — core, rule-based, zero deps pip install texthumanize[detect] # +50 MB — ONNX transformer detector pip install texthumanize[paraphrase] # +100 MB — T5 neural paraphraser pip install texthumanize[full] # all features pip install texthumanize[api] # OpenAI/Anthropic API clients pip install texthumanize[lang-cjk] # CJK language support (zh/ja/ko) pip install texthumanize[lang-european] # European languages (fr/es/it/pl/pt) ``` -------------------------------- ### Structured Logging Setup Source: https://github.com/ksanyok/texthumanize/blob/main/CHANGELOG.md Adds standard Python logging to modules, using a NullHandler by default to avoid log output unless configured by the user. ```python import logging logger = logging.getLogger(__name__) ``` -------------------------------- ### SEO Workflow Example for TextHumanize Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md This example demonstrates a complete workflow for using TextHumanize in SEO mode. It includes analyzing original text, humanizing with SEO protection, verifying keyword preservation, and checking AI detection improvement. ```python from texthumanize import humanize, analyze, detect_ai # 1. Analyze original report = analyze(seo_text, lang="en") print(f"Artificiality before: {report.artificiality_score:.0f}/100") # 2. Humanize with SEO protection result = humanize(seo_text, profile="seo", intensity=35, constraints={"keep_keywords": ["cloud", "scalability"]}) # 3. Verify keywords preserved for kw in ["cloud", "scalability"]: assert kw in result.text, f"Keyword '{kw}' was modified!" # 4. Check AI detection improvement ai_before = detect_ai(seo_text, lang="en") ai_after = detect_ai(result.text, lang="en") print(f"AI score: {ai_before['score']:.0%} → {ai_after['score']:.0%}") ``` -------------------------------- ### FastAPI Integration Example Source: https://github.com/ksanyok/texthumanize/blob/main/CHANGELOG.md Example of integrating TextHumanize with FastAPI, supporting asynchronous operations and Pydantic models. ```python examples/fastapi_integration.py ``` -------------------------------- ### Django Integration Example Source: https://github.com/ksanyok/texthumanize/blob/main/CHANGELOG.md Example of integrating TextHumanize with Django, showcasing views, middleware, and template filters. ```python examples/django_integration.py ``` -------------------------------- ### CLI AI Detection Example Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Example of using the TextHumanize command-line interface to detect AI in a file, with verbose output and JSON formatting. ```bash texthumanize detect file.txt --verbose --json ``` -------------------------------- ### Display Humanize Report Output Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Example output from the `explain()` function, showing a detailed breakdown of TextHumanize report metrics and changes. ```text === Отчёт TextHumanize === Язык: en | Профиль: web | Интенсивность: 60 Доля изменений: 25.3% --- Метрики --- Искусственность: 45.00 → 22.00 ↓ Канцеляризмы: 0.12 → 0.00 ↓ --- Изменения (3) --- [debureaucratization] "utilize" → "use" [connector] "Furthermore" → "Also" [structure] sentence split applied ``` -------------------------------- ### Start TextHumanize REST API Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Launch the TextHumanize REST API on a specified port. This allows you to interact with the library programmatically over HTTP. ```bash python -m texthumanize.api --port 8080 ``` -------------------------------- ### Custom Pipeline Plugin for Text Humanization Source: https://github.com/ksanyok/texthumanize/blob/main/docs/COOKBOOK.md Allows extending the text humanization pipeline by registering custom plugins. This example adds an emoji to the beginning of the text. ```python from texthumanize import Pipeline, HumanizeOptions def add_emoji(text: str, lang: str) -> str: """Add a relevant emoji to the first sentence.""" return "✨ " + text pipeline = Pipeline(HumanizeOptions(lang="en")) pipeline.register_plugin("typography", add_emoji, before=False) result = pipeline.run("Boring text here.", lang="en") print(result.text) # "✨ Boring text here." ``` -------------------------------- ### Get TextHumanize Version Source: https://github.com/ksanyok/texthumanize/blob/main/CONTRIBUTING.md Retrieve the installed version of the texthumanize package using a Python command. ```bash python -c "import texthumanize; print(texthumanize.__version__)" ``` -------------------------------- ### Humanize Text with SEO Profile Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Utilize the 'seo' profile in the `humanize` function for content that needs to maintain search engine ranking. This example shows how to set intensity and constraints, including keeping specific keywords. ```python result = humanize( text, profile="seo", intensity=40, # lower intensity for safety constraints={ "max_change_ratio": 0.3, "keep_keywords": ["cloud computing", "API", "microservices"], }, ) ``` -------------------------------- ### Explain AI Detection Signals Source: https://github.com/ksanyok/texthumanize/blob/main/docs-src/responsible-use.md Use `detect_ai_explain()` to get reasons behind AI detection scores, providing guidance for revisions. Specify the text and language for analysis. ```python detect_ai_explain(text, lang) ``` -------------------------------- ### Calculate Readability Metrics Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Quickly get Flesch-Kincaid and Coleman-Liau scores using analyze(), or compute all available readability indices with full_readability(). ```python from texthumanize import analyze, full_readability # Quick readability from analyze() report = analyze("Your text here.", lang="en") print(f"Flesch-Kincaid: {report.flesch_kincaid_grade:.1f}") print(f"Coleman-Liau: {report.coleman_liau_index:.1f}") # Full readability with all indices r = full_readability("Your text with multiple sentences. Each one counts.", lang="en") for metric, value in r.items(): print(f" {metric}: {value}") ``` -------------------------------- ### Universal Language Processing with Humanize Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md The `humanize` function can process text in any language using statistical methods when specific dictionaries are not available. This example demonstrates processing text in Japanese, Kazakh, Persian, and Vietnamese. ```python # Works with any language — no dictionaries needed result = humanize("日本語のテキスト", lang="ja") result = humanize("Текст на казахском", lang="kk") result = humanize("متن فارسی", lang="fa") result = humanize("Đây là văn bản tiếng Việt", lang="vi") ``` -------------------------------- ### Automatic Language Detection with Humanize Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md The `humanize` function can automatically detect the language of the input text. This example shows how the detected language is returned for Russian and English texts. ```python # Language is detected automatically result = humanize("Этот текст автоматически определяется как русский.") print(result.lang) # "ru" result = humanize("This text is automatically detected as English.") print(result.lang) # "en" ``` -------------------------------- ### Detect AI in Human Text Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Use the `detect_ai` function to assess the likelihood of a text being AI-generated. This example shows how to check a human-written text and print the AI score and verdict. ```python human_text = """ I tried that new coffee shop downtown yesterday. Their espresso was actually decent - not as burnt as the place on 5th. The barista was nice too, recommended this Ethiopian blend I'd never heard of. Might go back this weekend. """ result = detect_ai(human_text, lang="en") print(f"Score: {result['score']:.0%}") # → ~20-27% — Human confirmed print(f"Verdict: {result['verdict']}") # → "human_written" ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/ksanyok/texthumanize/blob/main/CONTRIBUTING.md Execute the test suite and generate a coverage report, highlighting missing lines. ```bash # With coverage pytest tests/ --cov=texthumanize --cov-report=term-missing ``` -------------------------------- ### Contributing Guidelines Source: https://github.com/ksanyok/texthumanize/blob/main/CHANGELOG.md Markdown file providing guidelines for developers on setting up the project, running tests, linting, type checking, and submitting pull requests. ```markdown CONTRIBUTING.md ``` -------------------------------- ### Run Humanization Quality Benchmark Source: https://github.com/ksanyok/texthumanize/blob/main/docs-src/benchmark-methodology.md Initialize and run the BenchmarkSuite for humanization quality assessment. Requires original text and humanized output. ```python from texthumanize import BenchmarkSuite suite = BenchmarkSuite(lang="en") report = suite.run_all([ {"original": original_text, "humanized": result.text}, ]) print(report.overall_score) ``` -------------------------------- ### Benchmark CLI Command Source: https://github.com/ksanyok/texthumanize/blob/main/CHANGELOG.md Command-line interface for running benchmarks. Supports language selection, JSON output, and verbose logging. ```python texthumanize benchmark -l en [--json] [--verbose] ``` -------------------------------- ### CLI Basic Usage Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Process text files from the command line, with options for input/output files, language, profile, and intensity. ```bash # Process a file (output to stdout) texthumanize input.txt # Process with options texthumanize input.txt -l en -p web -i 70 # Save to file texthumanize input.txt -o output.txt # Process from stdin echo "Text to process" | texthumanize - -l en cat article.txt | texthumanize - ``` -------------------------------- ### Single Text AI Detection Source: https://github.com/ksanyok/texthumanize/blob/main/README.md Use this function to get an AI detection score and verdict for a single piece of text. Specify the language for accurate analysis. ```python # Single text result = detect_ai("Text to check.", lang="en") print(f"{result['score']:.0%} — {result['verdict']}") ``` -------------------------------- ### Documentation Index Source: https://github.com/ksanyok/texthumanize/blob/main/CHANGELOG.md Markdown file serving as an index for the project documentation, located in the docs/ directory. ```markdown docs/README.md ``` -------------------------------- ### Apply Style Presets for Humanization Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Adapt the text humanization process to match specific writing styles like 'student', 'scientist', or 'journalist' by adjusting sentence length, vocabulary, and punctuation. Presets can be used directly or by providing a custom style fingerprint extracted from a writing sample. ```python from texthumanize import humanize, STYLE_PRESETS # Just pass a string — that's it result = humanize(text, target_style="student") # Or use the fingerprint object directly result = humanize(text, target_style=STYLE_PRESETS["scientist"]) # Custom fingerprint from your own writing sample from texthumanize import StylisticAnalyzer analyzer = StylisticAnalyzer(lang="en") my_style = analyzer.extract(my_writing_sample) result = humanize(text, target_style=my_style) ``` -------------------------------- ### explain(result) Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Generates a human-readable report detailing the changes made by the `humanize()` function. This is useful for understanding the transformations applied to the text. ```APIDOC ## explain(result) ### Description Generate a human-readable report of all changes made by `humanize()`. ### Method `explain` ### Parameters #### Path Parameters - **result** (HumanizeResult) - Required - The result object from a `humanize()` call. ### Returns `str` - A human-readable report of the changes. ``` -------------------------------- ### Run TextHumanize CLI with Quality Gate Source: https://github.com/ksanyok/texthumanize/blob/main/docs-src/responsible-use.md Use the `texthumanize` command-line tool with the `--fail-under-quality` option to set a minimum quality threshold for automated checks. ```bash texthumanize --fail-under-quality ``` -------------------------------- ### Humanize AI-Generated Text (OSS Model) Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Humanizes AI-generated text using an open-source model, offering a free alternative to paid APIs. This option may be rate-limited. ```python from texthumanize import humanize_ai # With OSS model (free, rate-limited): result = humanize_ai("Text to humanize.", lang="en", enable_oss=True) ``` -------------------------------- ### Manually Run Pre-commit Hooks Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Manually trigger all configured pre-commit hooks across your entire project. This is useful for checking all files at once. ```bash pre-commit run --all-files # manual run ``` -------------------------------- ### Run Full Test Suite Source: https://github.com/ksanyok/texthumanize/blob/main/CONTRIBUTING.md Execute the complete test suite for the TextHumanize project using pytest. ```bash # Full test suite pytest tests/ -q ``` -------------------------------- ### Dockerfile for API Server Source: https://github.com/ksanyok/texthumanize/blob/main/CHANGELOG.md Dockerfile to build a Python 3.12 slim image for the API server, configured for non-root user and exposing port 8080. ```dockerfile Dockerfile ``` -------------------------------- ### Lint and Format Code with Ruff Source: https://github.com/ksanyok/texthumanize/blob/main/CONTRIBUTING.md Check for linting errors and formatting issues in the project's code using the ruff tool. ```bash ruff check texthumanize/ tests/ ruff format --check texthumanize/ tests/ ``` -------------------------------- ### POS Tagging with POSTagger Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Utilize POSTagger for rule-based part-of-speech tagging in English, Russian, and Ukrainian. Initialize with the desired language. ```python from texthumanize import POSTagger tagger = POSTagger(lang="en") for word, tag in tagger.tag("The quick brown fox jumps"): print(f"{word:12s} → {tag}") ``` -------------------------------- ### Humanize Text with Different Profiles Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Apply humanization to text using predefined profiles like 'chat', 'web', 'seo', 'docs', 'formal', 'academic', 'marketing', 'social', and 'email'. Intensity and constraints can also be specified. ```python # Conversational style for social media result = humanize(text, profile="chat", intensity=80) # SEO-safe mode (preserves keywords, minimal changes) result = humanize(text, profile="seo", intensity=40, constraints={"keep_keywords": ["API", "cloud"]}) # Academic writing result = humanize(text, profile="academic", intensity=25) # Marketing copy — energetic and engaging result = humanize(text, profile="marketing", intensity=70) ``` -------------------------------- ### Quality Benchmarking with BenchmarkSuite Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Measure the quality of humanized text using BenchmarkSuite, which offers a 6-dimension automated benchmarking. A quick benchmark function is also available for single-pair comparisons. ```python from texthumanize import BenchmarkSuite, quick_benchmark # Quick single-pair benchmark: report = quick_benchmark("Original AI text.", "Humanized version.") print(report.summary()) # Full suite: suite = BenchmarkSuite(lang="en") report = suite.run_all([ {"original": "AI text 1.", "humanized": "Human text 1."}, {"original": "AI text 2.", "humanized": "Human text 2."}, ]) print(f"Overall score: {report.overall_score:.1f}/100") ``` -------------------------------- ### Benchmark Tests Source: https://github.com/ksanyok/texthumanize/blob/main/CHANGELOG.md Unit tests for the benchmark functionality, covering performance, quality, and multi-language aspects. ```python tests/test_benchmark.py ``` -------------------------------- ### Train Custom Dictionary from Corpus Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Analyze a collection of texts to identify overused AI phrases and generate a custom dictionary for the `humanize` function. Requires specifying the language and a minimum frequency for phrases to be considered overused. ```python from texthumanize import train_from_corpus, export_custom_dict # Analyze your text corpus texts = [ "Furthermore, it is important to note that...", "Moreover, the results clearly demonstrate...", # ... more texts ] result = train_from_corpus(texts, lang="en", min_frequency=2) print(f"Overused phrases: {result.overused_phrases}") print(f"AI patterns found: {len(result.repeated_patterns)}") print(f"Type-token ratio: {result.vocabulary_stats['type_token_ratio']:.2f}") # Export as custom dictionary for humanize() custom_dict = export_custom_dict(result) from texthumanize import humanize r = humanize("Your text...", custom_dict=custom_dict) ``` -------------------------------- ### PEP 562 Lazy Initialization Source: https://github.com/ksanyok/texthumanize/blob/main/CHANGELOG.md Implements PEP 562 for lazy loading of public names in __init__.py using __getattr__ and globals() caching to reduce import time and memory usage. ```python __getattr__() __dir__() ``` -------------------------------- ### TypeScript/JavaScript Core Usage Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Demonstrates basic usage of the humanize and analyze functions from the texthumanize library in JavaScript/TypeScript. Includes logging the processed text, change ratio, and AI score. ```typescript import { humanize, analyze } from 'texthumanize'; const result = humanize('Text to process', { lang: 'en', intensity: 60 }); console.log(result.text); console.log(`Changed: ${(result.changeRatio * 100).toFixed(0)}%`); const report = analyze('Text to check'); console.log(`AI score: ${report.artificialityScore}%`); ``` -------------------------------- ### Auto-Tuning Pipeline for Text Humanization Source: https://github.com/ksanyok/texthumanize/blob/main/docs/COOKBOOK.md Automatically tunes humanization intensity based on past results stored in a history file. It suggests intensity levels and records new results for future tuning. ```python from texthumanize import humanize, AutoTuner tuner = AutoTuner(history_path="tune_history.json") # Process multiple texts, recording each result for text in my_texts: intensity = tuner.suggest_intensity(text, lang="en") result = humanize(text, lang="en", intensity=intensity) tuner.record(result) # Check accumulated stats stats = tuner.summary() print(f"Processed: {stats['total_records']} texts") print(f"Suggested params: {tuner.suggest_params(lang='en').to_dict()}") ``` -------------------------------- ### Build and Compare Stylistic Fingerprints Source: https://github.com/ksanyok/texthumanize/blob/main/README.md Extract stylometric profiles from author writing samples and compare new text to these profiles for authorship attribution. Includes anonymizing text style. ```python from texthumanize import build_author_profile, compare_fingerprint, anonymize_style # Build a profile from samples profile = build_author_profile("Author's writing sample...", lang="en") print(f"Avg sentence: {profile.avg_sentence_length:.1f} words") print(f"Vocabulary richness: {profile.vocabulary_richness:.2f}") # Compare new text to a known author similarity = compare_fingerprint("New text to attribute", profile) print(f"Match: {similarity:.0%}") # Anonymize style — normalize distinctive patterns anon = anonymize_style("Text with distinctive style markers", lang="en") ``` -------------------------------- ### Explain Humanize Changes Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Generate a human-readable report detailing the changes made by the `humanize()` function. This helps in understanding the transformations applied to the text. ```python from texthumanize import humanize, explain result = humanize("Furthermore, it is important to utilize this approach.", lang="en") report = explain(result) print(report) ``` -------------------------------- ### Check Code Quality with Ruff Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Use ruff to check for linting errors in your project. This command verifies all code without making changes. ```bash # Check all code (0 errors) ruff check texthumanize/ ``` -------------------------------- ### Humanize AI-Generated Text (OpenAI) Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Humanizes AI-generated text using the OpenAI API for the best quality results. Requires an OpenAI API key and specifies the model to use. ```python from texthumanize import humanize_ai # With OpenAI API (best quality): result = humanize_ai( "Text to humanize.", lang="en", openai_api_key="sk-...", openai_model="gpt-4o-mini", ) ``` -------------------------------- ### Ensure Reproducibility with Seed Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Use the 'seed' parameter to guarantee identical results for the same input text across multiple runs. ```python # Same seed = same result every time r1 = humanize("Text here.", seed=42) r2 = humanize("Text here.", seed=42) assert r1.text == r2.text # guaranteed ``` -------------------------------- ### Run Detector Benchmark Source: https://github.com/ksanyok/texthumanize/blob/main/docs-src/benchmark-methodology.md Execute the TextHumanize detector benchmark for specified languages and output results in JSON format. ```bash texthumanize detector-benchmark --langs en,ru,uk --json ``` -------------------------------- ### Create a Feature Branch Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Create a new git branch for developing a specific feature. Follow this convention for contributions. ```bash git checkout -b feature/my-feature ``` -------------------------------- ### Auto-Tuner for Text Optimization Source: https://github.com/ksanyok/texthumanize/blob/main/README.md Automatically optimize text intensity and profile based on feedback. Suggests results and accepts feedback scores to improve future suggestions. ```python from texthumanize import AutoTuner tuner = AutoTuner() # Process and get feedback result = tuner.suggest(text, lang="en") # Provide feedback — was the result good? tuner.feedback(result, score=0.8) # 0.0 = bad, 1.0 = perfect ``` -------------------------------- ### Perform Type Checking Source: https://github.com/ksanyok/texthumanize/blob/main/CONTRIBUTING.md Run static type checking on the project code using mypy, ignoring missing imports. ```bash mypy texthumanize/ --ignore-missing-imports ``` -------------------------------- ### Run Specific Test File Source: https://github.com/ksanyok/texthumanize/blob/main/CONTRIBUTING.md Execute tests for a single file within the TextHumanize test suite. ```bash # Single file pytest tests/test_core.py -q ``` -------------------------------- ### Humanize AI-Generated Text (Default) Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Applies AI-powered humanization to text using built-in rules, requiring no external dependencies or API keys. This is the default and simplest method. ```python from texthumanize import humanize_ai # Default: uses built-in rules (zero dependencies) result = humanize_ai("AI-generated text here.", lang="en") print(result.text) ``` -------------------------------- ### Register Custom Plugin Class Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Register a plugin class with custom processing logic that runs before or after built-in stages. ```python # Plugin class with full context class BrandEnforcer: def __init__(self, brand: str, canonical: str): self.brand = brand self.canonical = canonical def process(self, text: str, lang: str, profile: str, intensity: int) -> str: import re return re.sub(re.escape(self.brand), self.canonical, text, flags=re.IGNORECASE) Pipeline.register_plugin( BrandEnforcer("texthumanize", "TextHumanize"), after="typography", ) # Process text — plugins run automatically result = humanize("texthumanize is great.") print(result.text) # "TextHumanize is great. ..." # Clean up when done Pipeline.clear_plugins() ``` -------------------------------- ### Benchmark Detector Performance Source: https://github.com/ksanyok/texthumanize/blob/main/README.md Evaluate the detector's performance using a benchmark corpus. This includes loading evaluation data and analyzing detection scores across different languages and labels. ```python # Offline detector benchmark: human vs raw/lightly/heavily edited AI from texthumanize import detector_benchmark, load_eval_corpus corpus = load_eval_corpus(include_metadata=True) print(corpus["license"]["id"]) report = detector_benchmark(languages=["en", "ru", "uk"]) print(report["per_language"]["en"]["avg_score_by_label"]) ``` -------------------------------- ### Output Diversification with FingerprintRandomizer Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Prevent detectable patterns in humanized text using FingerprintRandomizer. Initialize with a seed and jitter level for controlled diversity. ```python from texthumanize import FingerprintRandomizer r = FingerprintRandomizer(seed=42, jitter_level=0.3) text1 = r.diversify_output("Some humanized text.") text2 = r.diversify_output("Some humanized text.") # different each time ``` -------------------------------- ### Stylistic Fingerprinting for Text Humanization Source: https://github.com/ksanyok/texthumanize/blob/main/docs/COOKBOOK.md Extracts a stylistic fingerprint from a sample of writing and uses it as a target style for humanizing AI-generated text. This allows humanizing text to match a specific author's style. ```python from texthumanize import StylisticAnalyzer, StylisticFingerprint # Extract style from a sample analyzer = StylisticAnalyzer(lang="en") my_style = analyzer.extract(my_writing_sample) # Use as target result = humanize(ai_text, target_style=my_style) ``` -------------------------------- ### Async API Functions Source: https://github.com/ksanyok/texthumanize/blob/main/CHANGELOG.md Provides asynchronous functions for text humanization and AI detection. Uses asyncio.run_in_executor for non-blocking operations. ```python texthumanize/async_api.py ``` -------------------------------- ### SSE Streaming Endpoint Source: https://github.com/ksanyok/texthumanize/blob/main/CHANGELOG.md REST API endpoint for streaming humanized text chunks using Server-Sent Events. ```python POST /sse/humanize ``` -------------------------------- ### Input Size Limit Enforcement Source: https://github.com/ksanyok/texthumanize/blob/main/CHANGELOG.md Enforces input size limits for humanize and detect_ai functions, raising InputTooLargeError for texts exceeding 1MB. API server rejects requests over 5MB. ```python humanize() detect_ai() ``` -------------------------------- ### Analyze and Adjust Text Tone Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Determine the primary tone and formality level of a text. Adjust the tone of a text to a target level like 'casual'. ```python from texthumanize import analyze_tone, adjust_tone # Analyze tone = analyze_tone("Pursuant to our agreement, please facilitate the transfer.", lang="en") print(tone['primary_tone']) # "formal" print(tone['formality']) # ~0.85 # Adjust down casual = adjust_tone("Pursuant to our agreement, please facilitate the transfer.", target="casual", lang="en") print(casual) # → "Based on our agreement, go ahead and start the transfer." ``` -------------------------------- ### Set Text Processing Constraints Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Define constraints such as maximum change ratio, minimum sentence length, and keywords to keep. ```python constraints = { "max_change_ratio": 0.4, # max 40% of text changed "min_sentence_length": 3, # minimum words per sentence "keep_keywords": ["SEO", "API"], # keywords preserved exactly } ``` -------------------------------- ### Generate Audit Report Source: https://github.com/ksanyok/texthumanize/blob/main/docs-src/responsible-use.md Use `audit_report()` to generate a comprehensive report on text characteristics. Specify the text and language for analysis. ```python audit_report(text, lang) ``` -------------------------------- ### Profile Hot Paths for Latency and Memory Source: https://github.com/ksanyok/texthumanize/blob/main/docs-src/benchmark-methodology.md Profile the hot paths of TextHumanize for different input sizes, outputting results in JSON format. This is used for generating p50/p95 latency and tracemalloc peak-memory snapshots. ```bash python scripts/profile_hot_paths.py --sizes 1000,10000,100000 --json ``` -------------------------------- ### WordPress Plugin Source: https://github.com/ksanyok/texthumanize/blob/main/CHANGELOG.md A full WordPress plugin for TextHumanize, including a meta box for AI checks and humanization, a settings page, and AJAX handlers. ```php wordpress/texthumanize-wp.php ``` -------------------------------- ### Analyze and Adjust Text Tone Source: https://github.com/ksanyok/texthumanize/blob/main/README.md Analyze the formality of a given text and adjust its tone to a target level. Requires specifying the language. ```python from texthumanize import analyze_tone, adjust_tone tone = analyze_tone("Please submit the documentation.", lang="en") print(f"Formality: {tone['formality']}") # "professional" casual = adjust_tone("It is imperative to proceed immediately.", target="casual", lang="en") print(casual) # "We should probably get going on this." ``` -------------------------------- ### Generate Spintax for Text Spinning Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Create spintax formatted output for text variations using dictionary-based synonym replacement. Resolve spintax to a single variant. ```python from texthumanize.spinner import ContentSpinner spinner = ContentSpinner(lang="en", seed=42) # Generate spintax spintax = spinner.generate_spintax("The system provides important data.") print(spintax) # → "The {system|platform} {provides|offers} {important|crucial} {data|information}." # Resolve spintax to one variant resolved = spinner.resolve_spintax(spintax) print(resolved) ``` -------------------------------- ### Perform Type Checking with Mypy Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Run Mypy to perform static type checking on your Python code. Ensure your project adheres to PEP 561 standards. ```bash mypy texthumanize/ ``` -------------------------------- ### Generate Multiple Humanization Variants Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Create several different humanized versions of a given text and receive them sorted by quality score. This allows for selecting the best output from multiple options. Specify the number of variants and an optional seed for reproducibility. ```python from texthumanize import humanize_variants variants = humanize_variants( "AI-generated text to humanize.", lang="en", variants=5, # Generate 5 different versions seed=42, # Reproducible base seed ) # Results sorted by quality (best first) for v in variants: print(f"Variant {v['variant_id']}: score={v['ai_score']:.2f}, " f"changes={v['change_ratio']:.0%}") print(f" {v['text'][:80]}...") ``` -------------------------------- ### Context-Aware Synonym Selection Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Choose the most appropriate synonym for a word based on its context, topic detection, and collocation scoring. This feature performs word-sense disambiguation without requiring machine learning models. ```python from texthumanize.context import ContextualSynonyms ctx = ContextualSynonyms(lang="en", seed=42) ctx.detect_topic("The server handles API requests efficiently.") # Choose best synonym for "important" in tech context best = ctx.choose_synonym("important", ["significant", "crucial", "key", "vital"], "This is an important update to the system.") print(best) # "key" or "crucial" (tech-appropriate) ``` -------------------------------- ### detect_ai_batch(texts, lang) Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Performs AI detection on a list of texts in a batch operation. This is more efficient for analyzing multiple text samples simultaneously. ```APIDOC ## detect_ai_batch(texts, lang) ### Description Batch AI detection for multiple texts. ### Method `detect_ai_batch` ### Parameters #### Path Parameters - **texts** (list[str]) - Required - A list of texts to analyze. - **lang** (str) - Required - The language of the texts (e.g., "en"). ### Returns `list[dict]` - A list of results, one for each input text. ``` -------------------------------- ### Commit Changes in Git Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Stage and commit your code changes with a descriptive message. This is a standard step in the Git workflow for contributions. ```bash git commit -m 'Add my feature' ``` -------------------------------- ### Multi-Language Text Processing with Auto-Detection Source: https://github.com/ksanyok/texthumanize/blob/main/docs/COOKBOOK.md Processes text in multiple languages, automatically detecting the language of each input text before humanization. Prints the detected language and the humanized text. ```python from texthumanize import humanize # Auto-detect language texts = { "en": "The implementation utilizes comprehensive methodologies.", "ru": "Осуществление данной задачи является приоритетным.", "de": "Die Implementierung erfordert eine umfassende Analyse.", } for label, text in texts.items(): result = humanize(text, lang="auto") print(f"[{result.lang}] {result.text}") ``` -------------------------------- ### Sentence Rewriting with SyntaxRewriter Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Use SyntaxRewriter to apply sentence-level transformations, such as active/passive voice changes, clause inversions, and adverb migrations. A seed is used for reproducibility. ```python from texthumanize import SyntaxRewriter sr = SyntaxRewriter(lang="en", seed=42) variants = sr.rewrite("The team completed the project on time.") for v in variants: print(v) ``` -------------------------------- ### Target Student Writing Style Source: https://github.com/ksanyok/texthumanize/blob/main/docs/COOKBOOK.md Humanizes text to a 'student' writing style, characterized by shorter sentences and simpler vocabulary, with a specified intensity. ```python from texthumanize import humanize, STYLE_PRESETS result = humanize( scientific_text, target_style="student", intensity=70, ) # Output will have shorter sentences, simpler vocabulary ``` -------------------------------- ### analyze_tone(text, lang) Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Analyzes the tone, formality, and subjectivity of the input text. It provides scores for these aspects and identifies detected tone markers. ```APIDOC ## analyze_tone(text, lang) ### Description Analyze text tone, formality level, and subjectivity. ### Method `analyze_tone` ### Parameters #### Path Parameters - **text** (str) - Required - The input text to analyze. - **lang** (str) - Required - The language of the text (e.g., "en"). ### Returns `dict` with keys: `primary_tone`, `formality`, `subjectivity`, `confidence`, `scores`, `markers`. ``` -------------------------------- ### Adjust Text Tone: Casual to Formal Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Converts casual text to a formal tone using the adjust_tone function. Specify the target tone and language. ```python formal = adjust_tone( "Hey, we gotta fix this ASAP!", target="formal", lang="en", ) print(formal) ``` -------------------------------- ### Adjust Text Tone: Formal to Casual Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Converts formal text to a casual tone using the adjust_tone function. Specify the target tone and language. ```python casual = adjust_tone( "It is imperative to implement this solution immediately.", target="casual", # very_formal, formal, neutral, casual, very_casual lang="en", intensity=0.5, # 0.0-1.0: strength of adjustment ) print(casual) ``` -------------------------------- ### analyze(text, lang) Source: https://github.com/ksanyok/texthumanize/blob/main/docs/FULL_REFERENCE.md Analyzes input text to provide various naturalness and readability metrics. It returns an AnalysisReport object containing detailed statistics about the text's structure and quality. ```APIDOC ## analyze(text, lang) ### Description Analyzes text and returns naturalness metrics. ### Method `analyze` ### Parameters #### Path Parameters - **text** (str) - Required - The input text to analyze. - **lang** (str) - Required - The language of the text (e.g., "en"). ### Returns `AnalysisReport` dataclass containing various text metrics. ``` -------------------------------- ### Batch AI Detection Source: https://github.com/ksanyok/texthumanize/blob/main/README.md Process multiple text inputs efficiently in a single call to detect AI content across a list of texts. Language specification is required. ```python # Batch detection results = detect_ai_batch(["Text 1", "Text 2", "Text 3"], lang="en") ```