File size: 8,462 Bytes
c3b894b
 
 
a6de989
c3b894b
 
 
10032c3
c3b894b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6de989
 
 
 
 
 
c3b894b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6de989
c3b894b
 
 
 
10032c3
 
c3b894b
 
 
 
 
 
 
 
 
10032c3
 
 
 
 
c3b894b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6de989
 
 
 
 
 
 
c3b894b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6de989
c3b894b
a6de989
 
 
 
 
 
 
 
c3b894b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6de989
c3b894b
 
a6de989
 
 
 
 
 
 
 
c3b894b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6de989
c3b894b
 
a6de989
 
 
 
 
 
 
 
c3b894b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6de989
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
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)