127 行
4.1 KiB
Python
127 行
4.1 KiB
Python
"""Hydro MongoDB 直连读题/读训练(不依赖网页解析或 API 权限)。
|
||
|
||
文档集合 schema(docType=10 题目):
|
||
_id: ObjectId
|
||
pid: "P57" # 学生说的显示题号
|
||
reference.pid: 442 # URL /p/442 用的数字 ID
|
||
title: "练11.4..."
|
||
content.zh: "<h2>说明</h2>..." # 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 _html_to_md(s: str) -> str:
|
||
"""粗转 HTML → Markdown,保留标题/代码块/样例结构。"""
|
||
# katex: 取 <annotation> 里的 TeX
|
||
s = re.sub(r'<annotation[^>]*>(.*?)</annotation>', r'$\1$', s)
|
||
s = re.sub(r'<span class="katex[^"]*">.*?</span>', '', s) # 去掉渲染后的 katex-html
|
||
# 代码块
|
||
s = re.sub(r'<pre><code[^>]*>(.*?)</code></pre>', lambda m: '\n```\n' + m.group(1).strip() + '\n```\n', s, flags=re.S)
|
||
s = re.sub(r'<code[^>]*>(.*?)</code>', r'`\1`', s, flags=re.S)
|
||
# 标题
|
||
for i in range(6, 0, -1):
|
||
s = re.sub(rf'<h{i}[^>]*>(.*?)</h{i}>', r'\n' + '#' * i + r' \1\n', s, flags=re.S)
|
||
# 段落/列表
|
||
s = re.sub(r'<br\s*/?>', '\n', s)
|
||
s = re.sub(r'</p>', '\n\n', s)
|
||
s = re.sub(r'<li[^>]*>', '- ', s)
|
||
s = re.sub(r'</li>', '\n', s)
|
||
# 去剩余标签
|
||
s = re.sub(r'<[^>]+>', '', s)
|
||
# 清理空行
|
||
s = re.sub(r'\n{3,}', '\n\n', s)
|
||
return s.strip()
|
||
|
||
|
||
def _parse_content(raw) -> str:
|
||
"""content 可能是 dict 或 JSON 字符串,取 zh 字段再转 markdown。"""
|
||
if isinstance(raw, str):
|
||
try:
|
||
raw = json.loads(raw)
|
||
except Exception:
|
||
return _html_to_md(raw)
|
||
if isinstance(raw, dict):
|
||
raw = raw.get("zh") or raw.get("en") or ""
|
||
return _html_to_md(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}
|