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for the FIPI scraper service.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from datetime import datetime
8
+ import logging
9
+ import os
10
+ from pathlib import Path
11
+ import re
12
+ import ssl
13
+ from typing import Dict, List, Optional
14
+ from urllib.parse import parse_qs, urlparse
15
+
16
+ from bs4 import BeautifulSoup
17
+ from dotenv import load_dotenv
18
+ from fastapi import BackgroundTasks, FastAPI, HTTPException
19
+ from fastapi.middleware.cors import CORSMiddleware
20
+ from fastapi.responses import JSONResponse
21
+ import httpx
22
+
23
+ from models import (
24
+ CheckAnswerRequest,
25
+ CheckAnswerResponse,
26
+ ErrorResponse,
27
+ HealthResponse,
28
+ ScrapeRequest,
29
+ ScrapeResponse,
30
+ StatsResponse,
31
+ TaskResponse,
32
+ )
33
+ from scraper import FIPIScraper
34
+
35
+ BASE_DIR = Path(__file__).resolve().parent
36
+ load_dotenv(BASE_DIR / ".env")
37
+
38
+ logging.basicConfig(level=logging.INFO)
39
+ logger = logging.getLogger(__name__)
40
+
41
+ SUPABASE_AVAILABLE = False
42
+ SupabaseClient = None
43
+
44
+ try:
45
+ from supabase_client import SupabaseClient
46
+
47
+ SUPABASE_AVAILABLE = True
48
+ except ImportError as exc:
49
+ logger.warning("Supabase client import failed: %s", exc)
50
+ except Exception as exc: # pragma: no cover - startup guard
51
+ logger.warning("Supabase client init failed: %s", exc)
52
+
53
+
54
+ app = FastAPI(
55
+ title="AI Scraper FIPI",
56
+ description="Collects, stores and validates FIPI tasks.",
57
+ version="1.1.0",
58
+ )
59
+
60
+ app.add_middleware(
61
+ CORSMiddleware,
62
+ allow_origins=["*"],
63
+ allow_credentials=True,
64
+ allow_methods=["*"],
65
+ allow_headers=["*"],
66
+ )
67
+
68
+ scraper: Optional[FIPIScraper] = None
69
+ supabase_client: Optional[SupabaseClient] = None
70
+ last_auto_refresh_at: Optional[datetime] = None
71
+ refresh_in_progress = False
72
+
73
+
74
+ @app.on_event("startup")
75
+ async def startup_event() -> None:
76
+ global scraper, supabase_client
77
+
78
+ scraper = FIPIScraper(base_url=os.getenv("FIPI_BASE_URL", "https://fipi.ru"))
79
+ logger.info("FIPIScraper initialized")
80
+
81
+ if not SUPABASE_AVAILABLE:
82
+ logger.info("Supabase disabled")
83
+ return
84
+
85
+ supabase_url = os.getenv("SUPABASE_URL")
86
+ supabase_key = os.getenv("SUPABASE_SERVICE_KEY")
87
+ if not supabase_url or not supabase_key:
88
+ logger.warning("SUPABASE_URL or SUPABASE_SERVICE_KEY missing")
89
+ return
90
+
91
+ try:
92
+ client = SupabaseClient(url=supabase_url, key=supabase_key)
93
+ if await client.is_available():
94
+ supabase_client = client
95
+ logger.info("Supabase client connected")
96
+ else:
97
+ logger.error("Supabase is unavailable")
98
+ except Exception as exc: # pragma: no cover - startup guard
99
+ logger.error("Supabase startup error: %s", exc)
100
+
101
+
102
+ def _require_supabase() -> SupabaseClient:
103
+ if not supabase_client:
104
+ raise HTTPException(status_code=503, detail="Supabase is not configured")
105
+ return supabase_client
106
+
107
+
108
+ def _require_scraper() -> FIPIScraper:
109
+ if not scraper:
110
+ raise HTTPException(status_code=503, detail="Scraper is not configured")
111
+ return scraper
112
+
113
+
114
+ def _can_check_answer(task: Dict) -> bool:
115
+ source_url = task.get("source_url", "")
116
+ return "questions.php" in source_url and "qid=" in source_url
117
+
118
+
119
+ def _serialize_task(task: Dict) -> Dict:
120
+ payload = dict(task)
121
+ payload["can_check_answer"] = _can_check_answer(task)
122
+ return payload
123
+
124
+
125
+ async def _persist_tasks(tasks: List[Dict]) -> Dict[str, int]:
126
+ client = _require_supabase()
127
+ saved = 0
128
+ duplicates = 0
129
+ for task in tasks:
130
+ result = await client.insert_task(task)
131
+ if result:
132
+ saved += 1
133
+ else:
134
+ duplicates += 1
135
+ return {"saved": saved, "duplicates": duplicates}
136
+
137
+
138
+ def _needs_task_refresh(tasks: List[Dict]) -> bool:
139
+ if not tasks:
140
+ return True
141
+
142
+ dynamic_count = sum(1 for task in tasks if task.get("source_kind") == "dynamic_bank")
143
+ checkable_count = sum(1 for task in tasks if _can_check_answer(task))
144
+ minimum_total = max(10, int(os.getenv("SCRAPER_MIN_READY_TASKS", "40")))
145
+
146
+ if dynamic_count == 0 or checkable_count == 0:
147
+ return True
148
+
149
+ return len(tasks) < minimum_total
150
+
151
+
152
+ def _is_refresh_running() -> bool:
153
+ return refresh_in_progress
154
+
155
+
156
+ async def _run_refresh(subject: str = "russian") -> None:
157
+ global refresh_in_progress
158
+
159
+ try:
160
+ refresh_in_progress = True
161
+ scraped_tasks = await _require_scraper().scrape_tasks(subject=subject)
162
+ persisted = await _persist_tasks(scraped_tasks)
163
+ logger.info(
164
+ "Background refresh finished: scraped=%s saved=%s duplicates=%s",
165
+ len(scraped_tasks),
166
+ persisted["saved"],
167
+ persisted["duplicates"],
168
+ )
169
+ except Exception as exc: # pragma: no cover - background guard
170
+ logger.error("Background refresh failed: %s", exc)
171
+ finally:
172
+ refresh_in_progress = False
173
+
174
+
175
+ def _schedule_refresh(background_tasks: BackgroundTasks, subject: str = "russian") -> bool:
176
+ global last_auto_refresh_at
177
+
178
+ if _is_refresh_running():
179
+ return False
180
+
181
+ last_auto_refresh_at = datetime.utcnow()
182
+ background_tasks.add_task(_run_refresh, subject)
183
+ return True
184
+
185
+
186
+ async def _ensure_tasks_available(background_tasks: BackgroundTasks, subject: str = "russian") -> List[Dict]:
187
+ global last_auto_refresh_at
188
+
189
+ client = _require_supabase()
190
+ existing = await client.get_all_tasks()
191
+ if existing and not _needs_task_refresh(existing):
192
+ return existing
193
+
194
+ cooldown_minutes = max(1, int(os.getenv("SCRAPER_AUTO_REFRESH_COOLDOWN_MINUTES", "30")))
195
+ if last_auto_refresh_at and (datetime.utcnow() - last_auto_refresh_at).total_seconds() < cooldown_minutes * 60:
196
+ logger.info("Skipping auto refresh because cooldown is active")
197
+ return existing
198
+
199
+ if not existing:
200
+ logger.info("Tasks table is empty, running initial scrape")
201
+ last_auto_refresh_at = datetime.utcnow()
202
+ scraped_tasks = await _require_scraper().scrape_tasks(subject=subject)
203
+ await _persist_tasks(scraped_tasks)
204
+ refreshed = await client.get_all_tasks()
205
+ return refreshed or existing
206
+
207
+ if _schedule_refresh(background_tasks, subject):
208
+ logger.info("Existing tasks are stale or incomplete, scheduled background refresh")
209
+ else:
210
+ logger.info("Refresh is already running, returning existing tasks")
211
+
212
+ return existing
213
+
214
+
215
+ def _normalize_answer(answer: str) -> str:
216
+ return re.sub(r"\s+", "", answer.strip()).upper()
217
+
218
+
219
+ async def _resolve_task_guid(task: Dict) -> Optional[str]:
220
+ if task.get("task_guid"):
221
+ return task["task_guid"]
222
+
223
+ source_url = task.get("source_url", "")
224
+ if not _can_check_answer(task):
225
+ return None
226
+
227
+ html = await _require_scraper().fetch_page(source_url)
228
+ if not html:
229
+ return None
230
+
231
+ soup = BeautifulSoup(html, "lxml")
232
+ guid_input = soup.select_one("form[id^='checkform'] input[name='guid']")
233
+ return guid_input.get("value") if guid_input and guid_input.get("value") else None
234
+
235
+
236
+ async def _check_task_answer(task: Dict, answer: str) -> CheckAnswerResponse:
237
+ if not _can_check_answer(task):
238
+ raise HTTPException(status_code=400, detail="This task does not support answer checking")
239
+
240
+ normalized = _normalize_answer(answer)
241
+ if not normalized:
242
+ raise HTTPException(status_code=400, detail="Answer is empty")
243
+
244
+ parsed = urlparse(task["source_url"])
245
+ query = parse_qs(parsed.query)
246
+ project_guid = (query.get("proj") or [None])[0]
247
+ task_guid = await _resolve_task_guid(task)
248
+
249
+ if not project_guid or not task_guid:
250
+ raise HTTPException(status_code=500, detail="Unable to resolve FIPI task metadata")
251
+
252
+ solve_url = f"{parsed.scheme}://{parsed.netloc}{parsed.path.rsplit('/', 1)[0]}/solve.php"
253
+ ssl_context = ssl.create_default_context()
254
+ ssl_context.check_hostname = False
255
+ ssl_context.verify_mode = ssl.CERT_NONE
256
+
257
+ async with httpx.AsyncClient(
258
+ headers=_require_scraper().headers,
259
+ timeout=45.0,
260
+ verify=ssl_context,
261
+ follow_redirects=True,
262
+ ) as client:
263
+ page_response = await client.get(task["source_url"])
264
+ page_response.raise_for_status()
265
+ response = await client.post(
266
+ solve_url,
267
+ data={
268
+ "guid": task_guid,
269
+ "answer": normalized,
270
+ "ajax": "1",
271
+ "proj": project_guid,
272
+ },
273
+ headers={"Referer": task["source_url"]},
274
+ )
275
+ response.raise_for_status()
276
+
277
+ if not response:
278
+ raise HTTPException(status_code=502, detail="FIPI answer check failed")
279
+
280
+ status_code = response.text.strip()
281
+ status_map = {
282
+ "0": ("not_solved", False, "Не решено"),
283
+ "1": ("solved", True, "Решено"),
284
+ "2": ("incorrect", False, "Неверно"),
285
+ "3": ("correct", True, "Верно"),
286
+ }
287
+ if status_code not in status_map:
288
+ raise HTTPException(status_code=502, detail=f"Unexpected FIPI response: {status_code}")
289
+
290
+ status_label, is_correct, message = status_map[status_code]
291
+ return CheckAnswerResponse(
292
+ success=True,
293
+ is_correct=is_correct,
294
+ status_code=status_label,
295
+ status_label=message,
296
+ submitted_answer=answer,
297
+ normalized_answer=normalized,
298
+ message=message,
299
+ )
300
+
301
+
302
+ @app.get("/api/health", response_model=HealthResponse)
303
+ async def health_check() -> HealthResponse:
304
+ services = {
305
+ "api": True,
306
+ "scraper": scraper is not None,
307
+ "supabase": False,
308
+ }
309
+
310
+ if supabase_client:
311
+ try:
312
+ services["supabase"] = await supabase_client.is_available()
313
+ except Exception:
314
+ services["supabase"] = False
315
+
316
+ all_critical_ok = services["api"] and services["scraper"]
317
+ if all_critical_ok and all(services.values()):
318
+ status = "healthy"
319
+ elif all_critical_ok:
320
+ status = "degraded"
321
+ else:
322
+ status = "unhealthy"
323
+
324
+ return HealthResponse(status=status, timestamp=datetime.utcnow(), services=services)
325
+
326
+
327
+ @app.get("/api/tasks", response_model=List[TaskResponse])
328
+ async def get_all_tasks(background_tasks: BackgroundTasks) -> List[TaskResponse]:
329
+ tasks = await _ensure_tasks_available(background_tasks)
330
+ return [TaskResponse(**_serialize_task(task)) for task in tasks]
331
+
332
+
333
+ @app.get("/api/tasks/latest", response_model=List[TaskResponse])
334
+ async def get_latest_tasks(limit: int = 10) -> List[TaskResponse]:
335
+ tasks = await _require_supabase().get_latest_tasks(limit=limit)
336
+ return [TaskResponse(**_serialize_task(task)) for task in tasks]
337
+
338
+
339
+ @app.get("/api/tasks/{task_id}", response_model=TaskResponse)
340
+ async def get_task(task_id: int) -> TaskResponse:
341
+ task = await _require_supabase().get_task_by_id(task_id)
342
+ if not task:
343
+ raise HTTPException(status_code=404, detail="Task not found")
344
+ return TaskResponse(**_serialize_task(task))
345
+
346
+
347
+ @app.post("/api/tasks/{task_id}/check-answer", response_model=CheckAnswerResponse)
348
+ async def check_task_answer(task_id: int, request: CheckAnswerRequest) -> CheckAnswerResponse:
349
+ task = await _require_supabase().get_task_by_id(task_id)
350
+ if not task:
351
+ raise HTTPException(status_code=404, detail="Task not found")
352
+ return await _check_task_answer(task, request.answer)
353
+
354
+
355
+ @app.get("/api/tasks/type/{task_type}", response_model=List[TaskResponse])
356
+ async def get_tasks_by_type(task_type: str) -> List[TaskResponse]:
357
+ tasks = await _require_supabase().get_tasks_by_type(task_type)
358
+ return [TaskResponse(**_serialize_task(task)) for task in tasks]
359
+
360
+
361
+ @app.get("/api/tasks/search", response_model=List[TaskResponse])
362
+ async def search_tasks(q: str) -> List[TaskResponse]:
363
+ tasks = await _require_supabase().search_tasks(q)
364
+ return [TaskResponse(**_serialize_task(task)) for task in tasks]
365
+
366
+
367
+ @app.post("/api/scrape", response_model=ScrapeResponse)
368
+ async def scrape_tasks(request: ScrapeRequest) -> ScrapeResponse:
369
+ client = _require_supabase()
370
+ service = _require_scraper()
371
+
372
+ try:
373
+ tasks_scraped = 0
374
+ tasks_saved = 0
375
+ duplicates_skipped = 0
376
+
377
+ if request.urls:
378
+ for url in request.urls:
379
+ html = await service.fetch_page(url)
380
+ task = service.parse_task_page(html, url) if html else None
381
+ if not task:
382
+ continue
383
+ tasks_scraped += 1
384
+ result = await client.insert_task(task)
385
+ if result:
386
+ tasks_saved += 1
387
+ else:
388
+ duplicates_skipped += 1
389
+ elif request.query:
390
+ tasks = await service.search_tasks(request.query)
391
+ tasks_scraped = len(tasks)
392
+ persisted = await _persist_tasks(tasks)
393
+ tasks_saved = persisted["saved"]
394
+ duplicates_skipped = persisted["duplicates"]
395
+ else:
396
+ tasks = await service.scrape_tasks(subject=request.subject or "russian")
397
+ tasks_scraped = len(tasks)
398
+ persisted = await _persist_tasks(tasks)
399
+ tasks_saved = persisted["saved"]
400
+ duplicates_skipped = persisted["duplicates"]
401
+
402
+ return ScrapeResponse(
403
+ success=True,
404
+ tasks_scraped=tasks_scraped,
405
+ tasks_saved=tasks_saved,
406
+ duplicates_skipped=duplicates_skipped,
407
+ message=(
408
+ f"Processed {tasks_scraped} tasks. "
409
+ f"Saved: {tasks_saved}, duplicates: {duplicates_skipped}"
410
+ ),
411
+ )
412
+ except HTTPException:
413
+ raise
414
+ except Exception as exc: # pragma: no cover - endpoint guard
415
+ logger.error("Scrape error: %s", exc)
416
+ raise HTTPException(status_code=500, detail=f"Scrape error: {exc}")
417
+
418
+
419
+ @app.get("/api/stats", response_model=StatsResponse)
420
+ async def get_stats() -> StatsResponse:
421
+ client = _require_supabase()
422
+ stats = await client.get_stats()
423
+ latest = await client.get_latest_tasks(limit=1)
424
+ last_scrape = latest[0].get("scraped_at") if latest else None
425
+ return StatsResponse(
426
+ total_tasks=stats.get("total", 0),
427
+ by_type=stats.get("by_type", {}),
428
+ last_scrape=last_scrape,
429
+ )
430
+
431
+
432
+ @app.get("/", tags=["root"])
433
+ async def root() -> Dict[str, str]:
434
+ return {
435
+ "message": "AI Scraper FIPI API",
436
+ "version": "1.1.0",
437
+ "docs": "/docs",
438
+ }
439
+
440
+
441
+ @app.exception_handler(Exception)
442
+ async def global_exception_handler(request, exc) -> JSONResponse:
443
+ logger.error("Unhandled exception: %s", exc)
444
+ payload = ErrorResponse(
445
+ error="Internal Server Error",
446
+ detail=str(exc),
447
+ timestamp=datetime.utcnow(),
448
+ )
449
+ return JSONResponse(status_code=500, content=payload.model_dump(mode="json"))
450
+
451
+
452
+ if __name__ == "__main__":
453
+ import uvicorn
454
+
455
+ uvicorn.run(app, host="0.0.0.0", port=8000)