Spaces:
Runtime error

humanizer-engine / app /main.py
faseehsandhu's picture
stage 2 working
446613d
Raw History Blame Contribute Delete
7.45 kB
"""
Humanization Engine -- FastAPI application entry point.
Models are loaded once at startup via the lifespan context manager
and shared across all async requests.
"""
from __future__ import annotations
import logging
import time
from contextlib import asynccontextmanager
from typing import AsyncGenerator
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from app.config import get_settings
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Application-level state -- models loaded once, shared across requests
# ---------------------------------------------------------------------------
_start_time: float = 0.0
_models_loaded: bool = False
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
"""Load all heavyweight resources once at startup, release on shutdown."""
global _start_time, _models_loaded
settings = get_settings()
_start_time = time.time()
logger.info("Starting Humanization Engine ...")
# ---- 1. spaCy ----
nlp = None
try:
import spacy # type: ignore
logger.info("Loading spaCy model '%s' ...", settings.spacy_model)
nlp = spacy.load(settings.spacy_model)
app.state.nlp = nlp
logger.info("spaCy loaded.")
except Exception as exc:
logger.error("Failed to load spaCy model: %s", exc)
app.state.nlp = None
# ---- 2. Qwen2.5-0.5B perplexity scorer ----
scorer = None
try:
from app.core.perplexity_scorer import PerplexityScorer
logger.info("Loading Qwen2.5-0.5B perplexity scorer (~1.1 GB RAM) ...")
scorer = PerplexityScorer(model_id=settings.qwen_model_id)
app.state.perplexity_scorer = scorer
logger.info("Qwen2.5-0.5B loaded.")
except Exception as exc:
logger.error("Failed to load perplexity scorer: %s", exc)
app.state.perplexity_scorer = None
# ---- 3. language_tool_python ----
language_tool = None
try:
import language_tool_python # type: ignore
logger.info("Initialising LanguageTool ...")
language_tool = language_tool_python.LanguageTool("en-US")
app.state.language_tool = language_tool
logger.info("LanguageTool ready.")
except Exception as exc:
logger.error("Failed to initialise LanguageTool: %s", exc)
app.state.language_tool = None
# ---- 4. Warm up Qwen2.5 with a dummy inference ----
if scorer is not None:
try:
logger.info("Warming up Qwen2.5-0.5B ...")
scorer.score_sentence("This is a warm-up sentence.")
logger.info("Qwen2.5-0.5B warm-up complete.")
except Exception as exc:
logger.warning("Warm-up inference failed: %s", exc)
# ---- 5. Build Stage 1 TextAnalyzer ----
analyzer = None
try:
from app.core.analyzer import TextAnalyzer
analyzer = TextAnalyzer(
nlp=nlp,
perplexity_scorer=scorer,
vocab_path=settings.ai_vocabulary_path,
transition_path=settings.transition_words_path,
heuristic_path=settings.heuristic_patterns_path,
)
app.state.analyzer = analyzer
logger.info("TextAnalyzer (Stage 1) ready.")
except Exception as exc:
logger.error("Failed to create TextAnalyzer: %s", exc)
app.state.analyzer = None
# ---- 6. Build Stage 2 LLMRewriter ----
rewriter = None
try:
from app.core.prompt_manager import PromptManager
from app.core.llm_rewriter import LLMRewriter
prompt_manager = PromptManager()
rewriter = LLMRewriter(prompt_manager=prompt_manager)
app.state.rewriter = rewriter
logger.info("LLMRewriter (Stage 2) ready.")
except Exception as exc:
logger.error("Failed to create LLMRewriter: %s", exc)
app.state.rewriter = None
# ---- 7. Build Stage 3 PostValidator ----
post_validator = None
try:
from app.core.post_validator import PostValidator
post_validator = PostValidator(
nlp=nlp,
perplexity_scorer=scorer,
language_tool=language_tool,
vocab_path=settings.ai_vocabulary_path,
)
app.state.post_validator = post_validator
logger.info("PostValidator (Stage 3) ready.")
except Exception as exc:
logger.error("Failed to create PostValidator: %s", exc)
app.state.post_validator = None
# ---- 8. Wire up the full pipeline ----
try:
from app.core.pipeline import HumanizationPipeline
if analyzer and rewriter and post_validator:
pipeline = HumanizationPipeline(
analyzer=analyzer,
rewriter=rewriter,
post_validator=post_validator,
)
app.state.pipeline = pipeline
logger.info("HumanizationPipeline wired and ready.")
else:
app.state.pipeline = None
logger.warning("Pipeline not created: one or more stages missing.")
except Exception as exc:
logger.error("Failed to create pipeline: %s", exc)
app.state.pipeline = None
_models_loaded = True
logger.info("Humanization Engine ready. Startup complete.")
yield # Application runs here
# ---- Shutdown: release resources ----
logger.info("Shutting down ...")
if scorer:
del scorer
if language_tool:
try:
language_tool.close()
except Exception:
pass
logger.info("Shutdown complete.")
# ---------------------------------------------------------------------------
# FastAPI application
# ---------------------------------------------------------------------------
def create_app() -> FastAPI:
"""Factory function that creates and configures the FastAPI application."""
settings = get_settings()
logging.basicConfig(
level=getattr(logging, settings.log_level),
format="%(asctime)s %(levelname)-8s %(name)s %(message)s",
)
application = FastAPI(
title="Humanization Engine",
description=(
"Analysis-Guided LLM Rewrite -- bypasses AI detection while "
"preserving academic quality."
),
version="1.0.0",
lifespan=lifespan,
)
# CORS -- allow all origins for development
application.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# API routes
from app.api.routes import router as api_router # noqa: E402
application.include_router(api_router)
# Serve frontend as static files
try:
application.mount(
"/",
StaticFiles(directory="frontend", html=True),
name="frontend",
)
except Exception:
# frontend directory may not exist yet during testing
pass
return application
app = create_app()
# ---------------------------------------------------------------------------
# Expose startup time and model status for the /health endpoint
# ---------------------------------------------------------------------------
def get_start_time() -> float:
return _start_time
def get_models_loaded() -> bool:
return _models_loaded