tester / app.py
devilseye2004's picture
Upload 10 files
7c956fc verified
Raw History Blame Contribute Delete
15.6 kB
"""
AI Humanizer API - Three-Pass Text Enhancement
Copyright (c) 2026
Three-pass humanization using internal rewriting system.
No external APIs - pure Python implementation.
"""
import os
import logging
import time
import tempfile
from typing import Optional, Dict
from fastapi import FastAPI, HTTPException, UploadFile, File, Form
from fastapi.responses import Response
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from humanizer_three_pass import humanizer, passes_quality_check
from formatting_detector import preserve_formatting, formatting_detector
from markdown_converter import convert_for_copy, convert_for_display, analyze_formatting
try:
from export_pipeline import export_pipeline
HAS_EXPORT_PIPELINE = True
except ImportError as e:
HAS_EXPORT_PIPELINE = False
EXPORT_PIPELINE_ERROR = str(e)
logger.warning(f"Export pipeline not available: {e}")
import config
# --- LOGGING CONFIGURATION ---
logging.basicConfig(level=getattr(logging, config.settings.log_level))
logger = logging.getLogger(__name__)
# --- APP INITIALIZATION ---
app = FastAPI(title="Three-Pass Humanizer API", version="3.0")
# ── CORS ──────────────────────────────────────────────────────
# allow_credentials MUST be False when allow_origins=["*"]
# Browser will block the request otherwise (CORS spec violation)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=False, # ← IMPORTANT: False, not True
allow_methods=["*"],
allow_headers=["*"],
)
# --- API MODELS ---
class HumanizeRequest(BaseModel):
text: str
style: Optional[str] = "neutral" # Accept but ignore for now
class HumanizeResponse(BaseModel):
output: str # Formatted text with Markdown (for display)
plain_text: str # Plain text without Markdown (for copy/download)
human_score: int
ai_score: int
uniqueness: int
word_count_original: int
word_count_output: int
processing_time_ms: int
passes: int = 3
quality_check_passed: bool
formatting_preserved: Optional[Dict] = None
formatting_summary: Optional[Dict] = None
# --- QUALITY CHECK WITH RETRY ---
def humanize_with_quality_check(text: str, max_retries: int = config.settings.max_retries) -> str:
"""
Humanize text with quality check and automatic retry
Uses smart humanizer with formatting preservation
"""
retry_count = 0
while retry_count <= max_retries:
# Perform humanization with formatting preservation
humanized = preserve_formatting(text, humanizer.humanize)
# Check quality (only on natural language parts)
if passes_quality_check(humanized):
logger.info(f"Quality check passed (attempt {retry_count + 1})")
return humanized
else:
retry_count += 1
if retry_count <= max_retries:
logger.info(f"Quality check failed, retrying (attempt {retry_count})")
# Use the humanized output as input for retry
text = humanized
else:
logger.warning(f"Quality check failed after {max_retries} retries")
return humanized # Return the best we have
return humanized
# --- SCORE CALCULATION ---
def compute_scores(original: str, humanized: str) -> dict:
"""Compute humanization scores"""
import re
import statistics
# Split into sentences
sentences = re.findall(r'[^.!?]+[.!?]+', humanized) or []
if len(sentences) >= 2:
try:
# Calculate sentence length variation
lens = [len(s.split()) for s in sentences]
std = statistics.pstdev(lens)
burst_score = min(int(std * 10), 60)
except:
burst_score = 0
else:
burst_score = 0
# Contraction score
contractions = len(re.findall(r"\b\w+'\w+\b", humanized))
contr_score = min(contractions * 4, 25)
# Vocabulary change score
orig_words = set(original.lower().split())
hum_words = set(humanized.lower().split())
if orig_words:
changed = len(orig_words - hum_words)
vocab_score = min(int((changed / len(orig_words)) * 50), 35)
else:
vocab_score = 0
# Quality check result
quality_passed = passes_quality_check(humanized)
# Base human score with quality bonus
base_score = 75 if quality_passed else 60
human_score = min(
base_score + burst_score + contr_score + vocab_score,
99
)
return {
"human_score": human_score,
"ai_score": 100 - human_score,
"uniqueness": min(85 + vocab_score + burst_score, 99),
"quality_check_passed": quality_passed
}
# --- ENDPOINTS ---
@app.get("/health")
async def health():
"""Health check endpoint"""
return {
"status": "ok",
"version": "3.0",
"system": "Three-Pass Humanizer",
"passes": config.settings.passes
}
@app.get("/")
async def root():
return {
"message": "Three-Pass Humanizer API is running",
"endpoint": "POST /humanize",
"description": "Internal three-pass rewriting system"
}
@app.post("/humanize", response_model=HumanizeResponse)
async def humanize_endpoint(req: HumanizeRequest):
"""
Main endpoint for three-pass humanization.
Uses internal rewriting system with quality check and retry.
"""
try:
# Validate
text = req.text.strip() if req.text else ""
if not text:
raise HTTPException(status_code=400, detail="Text cannot be empty")
word_count = len(text.split())
if word_count > 10000: # Increased limit for three-pass system
raise HTTPException(status_code=400, detail="Text too long. Max 10,000 words.")
# Process with three-pass humanization
start = time.time()
humanized = humanize_with_quality_check(text)
scores = compute_scores(text, humanized)
elapsed_ms = int((time.time() - start) * 1000)
logger.info(f"Three-pass humanized {word_count} words β†’ {len(humanized.split())} words in {elapsed_ms}ms")
logger.info(f"Quality check: {scores['quality_check_passed']}, Human score: {scores['human_score']}")
# Get formatting preservation analysis
formatting_analysis = analyze_formatting(text)
# Convert to plain text for copy/download (without Markdown syntax)
plain_text = convert_for_copy(humanized)
return HumanizeResponse(
output=humanized, # Formatted text with Markdown (for display)
plain_text=plain_text, # Plain text without Markdown (for copy/download)
word_count_original=word_count,
word_count_output=len(humanized.split()),
processing_time_ms=elapsed_ms,
formatting_preserved=formatting_analysis,
**scores,
)
except HTTPException:
# Re-raise HTTP exceptions (validation errors)
raise
except Exception as e:
# Catch all other exceptions, log with full traceback, and return 500
logger.error(f"Humanization processing error: {str(e)}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Processing failed: {str(e)}")
@app.post("/humanize-document")
async def humanize_document(
file: UploadFile = File(..., description="Document file (TXT or DOCX)"),
style: str = Form("neutral"),
output_format: str = Form("json", description="Output format: json, txt, docx, or pdf")
):
"""
Handles file uploads and processes documents with three-pass humanization.
Supports TXT and DOCX input, returns JSON or file download.
"""
try:
# Read file content
content = await file.read()
# Determine file type and extract text
filename = file.filename.lower()
if filename.endswith('.txt'):
try:
text = content.decode('utf-8')
except UnicodeDecodeError as e:
logger.error(f"Failed to decode TXT file: {str(e)}")
raise HTTPException(
status_code=400,
detail="Invalid TXT file encoding. Please ensure the file is UTF-8 encoded."
)
elif filename.endswith('.docx'):
# For DOCX, we need python-docx library
# For now, return error if not available
try:
from docx import Document
import io
doc = Document(io.BytesIO(content))
# Simple text extraction from DOCX
text = "\n".join([paragraph.text for paragraph in doc.paragraphs if paragraph.text.strip()])
except ImportError:
raise HTTPException(
status_code=400,
detail="DOCX support not available. Please upload TXT files or install python-docx."
)
except Exception as e:
logger.error(f"Failed to parse DOCX file: {str(e)}")
raise HTTPException(
status_code=400,
detail="Invalid or corrupted DOCX file. Please ensure the file is a valid DOCX document."
)
else:
raise HTTPException(status_code=400, detail="Unsupported file type. Use .txt or .docx")
# Validate text
if not text.strip():
raise HTTPException(status_code=400, detail="Document is empty")
word_count = len(text.split())
if word_count > 10000:
raise HTTPException(status_code=400, detail="Document too long. Max 10,000 words.")
# Process with three-pass humanization
start = time.time()
humanized = humanize_with_quality_check(text)
elapsed_ms = int((time.time() - start) * 1000)
logger.info(f"Three-pass humanized document: {word_count} words in {elapsed_ms}ms")
# Return based on requested format
if output_format == "json":
scores = compute_scores(text, humanized)
# Convert to plain text for copy/download (without Markdown syntax)
plain_text = convert_for_copy(humanized)
return {
"output": humanized, # Formatted text with Markdown (for display)
"plain_text": plain_text, # Plain text without Markdown (for copy/download)
"metrics": {
"word_count_original": word_count,
"word_count_output": len(humanized.split()),
"processing_time_ms": elapsed_ms,
"human_score": scores["human_score"],
"quality_check_passed": scores["quality_check_passed"],
"passes": 3
}
}
elif output_format == "txt":
# Convert to plain text for download (without Markdown syntax)
plain_text = convert_for_copy(humanized)
return Response(
content=plain_text.encode('utf-8'),
media_type="text/plain",
headers={"Content-Disposition": "attachment; filename=humanized.txt"}
)
elif output_format == "docx":
# For DOCX output, we need python-docx
try:
from docx import Document
import io
# Convert to plain text for DOCX export (without Markdown syntax)
plain_text = convert_for_copy(humanized)
doc = Document()
for paragraph in plain_text.split('\n\n'):
if paragraph.strip():
doc.add_paragraph(paragraph.strip())
# Save to bytes
docx_io = io.BytesIO()
doc.save(docx_io)
docx_io.seek(0)
return Response(
content=docx_io.getvalue(),
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
headers={"Content-Disposition": "attachment; filename=humanized.docx"}
)
except ImportError:
raise HTTPException(
status_code=400,
detail="DOCX output not available. Please use 'json' or 'txt' format."
)
except Exception as e:
logger.error(f"Failed to create DOCX output: {str(e)}")
raise HTTPException(
status_code=500,
detail="Failed to generate DOCX output. Please try 'json' or 'txt' format."
)
elif output_format == "pdf":
# For PDF output, use export pipeline
if not HAS_EXPORT_PIPELINE:
raise HTTPException(
status_code=400,
detail="PDF export not available. Export pipeline failed to load."
)
try:
# Convert to plain text for PDF export (without Markdown syntax)
plain_text = convert_for_copy(humanized)
pdf_bytes = export_pipeline.to_pdf(plain_text)
return Response(
content=pdf_bytes,
media_type="application/pdf",
headers={"Content-Disposition": "attachment; filename=humanized.pdf"}
)
except ImportError as e:
logger.error(f"PDF export dependency error: {str(e)}")
raise HTTPException(
status_code=400,
detail=f"PDF output not available: {str(e)}"
)
except Exception as e:
logger.error(f"Failed to create PDF output: {str(e)}")
raise HTTPException(
status_code=500,
detail=f"Failed to generate PDF output: {str(e)}"
)
else:
raise HTTPException(status_code=400, detail="Invalid output format. Use: json, txt, docx, or pdf")
except HTTPException:
raise
except Exception as e:
logger.error(f"Document processing error: {str(e)}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Processing failed: {str(e)}")
@app.post("/humanize-stream")
async def humanize_stream(req: HumanizeRequest):
"""
Streaming endpoint (legacy compatibility).
Returns same as /humanize endpoint.
"""
return await humanize_endpoint(req)
# ── DO NOT add @app.options("/humanize") ──────────────────────
# CORSMiddleware handles OPTIONS preflight automatically.
# A manual OPTIONS handler conflicts with the middleware.
if __name__ == "__main__":
import uvicorn
port = int(os.getenv("PORT", config.settings.port))
uvicorn.run(app, host="0.0.0.0", port=port)