import asyncio import uuid import logging from typing import List, Optional, Dict, Any from contextlib import asynccontextmanager from fastapi import FastAPI, HTTPException, BackgroundTasks, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles from pydantic import BaseModel, HttpUrl from config import config from storage import db from scraper import scrape_urls, close_browser_pool from model import classify_content, initialize_model, classifier logging.basicConfig(level=getattr(logging, config.log_level)) logger = logging.getLogger(__name__) class ScrapeRequest(BaseModel): urls: List[HttpUrl] class ScrapeResponse(BaseModel): job_id: str status: str total: int class JobStatus(BaseModel): job_id: str status: str completed: int total: int results: Optional[List[dict]] = None class PageResponse(BaseModel): id: int url: str title: Optional[str] status_code: int text_length: int scraped_at: str error: Optional[str] clean_text: Optional[str] = None markdown: Optional[str] = None metadata: Optional[Dict[str, Any]] = None links: Optional[List[str]] = None images: Optional[List[Dict[str, str]]] = None headings: Optional[List[Dict[str, Any]]] = None features: Optional[dict] = None prediction: Optional[dict] = None class StatsResponse(BaseModel): total_pages: int error_pages: int success_pages: int total_predictions: int database_size_mb: float @asynccontextmanager async def lifespan(app: FastAPI): logger.info("Starting web scraper service") initialize_model() yield logger.info("Shutting down web scraper service") await close_browser_pool() app = FastAPI( title="Web Scraper API", description="Firecrawl-style web scraper with ML-based content classification", version="1.0.0", lifespan=lifespan ) app.mount("/static", StaticFiles(directory="static"), name="static") app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.get("/", include_in_schema=False) async def serve_index(): from fastapi.responses import FileResponse return FileResponse("static/index.html") @app.get("/health") async def health_check(): return {"status": "healthy", "service": "web-scraper"} @app.post("/scrape", response_model=ScrapeResponse) async def create_scrape_job(request: ScrapeRequest, background_tasks: BackgroundTasks): urls = [str(url) for url in request.urls] job_id = str(uuid.uuid4())[:8] db.create_job(job_id, urls) background_tasks.add_task(process_scrape_job, job_id, urls) return ScrapeResponse(job_id=job_id, status="pending", total=len(urls)) async def process_scrape_job(job_id: str, urls: List[str]): try: results = await scrape_urls(urls) for i, result in enumerate(results): page_id = db.save_page( url=result["url"], html=result["html"] or "", status_code=result["status_code"], title=result["title"], error=result["error"], clean_text=result.get("clean_text"), markdown=result.get("markdown"), metadata=result.get("metadata"), links=result.get("links"), images=result.get("images"), headings=result.get("headings"), ) if result["html"] and not result["error"]: classification = classify_content(result["html"], result["title"]) db.save_features(page_id, classification["features"]) pred = classification["prediction"] db.save_prediction( page_id=page_id, category=pred["category"], relevance_score=pred["relevance_score"], is_spam=pred["is_spam"], confidence=pred["confidence"], model_version=pred["model_version"] ) db.update_job_progress(job_id, i + 1, "running" if i < len(urls) - 1 else "completed") if classifier.should_retrain(): logger.info("Retraining model with new data") classifier.retrain_from_db() except Exception as e: logger.error(f"Job {job_id} failed: {e}") db.update_job_progress(job_id, 0, "failed") @app.get("/scrape/{job_id}", response_model=JobStatus) async def get_job_status(job_id: str): job = db.get_job(job_id) if not job: raise HTTPException(status_code=404, detail="Job not found") results = None if job["status"] == "completed": pages = [] for url in job["urls"]: page = db.get_page_by_url(url) if page: pages.append({ "url": page["url"], "title": page["title"], "status_code": page["status_code"], "text_length": page.get("text_length", 0), "error": page["error"], "clean_text": page.get("clean_text"), "markdown": page.get("markdown"), "metadata": page.get("metadata"), "links": page.get("links"), "images": page.get("images"), "headings": page.get("headings"), "features": db.get_features(page["id"]), "prediction": db.get_prediction(page["id"]), }) results = pages return JobStatus( job_id=job["job_id"], status=job["status"], completed=job["completed"], total=job["total"], results=results ) @app.get("/pages", response_model=List[PageResponse]) async def list_pages(limit: int = 50, offset: int = 0, status: Optional[str] = None): pages = db.get_pages(limit=limit, offset=offset, status=status) result = [] for page in pages: result.append(PageResponse( id=page["id"], url=page["url"], title=page["title"], status_code=page["status_code"], text_length=page.get("text_length", 0), scraped_at=page["scraped_at"], error=page["error"], clean_text=page.get("clean_text"), markdown=page.get("markdown"), metadata=page.get("metadata"), links=page.get("links"), images=page.get("images"), headings=page.get("headings"), features=db.get_features(page["id"]), prediction=db.get_prediction(page["id"]) )) return result @app.get("/pages/{page_id}", response_model=PageResponse) async def get_page(page_id: int): page = db.get_page(page_id) if not page: raise HTTPException(status_code=404, detail="Page not found") return PageResponse( id=page["id"], url=page["url"], title=page["title"], status_code=page["status_code"], text_length=page.get("text_length", 0), scraped_at=page["scraped_at"], error=page["error"], clean_text=page.get("clean_text"), markdown=page.get("markdown"), metadata=page.get("metadata"), links=page.get("links"), images=page.get("images"), headings=page.get("headings"), features=db.get_features(page["id"]), prediction=db.get_prediction(page["id"]) ) @app.get("/stats", response_model=StatsResponse) async def get_stats(): stats = db.get_stats() return StatsResponse(**stats) @app.post("/model/retrain") async def retrain_model(): result = classifier.retrain_from_db() return result @app.post("/model/predict") async def predict_content(request: Request): body = await request.json() html = body.get("html", "") title = body.get("title") if not html: raise HTTPException(status_code=400, detail="HTML content required") result = classify_content(html, title) return result @app.post("/db/vacuum") async def vacuum_database(): db.vacuum() return {"status": "Database vacuumed"} if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)