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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FastAPI app 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.1-proof-20260317",
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
+ if task.get("source_kind") == "dynamic_bank" and task.get("task_guid"):
116
+ return True
117
+
118
+ source_url = task.get("source_url", "")
119
+ parsed = urlparse(source_url)
120
+ query = parse_qs(parsed.query)
121
+ project_guid = (query.get("proj") or [None])[0]
122
+ question_id = (query.get("qid") or [None])[0]
123
+
124
+ return parsed.path.endswith("/questions.php") and bool(project_guid and (question_id or task.get("task_guid")))
125
+
126
+
127
+ def _serialize_task(task: Dict) -> Dict:
128
+ payload = dict(task)
129
+ payload["can_check_answer"] = _can_check_answer(task)
130
+ return payload
131
+
132
+
133
+ async def _persist_tasks(tasks: List[Dict]) -> Dict[str, int]:
134
+ client = _require_supabase()
135
+ saved = 0
136
+ duplicates = 0
137
+ for task in tasks:
138
+ result = await client.insert_task(task)
139
+ if result:
140
+ saved += 1
141
+ else:
142
+ duplicates += 1
143
+ return {"saved": saved, "duplicates": duplicates}
144
+
145
+
146
+ async def _collect_tasks(subject: str = "russian", *, include_official_archives: bool = True) -> List[Dict]:
147
+ service = _require_scraper()
148
+ if include_official_archives:
149
+ return await service.scrape_tasks(subject=subject, include_official_archives=True)
150
+ return await service.scrape_dynamic_bank(subject=subject)
151
+
152
+
153
+ async def _refresh_tasks(subject: str = "russian", *, include_official_archives: bool = True) -> Dict[str, int]:
154
+ scraped_tasks = await _collect_tasks(
155
+ subject=subject,
156
+ include_official_archives=include_official_archives,
157
+ )
158
+ persisted = await _persist_tasks(scraped_tasks)
159
+ return {
160
+ "scraped": len(scraped_tasks),
161
+ "saved": persisted["saved"],
162
+ "duplicates": persisted["duplicates"],
163
+ }
164
+
165
+
166
+ def _needs_task_refresh(tasks: List[Dict]) -> bool:
167
+ if not tasks:
168
+ return True
169
+
170
+ dynamic_count = sum(1 for task in tasks if task.get("source_kind") == "dynamic_bank")
171
+ checkable_count = sum(1 for task in tasks if _can_check_answer(task))
172
+ minimum_total = max(10, int(os.getenv("SCRAPER_MIN_READY_TASKS", "40")))
173
+
174
+ if dynamic_count == 0 or checkable_count == 0:
175
+ return True
176
+
177
+ return len(tasks) < minimum_total
178
+
179
+
180
+ def _needs_dynamic_bank_refresh(tasks: List[Dict]) -> bool:
181
+ if not tasks:
182
+ return True
183
+
184
+ dynamic_count = sum(1 for task in tasks if task.get("source_kind") == "dynamic_bank")
185
+ checkable_count = sum(1 for task in tasks if _can_check_answer(task))
186
+ return dynamic_count == 0 or checkable_count == 0
187
+
188
+
189
+ def _is_refresh_running() -> bool:
190
+ return refresh_in_progress
191
+
192
+
193
+ async def _run_refresh(subject: str = "russian", include_official_archives: bool = True) -> None:
194
+ global refresh_in_progress
195
+
196
+ try:
197
+ refresh_in_progress = True
198
+ refreshed = await _refresh_tasks(
199
+ subject=subject,
200
+ include_official_archives=include_official_archives,
201
+ )
202
+ logger.info(
203
+ "Background refresh finished: scraped=%s saved=%s duplicates=%s include_archives=%s",
204
+ refreshed["scraped"],
205
+ refreshed["saved"],
206
+ refreshed["duplicates"],
207
+ include_official_archives,
208
+ )
209
+ except Exception as exc: # pragma: no cover - background guard
210
+ logger.error("Background refresh failed: %s", exc)
211
+ finally:
212
+ refresh_in_progress = False
213
+
214
+
215
+ def _schedule_refresh(
216
+ background_tasks: BackgroundTasks,
217
+ subject: str = "russian",
218
+ *,
219
+ include_official_archives: bool = True,
220
+ ) -> bool:
221
+ global last_auto_refresh_at
222
+
223
+ if _is_refresh_running():
224
+ return False
225
+
226
+ last_auto_refresh_at = datetime.utcnow()
227
+ background_tasks.add_task(_run_refresh, subject, include_official_archives)
228
+ return True
229
+
230
+
231
+ async def _ensure_tasks_available(background_tasks: BackgroundTasks, subject: str = "russian") -> List[Dict]:
232
+ global last_auto_refresh_at
233
+
234
+ client = _require_supabase()
235
+ existing = await client.get_all_tasks()
236
+ if existing and not _needs_task_refresh(existing):
237
+ return existing
238
+
239
+ if not existing:
240
+ logger.info("Tasks table is empty, running initial dynamic scrape")
241
+ last_auto_refresh_at = datetime.utcnow()
242
+ await _refresh_tasks(subject=subject, include_official_archives=False)
243
+ refreshed = await client.get_all_tasks()
244
+ if refreshed and _schedule_refresh(background_tasks, subject, include_official_archives=True):
245
+ logger.info("Scheduled full refresh after initial dynamic scrape")
246
+ return refreshed or existing
247
+
248
+ if _needs_dynamic_bank_refresh(existing):
249
+ if _is_refresh_running():
250
+ logger.info("Dynamic bank refresh is already running, returning existing tasks")
251
+ return existing
252
+
253
+ logger.info("Tasks are missing dynamic/checkable entries, running targeted dynamic refresh")
254
+ refreshed = await _refresh_tasks(subject=subject, include_official_archives=False)
255
+ logger.info(
256
+ "Targeted dynamic refresh finished: scraped=%s saved=%s duplicates=%s",
257
+ refreshed["scraped"],
258
+ refreshed["saved"],
259
+ refreshed["duplicates"],
260
+ )
261
+
262
+ updated = await client.get_all_tasks()
263
+ if updated:
264
+ if len(updated) < max(10, int(os.getenv("SCRAPER_MIN_READY_TASKS", "40"))):
265
+ if _schedule_refresh(background_tasks, subject, include_official_archives=True):
266
+ logger.info("Scheduled full refresh after targeted dynamic refresh")
267
+ return updated
268
+
269
+ return existing
270
+
271
+ cooldown_minutes = max(1, int(os.getenv("SCRAPER_AUTO_REFRESH_COOLDOWN_MINUTES", "30")))
272
+ if last_auto_refresh_at and (datetime.utcnow() - last_auto_refresh_at).total_seconds() < cooldown_minutes * 60:
273
+ logger.info("Skipping auto refresh because cooldown is active")
274
+ return existing
275
+
276
+ if _schedule_refresh(background_tasks, subject, include_official_archives=True):
277
+ logger.info("Existing tasks are stale or incomplete, scheduled background refresh")
278
+ else:
279
+ logger.info("Refresh is already running, returning existing tasks")
280
+
281
+ return existing
282
+
283
+
284
+ def _normalize_answer(answer: str) -> str:
285
+ return re.sub(r"\s+", "", answer.strip()).upper()
286
+
287
+
288
+ async def _resolve_task_guid(task: Dict) -> Optional[str]:
289
+ if task.get("task_guid"):
290
+ return task["task_guid"]
291
+
292
+ source_url = task.get("source_url", "")
293
+ if not _can_check_answer(task):
294
+ return None
295
+
296
+ html = await _require_scraper().fetch_page(source_url)
297
+ if not html:
298
+ return None
299
+
300
+ soup = BeautifulSoup(html, "lxml")
301
+ guid_input = soup.select_one("form[id^='checkform'] input[name='guid']")
302
+ return guid_input.get("value") if guid_input and guid_input.get("value") else None
303
+
304
+
305
+ async def _check_task_answer(task: Dict, answer: str) -> CheckAnswerResponse:
306
+ if not _can_check_answer(task):
307
+ raise HTTPException(status_code=400, detail="This task does not support answer checking")
308
+
309
+ normalized = _normalize_answer(answer)
310
+ if not normalized:
311
+ raise HTTPException(status_code=400, detail="Answer is empty")
312
+
313
+ parsed = urlparse(task["source_url"])
314
+ query = parse_qs(parsed.query)
315
+ project_guid = (query.get("proj") or [None])[0]
316
+ task_guid = await _resolve_task_guid(task)
317
+
318
+ if not project_guid or not task_guid:
319
+ raise HTTPException(status_code=500, detail="Unable to resolve FIPI task metadata")
320
+
321
+ solve_url = f"{parsed.scheme}://{parsed.netloc}{parsed.path.rsplit('/', 1)[0]}/solve.php"
322
+ ssl_context = ssl.create_default_context()
323
+ ssl_context.check_hostname = False
324
+ ssl_context.verify_mode = ssl.CERT_NONE
325
+
326
+ async with httpx.AsyncClient(
327
+ headers=_require_scraper().headers,
328
+ timeout=45.0,
329
+ verify=ssl_context,
330
+ follow_redirects=True,
331
+ ) as client:
332
+ page_response = await client.get(task["source_url"])
333
+ page_response.raise_for_status()
334
+ response = await client.post(
335
+ solve_url,
336
+ data={
337
+ "guid": task_guid,
338
+ "answer": normalized,
339
+ "ajax": "1",
340
+ "proj": project_guid,
341
+ },
342
+ headers={"Referer": task["source_url"]},
343
+ )
344
+ response.raise_for_status()
345
+
346
+ if not response:
347
+ raise HTTPException(status_code=502, detail="FIPI answer check failed")
348
+
349
+ status_code = response.text.strip()
350
+ status_map = {
351
+ "0": ("not_solved", False, "Не решено"),
352
+ "1": ("solved", True, "Решено"),
353
+ "2": ("incorrect", False, "Неверно"),
354
+ "3": ("correct", True, "Верно"),
355
+ }
356
+ if status_code not in status_map:
357
+ raise HTTPException(status_code=502, detail=f"Unexpected FIPI response: {status_code}")
358
+
359
+ status_label, is_correct, message = status_map[status_code]
360
+ return CheckAnswerResponse(
361
+ success=True,
362
+ is_correct=is_correct,
363
+ status_code=status_label,
364
+ status_label=message,
365
+ submitted_answer=answer,
366
+ normalized_answer=normalized,
367
+ message=message,
368
+ )
369
+
370
+
371
+ @app.get("/api/health", response_model=HealthResponse)
372
+ async def health_check() -> HealthResponse:
373
+ services = {
374
+ "api": True,
375
+ "scraper": scraper is not None,
376
+ "supabase": False,
377
+ }
378
+
379
+ if supabase_client:
380
+ try:
381
+ services["supabase"] = await supabase_client.is_available()
382
+ except Exception:
383
+ services["supabase"] = False
384
+
385
+ all_critical_ok = services["api"] and services["scraper"]
386
+ if all_critical_ok and all(services.values()):
387
+ status = "healthy"
388
+ elif all_critical_ok:
389
+ status = "degraded"
390
+ else:
391
+ status = "unhealthy"
392
+
393
+ return HealthResponse(status=status, timestamp=datetime.utcnow(), services=services)
394
+
395
+
396
+ @app.get("/api/tasks", response_model=List[TaskResponse])
397
+ async def get_all_tasks(background_tasks: BackgroundTasks) -> List[TaskResponse]:
398
+ tasks = await _ensure_tasks_available(background_tasks)
399
+ return [TaskResponse(**_serialize_task(task)) for task in tasks]
400
+
401
+
402
+ @app.get("/api/tasks/latest", response_model=List[TaskResponse])
403
+ async def get_latest_tasks(limit: int = 10) -> List[TaskResponse]:
404
+ tasks = await _require_supabase().get_latest_tasks(limit=limit)
405
+ return [TaskResponse(**_serialize_task(task)) for task in tasks]
406
+
407
+
408
+ @app.get("/api/tasks/{task_id}", response_model=TaskResponse)
409
+ async def get_task(task_id: int) -> TaskResponse:
410
+ task = await _require_supabase().get_task_by_id(task_id)
411
+ if not task:
412
+ raise HTTPException(status_code=404, detail="Task not found")
413
+ return TaskResponse(**_serialize_task(task))
414
+
415
+
416
+ @app.post("/api/tasks/{task_id}/check-answer", response_model=CheckAnswerResponse)
417
+ async def check_task_answer(task_id: int, request: CheckAnswerRequest) -> CheckAnswerResponse:
418
+ task = await _require_supabase().get_task_by_id(task_id)
419
+ if not task:
420
+ raise HTTPException(status_code=404, detail="Task not found")
421
+ return await _check_task_answer(task, request.answer)
422
+
423
+
424
+ @app.get("/api/tasks/type/{task_type}", response_model=List[TaskResponse])
425
+ async def get_tasks_by_type(task_type: str) -> List[TaskResponse]:
426
+ tasks = await _require_supabase().get_tasks_by_type(task_type)
427
+ return [TaskResponse(**_serialize_task(task)) for task in tasks]
428
+
429
+
430
+ @app.get("/api/tasks/search", response_model=List[TaskResponse])
431
+ async def search_tasks(q: str) -> List[TaskResponse]:
432
+ tasks = await _require_supabase().search_tasks(q)
433
+ return [TaskResponse(**_serialize_task(task)) for task in tasks]
434
+
435
+
436
+ @app.post("/api/scrape", response_model=ScrapeResponse)
437
+ async def scrape_tasks(request: ScrapeRequest) -> ScrapeResponse:
438
+ client = _require_supabase()
439
+ service = _require_scraper()
440
+
441
+ try:
442
+ tasks_scraped = 0
443
+ tasks_saved = 0
444
+ duplicates_skipped = 0
445
+
446
+ if request.urls:
447
+ for url in request.urls:
448
+ html = await service.fetch_page(url)
449
+ task = service.parse_task_page(html, url) if html else None
450
+ if not task:
451
+ continue
452
+ tasks_scraped += 1
453
+ result = await client.insert_task(task)
454
+ if result:
455
+ tasks_saved += 1
456
+ else:
457
+ duplicates_skipped += 1
458
+ elif request.query:
459
+ tasks = await service.search_tasks(request.query)
460
+ tasks_scraped = len(tasks)
461
+ persisted = await _persist_tasks(tasks)
462
+ tasks_saved = persisted["saved"]
463
+ duplicates_skipped = persisted["duplicates"]
464
+ else:
465
+ if request.full_refresh:
466
+ tasks = await service.scrape_tasks(
467
+ subject=request.subject or "russian",
468
+ include_official_archives=True,
469
+ )
470
+ else:
471
+ tasks = await service.scrape_dynamic_bank(subject=request.subject or "russian")
472
+ tasks_scraped = len(tasks)
473
+ persisted = await _persist_tasks(tasks)
474
+ tasks_saved = persisted["saved"]
475
+ duplicates_skipped = persisted["duplicates"]
476
+
477
+ return ScrapeResponse(
478
+ success=True,
479
+ tasks_scraped=tasks_scraped,
480
+ tasks_saved=tasks_saved,
481
+ duplicates_skipped=duplicates_skipped,
482
+ message=(
483
+ f"Processed {tasks_scraped} tasks. "
484
+ f"Saved: {tasks_saved}, duplicates: {duplicates_skipped}"
485
+ ),
486
+ )
487
+ except HTTPException:
488
+ raise
489
+ except Exception as exc: # pragma: no cover - endpoint guard
490
+ logger.error("Scrape error: %s", exc)
491
+ raise HTTPException(status_code=500, detail=f"Scrape error: {exc}")
492
+
493
+
494
+ @app.get("/api/stats", response_model=StatsResponse)
495
+ async def get_stats() -> StatsResponse:
496
+ client = _require_supabase()
497
+ stats = await client.get_stats()
498
+ latest = await client.get_latest_tasks(limit=1)
499
+ last_scrape = latest[0].get("scraped_at") if latest else None
500
+ return StatsResponse(
501
+ total_tasks=stats.get("total", 0),
502
+ by_type=stats.get("by_type", {}),
503
+ last_scrape=last_scrape,
504
+ )
505
+
506
+
507
+ @app.get("/", tags=["root"])
508
+ async def root() -> Dict[str, str]:
509
+ return {
510
+ "message": "AI Scraper FIPI API proof-20260317",
511
+ "version": "1.1.1-proof-20260317",
512
+ "docs": "/docs",
513
+ }
514
+
515
+
516
+ @app.exception_handler(Exception)
517
+ async def global_exception_handler(request, exc) -> JSONResponse:
518
+ logger.error("Unhandled exception: %s", exc)
519
+ payload = ErrorResponse(
520
+ error="Internal Server Error",
521
+ detail=str(exc),
522
+ timestamp=datetime.utcnow(),
523
+ )
524
+ return JSONResponse(status_code=500, content=payload.model_dump(mode="json"))
525
+
526
+
527
+ if __name__ == "__main__":
528
+ import uvicorn
529
+
530
+ uvicorn.run(app, host="0.0.0.0", port=8000)