""" HumanizationPipeline -- wires Stage 1, 2, and 3 together. Provides a single ``process()`` entry point that: 1. Runs Stage 1 (TextAnalyzer) -- local analysis, produces instructions. 2. Runs Stage 2 (LLMRewriter) -- single async LLM call with instructions. 3. Runs Stage 3 (PostValidator) -- local validation and micro-corrections. Includes per-stage timing and comprehensive error handling with fallbacks. """ from __future__ import annotations import logging import time from typing import Any from app.core.analyzer import TextAnalyzer from app.core.llm_rewriter import LLMRewriter, RewriteResult from app.core.post_validator import PostValidator from app.core.prompt_manager import PromptManager logger = logging.getLogger(__name__) class HumanizationPipeline: """Main pipeline orchestrator. Args: analyzer: Stage 1 TextAnalyzer. rewriter: Stage 2 LLMRewriter. post_validator: Stage 3 PostValidator. """ def __init__( self, analyzer: TextAnalyzer, rewriter: LLMRewriter, post_validator: PostValidator, ) -> None: self.analyzer = analyzer self.rewriter = rewriter self.post_validator = post_validator # ------------------------------------------------------------------ # Public API # ------------------------------------------------------------------ async def process( self, text: str, mode: str = "standard", ) -> dict[str, Any]: """Run the full 3-stage humanization pipeline. Args: text: The AI-generated input text. mode: 'standard' or 'thorough'. Returns: Dict with: - success: bool - output_text: str (rewritten text, or original on failure) - analysis: dict (Stage 1 result) - stats: dict (processing statistics) - error: str (empty on success) """ t_total = time.perf_counter() # ---- Stage 1: Analysis (local, no API) ---- analysis_result, stage1_ms = self._run_stage1(text) # ---- Stage 2: LLM Rewrite (single API call) ---- rewrite_result = await self._run_stage2(text, analysis_result) # ---- Stage 3: Post-validation (local) ---- output_text = rewrite_result.output_text validation, stage3_ms = self._run_stage3( text, output_text, analysis_result, mode ) # ---- Assemble final response ---- total_ms = round((time.perf_counter() - t_total) * 1000, 1) stats = validation.get("stats", {}) stats["processing_time_ms"] = total_ms stats["stage1_time_ms"] = stage1_ms stats["stage2_time_ms"] = rewrite_result.stage2_time_ms stats["prompt_variant_used"] = rewrite_result.variant_used stats["llm_used"] = rewrite_result.llm_used return { "success": rewrite_result.success, "output_text": validation.get("output_text", output_text), "analysis": analysis_result, "stats": stats, "error": rewrite_result.error, } # ------------------------------------------------------------------ # Stage runners with error isolation # ------------------------------------------------------------------ def _run_stage1(self, text: str) -> tuple[dict[str, Any], float]: """Run Stage 1 analysis. Returns (analysis_result, elapsed_ms).""" t0 = time.perf_counter() try: result = self.analyzer.analyze(text) elapsed = round((time.perf_counter() - t0) * 1000, 1) logger.info("Stage 1 complete in %.1f ms", elapsed) return result, elapsed except Exception as exc: elapsed = round((time.perf_counter() - t0) * 1000, 1) logger.error("Stage 1 failed: %s. Using fallback generic analysis.", exc) return self._fallback_analysis(), elapsed async def _run_stage2( self, text: str, analysis_result: dict[str, Any] ) -> RewriteResult: """Run Stage 2 LLM rewrite. Returns RewriteResult.""" try: return await self.rewriter.rewrite(text, analysis_result) except Exception as exc: logger.error("Stage 2 unexpected error: %s. Returning original.", exc) return RewriteResult( output_text=text, success=False, error=str(exc), ) def _run_stage3( self, original_text: str, rewritten_text: str, analysis_result: dict[str, Any], mode: str, ) -> tuple[dict[str, Any], float]: """Run Stage 3 post-validation. Returns (result, elapsed_ms).""" t0 = time.perf_counter() try: result = self.post_validator.validate( original_text, rewritten_text, analysis_result, mode ) elapsed = round((time.perf_counter() - t0) * 1000, 1) logger.info("Stage 3 complete in %.1f ms", elapsed) return result, elapsed except Exception as exc: elapsed = round((time.perf_counter() - t0) * 1000, 1) logger.error("Stage 3 failed: %s. Returning Stage 2 output as-is.", exc) return {"output_text": rewritten_text, "stats": {}}, elapsed # ------------------------------------------------------------------ # Fallback analysis (when Stage 1 crashes) # ------------------------------------------------------------------ @staticmethod def _fallback_analysis() -> dict[str, Any]: """Return a minimal analysis that tells the LLM to do a basic rewrite.""" return { "summary": { "total_sentences": 0, "high_risk_sentences": 0, "medium_risk_sentences": 0, "low_risk_sentences": 0, "burstiness_cv": 0.0, "burstiness_rating": "unknown", "ai_vocabulary_count": 0, "transition_flags": 0, "opening_pattern_flags": 0, "overall_risk": "unknown", "analysis_time_ms": 0.0, }, "instructions": [ { "type": "general", "sentence_index": None, "severity": "medium", "instruction": ( "Rewrite this text as a university student polishing their " "essay. Make it sound natural and human. Vary sentence length, " "use occasional contractions, and avoid overly formal language." ), } ], "banned_words": [], "sentence_perplexities": [], }