""" API route definitions for the Humanization Engine. Endpoints: POST /humanize -- full 3-stage pipeline POST /analyze -- Stage 1 analysis only (debug/testing) GET /health -- health check """ from __future__ import annotations import logging import time from collections import defaultdict from typing import Any from fastapi import APIRouter, HTTPException, Request from fastapi.responses import JSONResponse from app.api.models import ( AnalyzeRequest, AnalyzeResponse, HealthResponse, HumanizeRequest, HumanizeResponse, ProcessingStats, ) from app.utils.text_utils import count_words logger = logging.getLogger(__name__) router = APIRouter() # --------------------------------------------------------------------------- # Simple in-memory rate limiter (per-IP, 17 requests per minute) # --------------------------------------------------------------------------- _rate_limit: dict[str, list[float]] = defaultdict(list) _RATE_WINDOW: float = 60.0 # seconds _RATE_MAX: int = 17 # requests per window def _check_rate_limit(client_ip: str) -> bool: """Return True if the request is allowed, False if rate-limited.""" now = time.time() timestamps = _rate_limit[client_ip] # Remove timestamps outside the window. _rate_limit[client_ip] = [t for t in timestamps if now - t < _RATE_WINDOW] if len(_rate_limit[client_ip]) >= _RATE_MAX: return False _rate_limit[client_ip].append(now) return True # --------------------------------------------------------------------------- # POST /humanize # --------------------------------------------------------------------------- @router.post("/humanize", response_model=HumanizeResponse) async def humanize(request: Request, body: HumanizeRequest) -> Any: """Run the full humanization pipeline (Stage 1 -> 2 -> 3).""" client_ip = request.client.host if request.client else "unknown" if not _check_rate_limit(client_ip): return JSONResponse( status_code=429, content={"success": False, "error": "Rate limit exceeded", "code": "RATE_LIMITED"}, ) # Input validation. from app.config import get_settings settings = get_settings() word_count = count_words(body.text) if word_count < settings.min_input_words: return JSONResponse( status_code=400, content={ "success": False, "error": f"Input too short: {word_count} words (minimum {settings.min_input_words})", "code": "INPUT_TOO_SHORT", }, ) if word_count > settings.max_input_words: return JSONResponse( status_code=400, content={ "success": False, "error": f"Input too long: {word_count} words (maximum {settings.max_input_words})", "code": "INPUT_TOO_LONG", }, ) # Get pipeline from app state. pipeline = getattr(request.app.state, "pipeline", None) if pipeline is None: return JSONResponse( status_code=503, content={ "success": False, "error": "Pipeline not initialized. Server is starting up.", "code": "PROCESSING_ERROR", }, ) logger.info("POST /humanize: %d words, mode=%s, ip=%s", word_count, body.mode, client_ip) try: result = await pipeline.process(body.text, mode=body.mode) except Exception as exc: logger.error("Pipeline error: %s", exc, exc_info=True) return JSONResponse( status_code=500, content={ "success": False, "error": "Internal processing error", "code": "PROCESSING_ERROR", }, ) # If both LLMs failed, return an error instead of the original text. if not result.get("success", False): error_msg = result.get("error", "LLM rewrite failed") logger.error("Pipeline returned failure: %s", error_msg) return JSONResponse( status_code=502, content={ "success": False, "error": f"LLM rewrite failed: {error_msg}", "code": "LLM_TIMEOUT", }, ) stats_raw = result.get("stats", {}) stats = ProcessingStats( input_word_count=stats_raw.get("input_word_count", word_count), output_word_count=stats_raw.get("output_word_count", 0), expansion_percentage=stats_raw.get("expansion_percentage", 0.0), input_avg_perplexity=stats_raw.get("input_avg_perplexity"), output_avg_perplexity=stats_raw.get("output_avg_perplexity"), input_burstiness_cv=stats_raw.get("input_burstiness_cv"), output_burstiness_cv=stats_raw.get("output_burstiness_cv"), banned_words_found_in_output=stats_raw.get("banned_words_found_in_output", []), banned_words_auto_fixed=stats_raw.get("banned_words_auto_fixed", 0), instructions_generated=stats_raw.get("instructions_generated", 0), high_risk_sentences=stats_raw.get("high_risk_sentences", 0), processing_time_ms=stats_raw.get("processing_time_ms", 0.0), stage1_time_ms=stats_raw.get("stage1_time_ms", 0.0), stage2_time_ms=stats_raw.get("stage2_time_ms", 0.0), stage3_time_ms=stats_raw.get("stage3_time_ms", 0.0), prompt_variant_used=stats_raw.get("prompt_variant_used", ""), llm_used=stats_raw.get("llm_used", ""), ) return HumanizeResponse( output_text=result.get("output_text", body.text), stats=stats, ) # --------------------------------------------------------------------------- # POST /analyze # --------------------------------------------------------------------------- @router.post("/analyze", response_model=AnalyzeResponse) async def analyze(request: Request, body: AnalyzeRequest) -> Any: """Run Stage 1 analysis only (no LLM call). Useful for debugging.""" analyzer = getattr(request.app.state, "analyzer", None) if analyzer is None: return JSONResponse( status_code=503, content={ "success": False, "error": "Analyzer not initialized. Server is starting up.", "code": "PROCESSING_ERROR", }, ) logger.info("POST /analyze: %d words", count_words(body.text)) try: analysis = analyzer.analyze(body.text) except Exception as exc: logger.error("Analysis error: %s", exc, exc_info=True) return JSONResponse( status_code=500, content={"success": False, "error": str(exc), "code": "PROCESSING_ERROR"}, ) return AnalyzeResponse(analysis=analysis) # --------------------------------------------------------------------------- # GET /health # --------------------------------------------------------------------------- @router.get("/health", response_model=HealthResponse) async def health(request: Request) -> Any: """Health check endpoint.""" from app.main import get_start_time, get_models_loaded models_loaded = get_models_loaded() start_time = get_start_time() uptime = round(time.time() - start_time, 1) if start_time > 0 else 0.0 status = "healthy" if models_loaded else "starting" # Check if critical components are available. has_pipeline = getattr(request.app.state, "pipeline", None) is not None if models_loaded and not has_pipeline: status = "degraded" return HealthResponse( status=status, models_loaded=models_loaded, uptime_seconds=uptime, )