"""Hydro MongoDB 直连读题/读训练(不依赖网页解析或 API 权限)。 文档集合 schema(docType=10 题目): _id: ObjectId pid: "P57" # 学生说的显示题号 reference.pid: 442 # URL /p/442 用的数字 ID title: "练11.4..." content.zh: "

说明

..." # HTML 题面 tag: [...] 训练(docType=40): title: "1 Scanner 训练" dag: [{"title": "...", "pids": [17, 7, 9, ...]}] # pids 是 reference.pid 数字 """ from __future__ import annotations import logging, re, json from typing import Any import pymongo from app.core.config import settings logger = logging.getLogger("fluent.hydro_db") _client: pymongo.MongoClient | None = None _db = None def _get_db(): global _client, _db if _db is None: _client = pymongo.MongoClient(settings.mongo_uri, serverSelectionTimeoutMS=3000) _db = _client.get_database() return _db def _strip_html(s: str) -> str: s = re.sub(r']*>(.*?)', r'$\1$', s) s = re.sub(r'', '\n', s) s = re.sub(r'', '\n', s) s = re.sub(r']*>', '- ', s) s = re.sub(r'<[^>]+>', '', s) return re.sub(r'\n{3,}', '\n\n', s).strip() def _parse_content(raw) -> str: """content 可能是 dict 或 JSON 字符串,取 zh 字段再剥 HTML。""" if isinstance(raw, str): try: raw = json.loads(raw) except Exception: return _strip_html(raw) if isinstance(raw, dict): raw = raw.get("zh") or raw.get("en") or "" return _strip_html(str(raw)) def get_problem(pid_input: str) -> dict | None: """按显示题号(P57)或数字 ID(442)查题目。""" db = _get_db() q: dict[str, Any] = {"docType": 10} pid = pid_input.strip().upper().lstrip("P") if pid.isdigit(): q["$or"] = [ {"pid": f"P{pid}"}, {"sort": f"P{pid.zfill(6)}"}, {"reference.pid": int(pid)}, ] else: q["pid"] = f"P{pid}" doc = db.document.find_one(q) if not doc: return None ref = doc.get("reference") or {} return { "pid": doc.get("pid", ""), "title": doc.get("title", ""), "numeric_id": ref.get("pid", 0), "content": _parse_content(doc.get("content")), } def list_trainings() -> list[dict]: db = _get_db() out = [] for t in db.document.find({"docType": 40}, {"title": 1, "description": 1, "domainId": 1}): out.append({"id": str(t["_id"]), "title": t.get("title", ""), "domainId": t.get("domainId", "")}) return out def find_training(keyword: str) -> list[dict]: kw = keyword.strip().lower() return [t for t in list_trainings() if kw in t["title"].lower()] def get_training_problems(training_id: str) -> dict: from bson import ObjectId db = _get_db() doc = db.document.find_one({"_id": ObjectId(training_id), "docType": 40}) if not doc: return {} domain = doc.get("domainId", "") sections = [] for sec in doc.get("dag") or []: probs = [] for did in sec.get("pids") or []: p = db.document.find_one( {"docType": 10, "docId": did, "domainId": domain}, {"pid": 1, "title": 1}, ) if p: probs.append({"pid": p.get("pid", ""), "title": p.get("title", "")}) sections.append({"title": sec.get("title", ""), "problems": probs}) return {"title": doc.get("title", ""), "sections": sections}