db.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. # -*- coding: utf-8 -*-
  2. """mode_workflow · MySQL 持久化(DB 为唯一事实源)
  3. ================================================================================
  4. 读 .env 的 MYSQL_* 连接 MySQL。四张表:
  5. search_process —— 每行一个 (query, 帖子):工序方向的搜索 + llm 评估结果
  6. search_tools —— 同结构,工具方向的搜索结果(方向由表区分,不再用 mode_type 列)
  7. mode_process —— 每行一个解构出的工序(steps 等嵌套结构存 JSON 列)
  8. mode_tools —— 每行一个解构出的工具
  9. 与旧 fixed_query_eval/db.py 的关键差异:本系统 DB 是主存储,写入失败直接 raise,
  10. 不做"失败不阻断"。读侧保留防御(返回空/None)。
  11. 用法:
  12. python db.py init # 建表(幂等)
  13. python db.py check # 打印四表行数
  14. python db.py clear # 清空四表数据(TRUNCATE)
  15. """
  16. import json
  17. import os
  18. import sys
  19. from datetime import datetime
  20. from pathlib import Path
  21. PROJECT_ROOT = Path(__file__).resolve().parents[2]
  22. sys.path.insert(0, str(PROJECT_ROOT))
  23. from dotenv import load_dotenv
  24. load_dotenv()
  25. import pymysql
  26. from pymysql.cursors import DictCursor
  27. def _conn():
  28. if not os.getenv("MYSQL_HOST"):
  29. raise RuntimeError("缺 MYSQL_HOST:检查 .env 的 MYSQL_* 配置")
  30. return pymysql.connect(
  31. host=os.getenv("MYSQL_HOST"),
  32. port=int(os.getenv("MYSQL_PORT", 3306)),
  33. user=os.getenv("MYSQL_USER"),
  34. password=os.getenv("MYSQL_PASSWORD"),
  35. database=os.getenv("MYSQL_DATABASE"),
  36. charset="utf8mb4", cursorclass=DictCursor,
  37. autocommit=True, connect_timeout=10,
  38. )
  39. # ── DDL ──────────────────────────────────────────────────────────────────────
  40. SEARCH_TABLES = {"process": "search_process", "tools": "search_tools"}
  41. MODE_TABLES = {"process": "mode_process", "tools": "mode_tools"}
  42. def _search_table(mode_or_table):
  43. """mode(process/tools)或表名 → 合法搜索表名(白名单,防 SQL 注入)。"""
  44. t = SEARCH_TABLES.get(mode_or_table, mode_or_table)
  45. if t not in SEARCH_TABLES.values():
  46. raise ValueError(f"未知搜索表/模式: {mode_or_table!r}")
  47. return t
  48. def _mode_table(mode_or_table):
  49. """mode(process/tools)或表名 → 合法解构表名(白名单,防 SQL 注入)。"""
  50. t = MODE_TABLES.get(mode_or_table, mode_or_table)
  51. if t not in MODE_TABLES.values():
  52. raise ValueError(f"未知解构表/模式: {mode_or_table!r}")
  53. return t
  54. def _ddl_search(table, direction):
  55. return f"""
  56. CREATE TABLE IF NOT EXISTS {table} (
  57. id BIGINT AUTO_INCREMENT PRIMARY KEY,
  58. query_id VARCHAR(32) NOT NULL COMMENT 'q0000',
  59. query_text VARCHAR(512) NULL,
  60. case_id VARCHAR(128) NOT NULL COMMENT 'platform_channelContentId',
  61. platform VARCHAR(32) NULL,
  62. channel_content_id VARCHAR(128) NULL,
  63. title VARCHAR(512) NULL,
  64. url VARCHAR(1024) NULL,
  65. content_type VARCHAR(32) NULL,
  66. body LONGTEXT NULL,
  67. images JSON NULL,
  68. videos JSON NULL,
  69. like_count INT NULL,
  70. publish_time VARCHAR(64) NULL,
  71. quality_score FLOAT NULL COMMENT 'post._quality_score',
  72. quality_grade VARCHAR(8) NULL,
  73. found_by JSON NULL COMMENT '命中的措辞数组',
  74. knowledge_type JSON NULL COMMENT '["能力","工序","工具"] 子集',
  75. overall_score FLOAT NULL COMMENT '(相关均值+质量均值)/2',
  76. llm_evaluation JSON NULL COMMENT '评估全量 blob',
  77. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  78. updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  79. UNIQUE KEY uk_qid_case (query_id, case_id),
  80. KEY idx_platform (platform)
  81. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='搜索+评估结果({direction})';
  82. """
  83. DDL_PROCESS = """
  84. CREATE TABLE IF NOT EXISTS mode_process (
  85. id BIGINT AUTO_INCREMENT PRIMARY KEY,
  86. query_id VARCHAR(32) NOT NULL,
  87. case_id VARCHAR(128) NOT NULL,
  88. platform VARCHAR(32) NULL,
  89. post_title VARCHAR(512) NULL,
  90. source JSON NULL COMMENT '解构返回的 source 块',
  91. procedure_id VARCHAR(16) NULL COMMENT 'p1,p2…',
  92. name VARCHAR(255) NULL,
  93. purpose TEXT NULL,
  94. category VARCHAR(32) NULL COMMENT '产物创造/资产建设/自动化/分析/学习',
  95. declarations JSON NULL,
  96. type_registry JSON NULL,
  97. steps JSON NULL COMMENT '步骤数组全量',
  98. step_count INT NULL,
  99. tools_used JSON NULL COMMENT '从 steps[].via 去重提取',
  100. model VARCHAR(64) NULL,
  101. version VARCHAR(32) NULL COMMENT 'v_MMDDHHMM,保留历史;link_* 为跨 query 复制(cost=0)',
  102. cost_usd DECIMAL(10,6) NULL COMMENT '本次解构调用成本(同版本各行相同,聚合需按 case+version 去重)',
  103. duration_s FLOAT NULL,
  104. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  105. KEY idx_case_ver (case_id, version),
  106. KEY idx_qid (query_id)
  107. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='工序解构结果(每行一个工序)';
  108. """
  109. DDL_TOOLS = """
  110. CREATE TABLE IF NOT EXISTS mode_tools (
  111. id BIGINT AUTO_INCREMENT PRIMARY KEY,
  112. query_id VARCHAR(32) NOT NULL,
  113. case_id VARCHAR(128) NOT NULL,
  114. platform VARCHAR(32) NULL,
  115. post_title VARCHAR(512) NULL,
  116. tool_name VARCHAR(255) NULL,
  117. substance_scope JSON NULL COMMENT '实质作用域(数组)',
  118. form_scope JSON NULL COMMENT '形式作用域(数组或null)',
  119. creation_layer VARCHAR(32) NULL COMMENT '制作层/创作层',
  120. source_link VARCHAR(1024) NULL,
  121. input_desc TEXT NULL,
  122. output_desc TEXT NULL,
  123. usage_json JSON NULL,
  124. cases_json JSON NULL,
  125. defects_json JSON NULL,
  126. updated_time VARCHAR(64) NULL COMMENT '工具最新更新时间',
  127. model VARCHAR(64) NULL,
  128. version VARCHAR(32) NULL COMMENT 'v_MMDDHHMM;link_* 为跨 query 复制(cost=0)',
  129. cost_usd DECIMAL(10,6) NULL COMMENT '同 mode_process,聚合按 case+version 去重',
  130. duration_s FLOAT NULL,
  131. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  132. KEY idx_case_ver (case_id, version),
  133. KEY idx_qid (query_id),
  134. KEY idx_tool_name (tool_name)
  135. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='工具解构结果(每行一个工具)';
  136. """
  137. def init_tables():
  138. conn = _conn()
  139. try:
  140. with conn.cursor() as cur:
  141. cur.execute(_ddl_search("search_process", "工序方向"))
  142. cur.execute(_ddl_search("search_tools", "工具方向"))
  143. cur.execute(DDL_PROCESS)
  144. cur.execute(DDL_TOOLS)
  145. # 历史库迁移:version 由 VARCHAR(16) 放宽到 32,容纳 link_v_mopN_* 复制版本。
  146. # MODIFY 幂等(已是 32 则 MySQL 元数据无操作),建表后表必存在,可安全执行。
  147. for t in ("mode_process", "mode_tools"):
  148. cur.execute(f"ALTER TABLE {t} MODIFY COLUMN version VARCHAR(32) NULL")
  149. print("✅ 建表完成:search_process, search_tools, mode_process, mode_tools")
  150. finally:
  151. conn.close()
  152. def clear_tables():
  153. """清空四张表的数据(TRUNCATE,表结构保留)。"""
  154. conn = _conn()
  155. try:
  156. with conn.cursor() as cur:
  157. for t in ("search_process", "search_tools", "mode_process", "mode_tools"):
  158. cur.execute(f"TRUNCATE TABLE {t}")
  159. print(f"🧹 已清空 {t}")
  160. finally:
  161. conn.close()
  162. # ── 工具函数 ──────────────────────────────────────────────────────────────────
  163. def _loads(v, default=None):
  164. """pymysql 的 JSON 列可能返回字符串,统一解析。"""
  165. if v is None:
  166. return default
  167. if isinstance(v, (list, dict)):
  168. return v
  169. try:
  170. return json.loads(v)
  171. except Exception:
  172. return default
  173. def _j(v):
  174. """写入 JSON 列:None 保持 NULL,其余 dumps。"""
  175. return None if v is None else json.dumps(v, ensure_ascii=False)
  176. def _collect_scores(node):
  177. """递归收集嵌套评估里所有「得分」。LLM 直出的得分多为字符串("1"/"4"),
  178. 个别为数字(如 时效性 10),统一按 float 解析;非数值(如 "N/A")跳过不计入。"""
  179. out = []
  180. if isinstance(node, dict):
  181. for k, v in node.items():
  182. if k == "得分":
  183. try:
  184. out.append(float(v))
  185. except (TypeError, ValueError):
  186. pass
  187. else:
  188. out.extend(_collect_scores(v))
  189. elif isinstance(node, list):
  190. for v in node:
  191. out.extend(_collect_scores(v))
  192. return out
  193. def overall_score(e):
  194. """综合分 = (相关性各项均值 + 质量各项均值) / 可得部分数。算不出返回 None。"""
  195. parts = []
  196. for key in ("相关性", "质量"):
  197. scores = _collect_scores((e or {}).get(key))
  198. if scores:
  199. parts.append(sum(scores) / len(scores))
  200. return round(sum(parts) / len(parts), 2) if parts else None
  201. def _recency_hard(date_str):
  202. """硬时效(同 mode_procedure/server.py:_recency_hard):半年内=3 / 两年内=2 / 更早=1。
  203. publish_time 头 10 字符按 YYYY-MM-DD 解析,失败返回 None(不参与判定)。"""
  204. try:
  205. d = datetime.strptime(str(date_str or "")[:10], "%Y-%m-%d")
  206. except (ValueError, TypeError):
  207. return None
  208. days = (datetime.now() - d).days
  209. if days <= 180:
  210. return 3
  211. if days <= 730:
  212. return 2
  213. return 1
  214. def is_adopted(overall, evaluation, publish_time):
  215. """采纳/命中判定,口径对齐 mode_procedure 的 decision=="report":
  216. 制作相关性<4、发布超两年、综合分<6 —— 任一命中即不采纳;指标缺失不参与判定。"""
  217. rel = None
  218. v = ((evaluation or {}).get("相关性") or {}).get("和内容制作知识相关")
  219. if isinstance(v, dict):
  220. v = v.get("得分")
  221. try:
  222. rel = float(v) if v is not None else None
  223. except (TypeError, ValueError):
  224. rel = None
  225. if rel is not None and rel < 4:
  226. return False
  227. rh = _recency_hard(publish_time)
  228. if rh is not None and rh < 2:
  229. return False
  230. if overall is not None and float(overall) < 6:
  231. return False
  232. return True
  233. # ── search_process / search_tools ────────────────────────────────────────────
  234. def upsert_search_posts(query_id, query_text, results, table="search_process"):
  235. """一组搜索结果写入指定搜索表(按 (query_id, case_id) upsert)。返回写入条数。
  236. table:search_process(工序方向) / search_tools(工具方向)。"""
  237. table = _search_table(table)
  238. if not results:
  239. return 0
  240. rows = []
  241. for r in results:
  242. post = r.get("post") or {}
  243. e = r.get("llm_evaluation") or {}
  244. rows.append((
  245. query_id, query_text, r.get("case_id"), r.get("platform"),
  246. r.get("channel_content_id"),
  247. (post.get("title") or post.get("desc") or "")[:500],
  248. r.get("source_url"), post.get("content_type"),
  249. post.get("body_text") or post.get("desc") or "",
  250. _j(post.get("images") or []), _j(post.get("videos") or []),
  251. post.get("like_count"),
  252. str(post.get("publish_time") or post.get("publish_timestamp") or "")[:64],
  253. post.get("_quality_score"), post.get("_quality_grade"),
  254. _j(r.get("found_by_queries") or []),
  255. _j(e.get("知识类型") or []),
  256. overall_score(e),
  257. _j(e),
  258. ))
  259. sql = f"""
  260. INSERT INTO {table}
  261. (query_id, query_text, case_id, platform, channel_content_id, title, url,
  262. content_type, body, images, videos, like_count, publish_time,
  263. quality_score, quality_grade, found_by, knowledge_type,
  264. overall_score, llm_evaluation)
  265. VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
  266. ON DUPLICATE KEY UPDATE
  267. query_text=VALUES(query_text), platform=VALUES(platform),
  268. channel_content_id=VALUES(channel_content_id), title=VALUES(title), url=VALUES(url),
  269. content_type=VALUES(content_type), body=VALUES(body), images=VALUES(images),
  270. videos=VALUES(videos), like_count=VALUES(like_count), publish_time=VALUES(publish_time),
  271. quality_score=VALUES(quality_score), quality_grade=VALUES(quality_grade),
  272. found_by=VALUES(found_by), knowledge_type=VALUES(knowledge_type),
  273. overall_score=VALUES(overall_score), llm_evaluation=VALUES(llm_evaluation);
  274. """
  275. conn = _conn()
  276. try:
  277. with conn.cursor() as cur:
  278. cur.executemany(sql, rows)
  279. return len(rows)
  280. finally:
  281. conn.close()
  282. def fetch_queries(mode="process"):
  283. """某方向搜索表的 query 列表 + 帖子数 + 采纳/命中数 + 解构进度。"""
  284. table = _search_table(mode)
  285. conn = _conn()
  286. try:
  287. with conn.cursor() as cur:
  288. cur.execute(f"""SELECT query_id, MAX(query_text) AS query_text,
  289. COUNT(*) AS post_count
  290. FROM {table} GROUP BY query_id ORDER BY query_id""")
  291. queries = cur.fetchall()
  292. cur.execute(f"""SELECT query_id, overall_score, llm_evaluation, publish_time
  293. FROM {table}""")
  294. hits = {}
  295. for r in cur.fetchall():
  296. if is_adopted(r["overall_score"], _loads(r["llm_evaluation"]), r["publish_time"]):
  297. hits[r["query_id"]] = hits.get(r["query_id"], 0) + 1
  298. cur.execute("SELECT query_id, COUNT(DISTINCT case_id) AS n FROM mode_process GROUP BY query_id")
  299. np = {r["query_id"]: r["n"] for r in cur.fetchall()}
  300. cur.execute("SELECT query_id, COUNT(DISTINCT case_id) AS n FROM mode_tools GROUP BY query_id")
  301. nt = {r["query_id"]: r["n"] for r in cur.fetchall()}
  302. finally:
  303. conn.close()
  304. for q in queries:
  305. q["hit_count"] = hits.get(q["query_id"], 0)
  306. q["process_done"] = np.get(q["query_id"], 0)
  307. q["tools_done"] = nt.get(q["query_id"], 0)
  308. return queries
  309. def fetch_posts(query_id, mode="process"):
  310. """某方向搜索表里某 query 的全部帖子(JSON 列已解析),带 has_process/has_tools 标记。"""
  311. table = _search_table(mode)
  312. conn = _conn()
  313. try:
  314. with conn.cursor() as cur:
  315. cur.execute(f"""SELECT * FROM {table} WHERE query_id=%s
  316. ORDER BY overall_score DESC, id""", (query_id,))
  317. rows = cur.fetchall()
  318. cur.execute("SELECT DISTINCT case_id FROM mode_process WHERE query_id=%s", (query_id,))
  319. hp = {r["case_id"] for r in cur.fetchall()}
  320. cur.execute("SELECT DISTINCT case_id FROM mode_tools WHERE query_id=%s", (query_id,))
  321. ht = {r["case_id"] for r in cur.fetchall()}
  322. finally:
  323. conn.close()
  324. for r in rows:
  325. for col in ("images", "videos", "found_by", "knowledge_type", "llm_evaluation"):
  326. r[col] = _loads(r[col])
  327. r["adopted"] = is_adopted(r["overall_score"], r["llm_evaluation"], r["publish_time"])
  328. r["has_process"] = r["case_id"] in hp
  329. r["has_tools"] = r["case_id"] in ht
  330. r.pop("created_at", None); r.pop("updated_at", None)
  331. return rows
  332. def fetch_post(query_id, case_id, table="search_process"):
  333. """指定搜索表的单帖完整行(给 pipeline 脚本重建 source 用)。无则 None。"""
  334. table = _search_table(table)
  335. conn = _conn()
  336. try:
  337. with conn.cursor() as cur:
  338. cur.execute(f"SELECT * FROM {table} WHERE query_id=%s AND case_id=%s",
  339. (query_id, case_id))
  340. row = cur.fetchone()
  341. finally:
  342. conn.close()
  343. if not row:
  344. return None
  345. for col in ("images", "videos", "found_by", "knowledge_type", "llm_evaluation"):
  346. row[col] = _loads(row[col])
  347. return row
  348. # ── mode_process ─────────────────────────────────────────────────────────────
  349. def replace_process(query_id, case_id, platform, post_title, payload,
  350. model, version, cost_usd, duration_s):
  351. """写入一帖某版本的工序解构结果(payload = {source, procedures})。
  352. 删 (case_id, version) 旧行再插,同版本重跑幂等、跨版本保留历史。返回工序条数。"""
  353. source = payload.get("source")
  354. procedures = payload.get("procedures") or []
  355. conn = _conn()
  356. try:
  357. with conn.cursor() as cur:
  358. cur.execute("DELETE FROM mode_process WHERE case_id=%s AND version=%s",
  359. (case_id, version))
  360. if procedures:
  361. rows = []
  362. for p in procedures:
  363. steps = p.get("steps") or []
  364. vias = []
  365. for s in steps:
  366. v = s.get("via")
  367. if v and v not in vias:
  368. vias.append(v)
  369. rows.append((
  370. query_id, case_id, platform, (post_title or "")[:500],
  371. _j(source), p.get("id"), (p.get("name") or "")[:250],
  372. p.get("purpose"), p.get("category"),
  373. _j(p.get("declarations")), _j(p.get("type_registry")),
  374. _j(steps), len(steps), _j(vias),
  375. model, version, cost_usd, duration_s,
  376. ))
  377. cur.executemany("""
  378. INSERT INTO mode_process
  379. (query_id, case_id, platform, post_title, source, procedure_id, name,
  380. purpose, category, declarations, type_registry, steps, step_count,
  381. tools_used, model, version, cost_usd, duration_s)
  382. VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
  383. """, rows)
  384. return len(procedures)
  385. finally:
  386. conn.close()
  387. def fetch_process_versions(case_id):
  388. conn = _conn()
  389. try:
  390. with conn.cursor() as cur:
  391. cur.execute("""SELECT version, COUNT(*) AS n, MAX(model) AS model
  392. FROM mode_process WHERE case_id=%s
  393. GROUP BY version ORDER BY version DESC""", (case_id,))
  394. return cur.fetchall()
  395. finally:
  396. conn.close()
  397. def fetch_process(case_id, version=None):
  398. """重建 {case_id, version, model, source, procedures:[...]}。version=None 取最新。"""
  399. conn = _conn()
  400. try:
  401. with conn.cursor() as cur:
  402. if version is None:
  403. cur.execute("""SELECT version FROM mode_process WHERE case_id=%s
  404. ORDER BY version DESC, id DESC LIMIT 1""", (case_id,))
  405. row = cur.fetchone()
  406. if not row:
  407. return None
  408. version = row["version"]
  409. cur.execute("""SELECT * FROM mode_process WHERE case_id=%s AND version=%s
  410. ORDER BY id""", (case_id, version))
  411. rows = cur.fetchall()
  412. finally:
  413. conn.close()
  414. if not rows:
  415. return None
  416. procedures = [{
  417. "id": r["procedure_id"], "name": r["name"], "purpose": r["purpose"],
  418. "category": r["category"], "declarations": _loads(r["declarations"]),
  419. "type_registry": _loads(r["type_registry"]), "steps": _loads(r["steps"], []),
  420. "tools_used": _loads(r["tools_used"], []),
  421. } for r in rows]
  422. return {"case_id": case_id, "version": version, "platform": rows[0]["platform"],
  423. "title": rows[0]["post_title"], "model": rows[0]["model"],
  424. "cost_usd": float(rows[0]["cost_usd"]) if rows[0]["cost_usd"] is not None else None,
  425. "duration_s": rows[0]["duration_s"],
  426. "source": _loads(rows[0]["source"]), "procedures": procedures}
  427. # ── mode_tools ───────────────────────────────────────────────────────────────
  428. def replace_tools(query_id, case_id, platform, post_title, tools,
  429. model, version, cost_usd, duration_s):
  430. """写入一帖某版本的工具解构结果。语义同 replace_process。返回工具条数。"""
  431. conn = _conn()
  432. try:
  433. with conn.cursor() as cur:
  434. cur.execute("DELETE FROM mode_tools WHERE case_id=%s AND version=%s",
  435. (case_id, version))
  436. if tools:
  437. rows = [(
  438. query_id, case_id, platform, (post_title or "")[:500],
  439. (t.get("工具名称") or "")[:250],
  440. _j(t.get("实质作用域")), _j(t.get("形式作用域")),
  441. t.get("创作层级"), t.get("来源链接"), t.get("输入"), t.get("输出"),
  442. _j(t.get("用法")), _j(t.get("案例")), _j(t.get("缺点")),
  443. t.get("最新更新时间"), model, version, cost_usd, duration_s,
  444. ) for t in tools]
  445. cur.executemany("""
  446. INSERT INTO mode_tools
  447. (query_id, case_id, platform, post_title, tool_name, substance_scope,
  448. form_scope, creation_layer, source_link, input_desc, output_desc,
  449. usage_json, cases_json, defects_json, updated_time, model, version,
  450. cost_usd, duration_s)
  451. VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
  452. """, rows)
  453. return len(tools)
  454. finally:
  455. conn.close()
  456. def fetch_tools_versions(case_id):
  457. conn = _conn()
  458. try:
  459. with conn.cursor() as cur:
  460. cur.execute("""SELECT version, COUNT(*) AS n, MAX(model) AS model
  461. FROM mode_tools WHERE case_id=%s
  462. GROUP BY version ORDER BY version DESC""", (case_id,))
  463. return cur.fetchall()
  464. finally:
  465. conn.close()
  466. def fetch_tools(case_id, version=None):
  467. """重建 {case_id, version, model, tool_count, tools:[...]}。version=None 取最新。"""
  468. conn = _conn()
  469. try:
  470. with conn.cursor() as cur:
  471. if version is None:
  472. cur.execute("""SELECT version FROM mode_tools WHERE case_id=%s
  473. ORDER BY version DESC, id DESC LIMIT 1""", (case_id,))
  474. row = cur.fetchone()
  475. if not row:
  476. return None
  477. version = row["version"]
  478. cur.execute("""SELECT * FROM mode_tools WHERE case_id=%s AND version=%s
  479. ORDER BY id""", (case_id, version))
  480. rows = cur.fetchall()
  481. finally:
  482. conn.close()
  483. if not rows:
  484. return None
  485. tools = [{
  486. "工具名称": r["tool_name"], "实质作用域": _loads(r["substance_scope"]),
  487. "形式作用域": _loads(r["form_scope"]), "创作层级": r["creation_layer"],
  488. "来源链接": r["source_link"], "输入": r["input_desc"], "输出": r["output_desc"],
  489. "用法": _loads(r["usage_json"]), "案例": _loads(r["cases_json"]),
  490. "缺点": _loads(r["defects_json"]), "最新更新时间": r["updated_time"],
  491. } for r in rows]
  492. return {"case_id": case_id, "version": version, "platform": rows[0]["platform"],
  493. "title": rows[0]["post_title"], "model": rows[0]["model"],
  494. "cost_usd": float(rows[0]["cost_usd"]) if rows[0]["cost_usd"] is not None else None,
  495. "duration_s": rows[0]["duration_s"],
  496. "tool_count": len(tools), "tools": tools}
  497. # ── 跨 query 去重 / link 复制(方案A:解构前先去重,避免重复花钱)──────────────
  498. # case_id 是帖子物理身份(platform_channelContentId),与 query 无关。同一帖被多个
  499. # query 搜到时只需真实解构一次;其余 query 用 link_* 复制行补齐关联(cost=0)。
  500. def latest_real_version(case_id, mode="process"):
  501. """该 case 是否已有「真实」解构(任意 query;link_* 是复制品,不算源)。
  502. 返回最新一行 {"version","query_id"} 或 None。给解构前去重判定用。"""
  503. table = _mode_table(mode)
  504. conn = _conn()
  505. try:
  506. with conn.cursor() as cur:
  507. cur.execute(f"""SELECT version, query_id FROM {table}
  508. WHERE case_id=%s AND LEFT(version,5) <> 'link_'
  509. ORDER BY version DESC, id DESC LIMIT 1""", (case_id,))
  510. return cur.fetchone()
  511. finally:
  512. conn.close()
  513. def link_process(query_id, case_id, mode="process"):
  514. """把 case 在别处最新「真实」版本的解构行复制到目标 query
  515. (version='link_'+源版本, cost_usd=0)。幂等(先删目标同版本)。
  516. 返回复制行数;该 case 从未真实解构过则返回 0(无源可复制)。"""
  517. table = _mode_table(mode)
  518. conn = _conn()
  519. try:
  520. with conn.cursor() as cur:
  521. cur.execute(f"""SELECT version FROM {table}
  522. WHERE case_id=%s AND LEFT(version,5) <> 'link_'
  523. ORDER BY version DESC, id DESC LIMIT 1""", (case_id,))
  524. r = cur.fetchone()
  525. if not r:
  526. return 0
  527. srcver = r["version"]
  528. newver = ("link_" + srcver)[:32] # version 列 VARCHAR(32)
  529. # 复制除自增 id / 时间戳外的全部列,改写 query_id / version / cost。
  530. cur.execute(f"SHOW COLUMNS FROM {table}")
  531. cols = [c["Field"] for c in cur.fetchall()
  532. if c["Field"] not in ("id", "created_at", "updated_at")]
  533. cur.execute(f"SELECT {','.join(cols)} FROM {table} WHERE case_id=%s AND version=%s",
  534. (case_id, srcver))
  535. rows = cur.fetchall()
  536. cur.execute(f"DELETE FROM {table} WHERE query_id=%s AND case_id=%s AND version=%s",
  537. (query_id, case_id, newver))
  538. for row in rows:
  539. row = dict(row)
  540. row["query_id"] = query_id
  541. row["version"] = newver
  542. row["cost_usd"] = 0
  543. cur.execute(
  544. f"INSERT INTO {table} ({','.join(cols)}) VALUES ({','.join(['%s']*len(cols))})",
  545. [row[k] for k in cols])
  546. return len(rows)
  547. finally:
  548. conn.close()
  549. # ── Dashboard 原始行(指标计算在 server.py)─────────────────────────────────────
  550. def fetch_dashboard_rows():
  551. """拉 Dashboard 计算所需的轻量行。数据量级:百~千行,Python 聚合足够。"""
  552. conn = _conn()
  553. try:
  554. with conn.cursor() as cur:
  555. # 进度分母走「采纳」口径,需带上 is_adopted 判定所需字段;
  556. # mode 标方向(工序帖来自 search_process,工具帖来自 search_tools)。
  557. cols = ("query_id, case_id, platform, knowledge_type, "
  558. "overall_score, publish_time, llm_evaluation")
  559. cur.execute(f"SELECT {cols} FROM search_process")
  560. posts = cur.fetchall()
  561. for p in posts:
  562. p["mode"] = "process"
  563. cur.execute(f"SELECT {cols} FROM search_tools")
  564. st = cur.fetchall()
  565. for p in st:
  566. p["mode"] = "tools"
  567. posts += st
  568. cur.execute("""SELECT case_id, version, steps, tools_used, cost_usd,
  569. duration_s, created_at FROM mode_process""")
  570. procs = cur.fetchall()
  571. cur.execute("""SELECT case_id, version, tool_name, substance_scope,
  572. form_scope, cost_usd, duration_s, created_at
  573. FROM mode_tools""")
  574. tools = cur.fetchall()
  575. finally:
  576. conn.close()
  577. for p in posts:
  578. p["knowledge_type"] = _loads(p["knowledge_type"], [])
  579. # 采纳判定:口径同帖子列表(is_adopted),作为「需解构」分母依据
  580. p["adopted"] = is_adopted(
  581. p["overall_score"], _loads(p["llm_evaluation"]), p["publish_time"])
  582. for r in procs:
  583. r["steps"] = _loads(r["steps"], [])
  584. r["tools_used"] = _loads(r["tools_used"], [])
  585. r["cost_usd"] = float(r["cost_usd"]) if r["cost_usd"] is not None else None
  586. r["created_at"] = str(r["created_at"]) if r["created_at"] else None
  587. for r in tools:
  588. r["substance_scope"] = _loads(r["substance_scope"], [])
  589. r["form_scope"] = _loads(r["form_scope"], [])
  590. r["cost_usd"] = float(r["cost_usd"]) if r["cost_usd"] is not None else None
  591. r["created_at"] = str(r["created_at"]) if r["created_at"] else None
  592. return posts, procs, tools
  593. def check():
  594. conn = _conn()
  595. try:
  596. with conn.cursor() as cur:
  597. for t in ("search_process", "search_tools", "mode_process", "mode_tools"):
  598. cur.execute(f"SELECT COUNT(*) AS n FROM {t}")
  599. print(f"{t}: {cur.fetchone()['n']} 行")
  600. finally:
  601. conn.close()
  602. if __name__ == "__main__":
  603. cmd = sys.argv[1] if len(sys.argv) > 1 else ""
  604. if cmd == "init":
  605. init_tables()
  606. elif cmd == "check":
  607. check()
  608. elif cmd == "clear":
  609. clear_tables()
  610. else:
  611. print("用法:\n python db.py init # 建表\n python db.py check # 四表行数\n python db.py clear # 清空四表数据")