db.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  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. from dbutils.pooled_db import PooledDB
  28. # ── 连接池 ──────────────────────────────────────────────────────────────────
  29. # MySQL 是远程 RDS,每次 pymysql.connect() 的 TCP+鉴权握手 ~0.5s。旧实现每个
  30. # 请求新建一条连接,一次"点开帖子"要 2~3 个请求 = 2~3 次握手 ≈ 1s。改用连接池
  31. # 复用长连接后,握手只在池初始化时各发生一次,后续取连接近乎零开销。
  32. # server.py 是 ThreadingHTTPServer(每请求一线程),PooledDB 线程安全,正好匹配。
  33. # 注意:fetch_* 里的 conn.close() 在池连接上语义是"归还池中"而非真正断开。
  34. _POOL = None
  35. def _pool():
  36. global _POOL
  37. if _POOL is None:
  38. if not os.getenv("MYSQL_HOST"):
  39. raise RuntimeError("缺 MYSQL_HOST:检查 .env 的 MYSQL_* 配置")
  40. _POOL = PooledDB(
  41. creator=pymysql,
  42. mincached=2, # 启动即预热 2 条,首点不再吃冷握手
  43. maxcached=5, # 空闲保留上限
  44. maxconnections=20, # 并发上限(ThreadingHTTPServer 线程数)
  45. blocking=True, # 连接耗尽时等待而非报错
  46. ping=1, # 取用前 ping,自动剔除被 RDS 掐断的死连接
  47. host=os.getenv("MYSQL_HOST"),
  48. port=int(os.getenv("MYSQL_PORT", 3306)),
  49. user=os.getenv("MYSQL_USER"),
  50. password=os.getenv("MYSQL_PASSWORD"),
  51. database=os.getenv("MYSQL_DATABASE"),
  52. charset="utf8mb4", cursorclass=DictCursor,
  53. autocommit=True, connect_timeout=10,
  54. )
  55. return _POOL
  56. def _conn():
  57. """从池取一条连接;用法不变(with cursor / conn.close() 归还池)。"""
  58. return _pool().connection()
  59. # ── DDL ──────────────────────────────────────────────────────────────────────
  60. SEARCH_TABLES = {"process": "search_process", "tools": "search_tools"}
  61. MODE_TABLES = {"process": "mode_process", "tools": "mode_tools"}
  62. def _search_table(mode_or_table):
  63. """mode(process/tools)或表名 → 合法搜索表名(白名单,防 SQL 注入)。"""
  64. t = SEARCH_TABLES.get(mode_or_table, mode_or_table)
  65. if t not in SEARCH_TABLES.values():
  66. raise ValueError(f"未知搜索表/模式: {mode_or_table!r}")
  67. return t
  68. def _mode_table(mode_or_table):
  69. """mode(process/tools)或表名 → 合法解构表名(白名单,防 SQL 注入)。"""
  70. t = MODE_TABLES.get(mode_or_table, mode_or_table)
  71. if t not in MODE_TABLES.values():
  72. raise ValueError(f"未知解构表/模式: {mode_or_table!r}")
  73. return t
  74. def _ddl_search(table, direction):
  75. return f"""
  76. CREATE TABLE IF NOT EXISTS {table} (
  77. id BIGINT AUTO_INCREMENT PRIMARY KEY,
  78. query_id VARCHAR(32) NOT NULL COMMENT 'q0000',
  79. query_text VARCHAR(512) NULL,
  80. case_id VARCHAR(128) NOT NULL COMMENT 'platform_channelContentId',
  81. platform VARCHAR(32) NULL,
  82. channel_content_id VARCHAR(128) NULL,
  83. title VARCHAR(512) NULL,
  84. url VARCHAR(1024) NULL,
  85. content_type VARCHAR(32) NULL,
  86. body LONGTEXT NULL,
  87. images JSON NULL,
  88. videos JSON NULL,
  89. like_count INT NULL,
  90. publish_time VARCHAR(64) NULL,
  91. quality_score FLOAT NULL COMMENT 'post._quality_score',
  92. quality_grade VARCHAR(8) NULL,
  93. found_by JSON NULL COMMENT '命中的措辞数组',
  94. knowledge_type JSON NULL COMMENT '["能力","工序","工具"] 子集',
  95. overall_score FLOAT NULL COMMENT '(相关均值+质量均值)/2',
  96. llm_evaluation JSON NULL COMMENT '评估全量 blob',
  97. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  98. updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  99. UNIQUE KEY uk_qid_case (query_id, case_id),
  100. KEY idx_platform (platform)
  101. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='搜索+评估结果({direction})';
  102. """
  103. DDL_PROCESS = """
  104. CREATE TABLE IF NOT EXISTS mode_process (
  105. id BIGINT AUTO_INCREMENT PRIMARY KEY,
  106. query_id VARCHAR(32) NOT NULL,
  107. case_id VARCHAR(128) NOT NULL,
  108. platform VARCHAR(32) NULL,
  109. post_title VARCHAR(512) NULL,
  110. source JSON NULL COMMENT '解构返回的 source 块',
  111. procedure_id VARCHAR(16) NULL COMMENT 'p1,p2…',
  112. name VARCHAR(255) NULL,
  113. purpose TEXT NULL,
  114. category VARCHAR(32) NULL COMMENT '产物创造/资产建设/自动化/分析/学习',
  115. declarations JSON NULL,
  116. type_registry JSON NULL,
  117. steps JSON NULL COMMENT '步骤数组全量',
  118. step_count INT NULL,
  119. tools_used JSON NULL COMMENT '从 steps[].via 去重提取',
  120. model VARCHAR(64) NULL,
  121. version VARCHAR(32) NULL COMMENT 'v_MMDDHHMM,保留历史;link_* 为跨 query 复制(cost=0)',
  122. cost_usd DECIMAL(10,6) NULL COMMENT '本次解构调用成本(同版本各行相同,聚合需按 case+version 去重)',
  123. duration_s FLOAT NULL,
  124. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  125. KEY idx_case_ver (case_id, version),
  126. KEY idx_qid (query_id)
  127. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='工序解构结果(每行一个工序)';
  128. """
  129. DDL_TOOLS = """
  130. CREATE TABLE IF NOT EXISTS mode_tools (
  131. id BIGINT AUTO_INCREMENT PRIMARY KEY,
  132. query_id VARCHAR(32) NOT NULL,
  133. case_id VARCHAR(128) NOT NULL,
  134. platform VARCHAR(32) NULL,
  135. post_title VARCHAR(512) NULL,
  136. tool_name VARCHAR(255) NULL,
  137. substance_scope JSON NULL COMMENT '实质作用域(数组)',
  138. form_scope JSON NULL COMMENT '形式作用域(数组或null)',
  139. creation_layer VARCHAR(32) NULL COMMENT '制作层/创作层',
  140. source_link VARCHAR(1024) NULL,
  141. input_desc TEXT NULL,
  142. output_desc TEXT NULL,
  143. usage_json JSON NULL,
  144. cases_json JSON NULL,
  145. defects_json JSON NULL,
  146. updated_time VARCHAR(64) NULL COMMENT '工具最新更新时间',
  147. model VARCHAR(64) NULL,
  148. version VARCHAR(32) NULL COMMENT 'v_MMDDHHMM;link_* 为跨 query 复制(cost=0)',
  149. cost_usd DECIMAL(10,6) NULL COMMENT '同 mode_process,聚合按 case+version 去重',
  150. duration_s FLOAT NULL,
  151. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  152. KEY idx_case_ver (case_id, version),
  153. KEY idx_qid (query_id),
  154. KEY idx_tool_name (tool_name)
  155. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='工具解构结果(每行一个工具)';
  156. """
  157. # 工序知识「已导入知识库」台账:防重复上传(import_process_knowledge.py 用)。
  158. # 每条知识 = 某 case 的某个工序(proc_index 1-based)。记录导入时的 mode_process 版本:
  159. # 版本变了(重解构)说明内容已变,应重导;版本不变即视为「已传过」,跳过。
  160. # 选 DB 台账而非本地文件,是为了换机器/换链接后也不会重复写知识库。
  161. DDL_INGEST_LOG = """
  162. CREATE TABLE IF NOT EXISTS knowledge_ingest_log (
  163. id BIGINT AUTO_INCREMENT PRIMARY KEY,
  164. case_id VARCHAR(128) NOT NULL,
  165. proc_index INT NOT NULL COMMENT '工序序号(1-based),对齐导入脚本枚举',
  166. version VARCHAR(32) NULL COMMENT '导入时 mode_process 版本;变了应重导',
  167. knowledge_id VARCHAR(128) NULL COMMENT '接口返回的 knowledge_id',
  168. api_url VARCHAR(255) NULL,
  169. ingested_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  170. updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  171. UNIQUE KEY uk_case_proc (case_id, proc_index)
  172. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='工序知识已导入台账(防重复上传)';
  173. """
  174. def init_tables():
  175. conn = _conn()
  176. try:
  177. with conn.cursor() as cur:
  178. cur.execute(_ddl_search("search_process", "工序方向"))
  179. cur.execute(_ddl_search("search_tools", "工具方向"))
  180. cur.execute(DDL_PROCESS)
  181. cur.execute(DDL_TOOLS)
  182. cur.execute(DDL_INGEST_LOG)
  183. # 历史库迁移:version 由 VARCHAR(16) 放宽到 32,容纳 link_v_mopN_* 复制版本。
  184. # MODIFY 幂等(已是 32 则 MySQL 元数据无操作),建表后表必存在,可安全执行。
  185. for t in ("mode_process", "mode_tools"):
  186. cur.execute(f"ALTER TABLE {t} MODIFY COLUMN version VARCHAR(32) NULL")
  187. print("✅ 建表完成:search_process, search_tools, mode_process, mode_tools, knowledge_ingest_log")
  188. finally:
  189. conn.close()
  190. def clear_tables():
  191. """清空四张表的数据(TRUNCATE,表结构保留)。"""
  192. conn = _conn()
  193. try:
  194. with conn.cursor() as cur:
  195. for t in ("search_process", "search_tools", "mode_process", "mode_tools"):
  196. cur.execute(f"TRUNCATE TABLE {t}")
  197. print(f"🧹 已清空 {t}")
  198. finally:
  199. conn.close()
  200. # ── 工具函数 ──────────────────────────────────────────────────────────────────
  201. def _loads(v, default=None):
  202. """pymysql 的 JSON 列可能返回字符串,统一解析。"""
  203. if v is None:
  204. return default
  205. if isinstance(v, (list, dict)):
  206. return v
  207. try:
  208. return json.loads(v)
  209. except Exception:
  210. return default
  211. def _j(v):
  212. """写入 JSON 列:None 保持 NULL,其余 dumps。"""
  213. return None if v is None else json.dumps(v, ensure_ascii=False)
  214. def _collect_scores(node):
  215. """递归收集嵌套评估里所有「得分」。LLM 直出的得分多为字符串("1"/"4"),
  216. 个别为数字(如 时效性 10),统一按 float 解析;非数值(如 "N/A")跳过不计入。"""
  217. out = []
  218. if isinstance(node, dict):
  219. for k, v in node.items():
  220. if k == "得分":
  221. try:
  222. out.append(float(v))
  223. except (TypeError, ValueError):
  224. pass
  225. else:
  226. out.extend(_collect_scores(v))
  227. elif isinstance(node, list):
  228. for v in node:
  229. out.extend(_collect_scores(v))
  230. return out
  231. def overall_score(e):
  232. """综合分 = (相关性各项均值 + 质量各项均值) / 可得部分数。算不出返回 None。"""
  233. parts = []
  234. for key in ("相关性", "质量"):
  235. scores = _collect_scores((e or {}).get(key))
  236. if scores:
  237. parts.append(sum(scores) / len(scores))
  238. return round(sum(parts) / len(parts), 2) if parts else None
  239. def _recency_hard(date_str):
  240. """硬时效(同 mode_procedure/server.py:_recency_hard):半年内=3 / 两年内=2 / 更早=1。
  241. publish_time 头 10 字符按 YYYY-MM-DD 解析,失败返回 None(不参与判定)。"""
  242. try:
  243. d = datetime.strptime(str(date_str or "")[:10], "%Y-%m-%d")
  244. except (ValueError, TypeError):
  245. return None
  246. days = (datetime.now() - d).days
  247. if days <= 180:
  248. return 3
  249. if days <= 730:
  250. return 2
  251. return 1
  252. def _fixed_dim_score(evaluation, name):
  253. """取 质量.固定维度.<name>.得分 标量,缺失/非数值返回 None(不参与判定)。"""
  254. v = (((evaluation or {}).get("质量") or {}).get("固定维度") or {}).get(name)
  255. if isinstance(v, dict):
  256. v = v.get("得分")
  257. try:
  258. return float(v) if v is not None else None
  259. except (TypeError, ValueError):
  260. return None
  261. def _impl_score(evaluation):
  262. """取 质量.动态维度.工序.字段完整性.实现完整性.得分 标量,缺失/非数值返回 None。
  263. 新版 prompt 把旧「可复现性」的硬封顶规则并入了「实现完整性」,故采纳门槛改读此处。"""
  264. v = ((((((evaluation or {}).get("质量") or {}).get("动态维度") or {})
  265. .get("工序") or {}).get("字段完整性") or {}).get("实现完整性"))
  266. if isinstance(v, dict):
  267. v = v.get("得分")
  268. try:
  269. return float(v) if v is not None else None
  270. except (TypeError, ValueError):
  271. return None
  272. def _repro_score(evaluation):
  273. """采纳门槛用的「可复现/可实现」得分:优先旧版「可复现性」(固定维度),
  274. 缺失则回退新版「实现完整性」(动态维度.工序)。这样新旧两套评估 blob 都能正确判定。"""
  275. v = _fixed_dim_score(evaluation, "可复现性")
  276. return v if v is not None else _impl_score(evaluation)
  277. def is_adopted(overall, evaluation, publish_time):
  278. """采纳/命中判定,口径对齐 mode_procedure 的 decision=="report":
  279. 制作相关性<4、可复现/实现完整性<4、发布超两年、综合分<6 —— 任一命中即不采纳;指标缺失不参与判定。
  280. (意图可控性暂只采分不设门槛,留待阈值标定后再开。)
  281. 可复现/实现门槛兼容新旧 schema:旧版读「可复现性」,新版读「实现完整性」(见 _repro_score)。
  282. fail-closed:评估失败(_error)、blob 缺失/为空、或综合分算不出(None)→ 直接判不采纳。
  283. 评不出的帖子不该混进命中集(此前 fail-open 会因各指标取不到值而误判采纳)。"""
  284. if not isinstance(evaluation, dict) or not evaluation or evaluation.get("_error"):
  285. return False
  286. if overall is None:
  287. return False
  288. rel = None
  289. v = ((evaluation or {}).get("相关性") or {}).get("和内容制作知识相关")
  290. if isinstance(v, dict):
  291. v = v.get("得分")
  292. try:
  293. rel = float(v) if v is not None else None
  294. except (TypeError, ValueError):
  295. rel = None
  296. if rel is not None and rel < 4:
  297. return False
  298. repro = _repro_score(evaluation)
  299. if repro is not None and repro < 4:
  300. return False
  301. rh = _recency_hard(publish_time)
  302. if rh is not None and rh < 2:
  303. return False
  304. if overall is not None and float(overall) < 6:
  305. return False
  306. return True
  307. def is_adopted_rel(overall, rel, publish_time, repro=None):
  308. """is_adopted 的轻量版:相关性得分(rel)、可复现/实现门槛(repro)已由 SQL JSON_EXTRACT
  309. 直接取出(repro 由 _REPRO_SQL 兼容新旧 schema 取值),无需传输/解析整块 llm_evaluation。
  310. 判定口径与 is_adopted 完全一致(含 fail-closed:综合分算不出→不采纳;失败帖的 overall_score 列为 NULL)。"""
  311. if overall is None:
  312. return False
  313. try:
  314. rel = float(rel) if rel is not None else None
  315. except (TypeError, ValueError):
  316. rel = None
  317. if rel is not None and rel < 4:
  318. return False
  319. try:
  320. repro = float(repro) if repro is not None else None
  321. except (TypeError, ValueError):
  322. repro = None
  323. if repro is not None and repro < 4:
  324. return False
  325. rh = _recency_hard(publish_time)
  326. if rh is not None and rh < 2:
  327. return False
  328. if overall is not None and float(overall) < 6:
  329. return False
  330. return True
  331. # ── search_process / search_tools ────────────────────────────────────────────
  332. def upsert_search_posts(query_id, query_text, results, table="search_process"):
  333. """一组搜索结果写入指定搜索表(按 (query_id, case_id) upsert)。返回写入条数。
  334. table:search_process(工序方向) / search_tools(工具方向)。"""
  335. table = _search_table(table)
  336. if not results:
  337. return 0
  338. rows = []
  339. for r in results:
  340. post = r.get("post") or {}
  341. e = r.get("llm_evaluation") or {}
  342. rows.append((
  343. query_id, query_text, r.get("case_id"), r.get("platform"),
  344. r.get("channel_content_id"),
  345. (post.get("title") or post.get("desc") or "")[:500],
  346. r.get("source_url"), post.get("content_type"),
  347. post.get("body_text") or post.get("desc") or "",
  348. _j(post.get("images") or []), _j(post.get("videos") or []),
  349. post.get("like_count"),
  350. str(post.get("publish_time") or post.get("publish_timestamp") or "")[:64],
  351. post.get("_quality_score"), post.get("_quality_grade"),
  352. _j(r.get("found_by_queries") or []),
  353. _j(e.get("知识类型") or []),
  354. overall_score(e),
  355. _j(e),
  356. ))
  357. sql = f"""
  358. INSERT INTO {table}
  359. (query_id, query_text, case_id, platform, channel_content_id, title, url,
  360. content_type, body, images, videos, like_count, publish_time,
  361. quality_score, quality_grade, found_by, knowledge_type,
  362. overall_score, llm_evaluation)
  363. VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
  364. ON DUPLICATE KEY UPDATE
  365. query_text=VALUES(query_text), platform=VALUES(platform),
  366. channel_content_id=VALUES(channel_content_id), title=VALUES(title), url=VALUES(url),
  367. content_type=VALUES(content_type), body=VALUES(body), images=VALUES(images),
  368. videos=VALUES(videos), like_count=VALUES(like_count), publish_time=VALUES(publish_time),
  369. quality_score=VALUES(quality_score), quality_grade=VALUES(quality_grade),
  370. found_by=VALUES(found_by), knowledge_type=VALUES(knowledge_type),
  371. overall_score=VALUES(overall_score), llm_evaluation=VALUES(llm_evaluation);
  372. """
  373. conn = _conn()
  374. try:
  375. with conn.cursor() as cur:
  376. cur.executemany(sql, rows)
  377. return len(rows)
  378. finally:
  379. conn.close()
  380. def fetch_queries(mode="process"):
  381. """某方向搜索表的 query 列表 + 帖子数 + 采纳/命中数 + 解构进度。"""
  382. table = _search_table(mode)
  383. conn = _conn()
  384. try:
  385. with conn.cursor() as cur:
  386. cur.execute(f"""SELECT query_id, MAX(query_text) AS query_text,
  387. COUNT(*) AS post_count
  388. FROM {table} GROUP BY query_id ORDER BY query_id""")
  389. queries = cur.fetchall()
  390. cur.execute(f"""SELECT query_id, overall_score, llm_evaluation, publish_time
  391. FROM {table}""")
  392. hits = {}
  393. for r in cur.fetchall():
  394. if is_adopted(r["overall_score"], _loads(r["llm_evaluation"]), r["publish_time"]):
  395. hits[r["query_id"]] = hits.get(r["query_id"], 0) + 1
  396. cur.execute("SELECT query_id, COUNT(DISTINCT case_id) AS n FROM mode_process GROUP BY query_id")
  397. np = {r["query_id"]: r["n"] for r in cur.fetchall()}
  398. cur.execute("SELECT query_id, COUNT(DISTINCT case_id) AS n FROM mode_tools GROUP BY query_id")
  399. nt = {r["query_id"]: r["n"] for r in cur.fetchall()}
  400. finally:
  401. conn.close()
  402. for q in queries:
  403. q["hit_count"] = hits.get(q["query_id"], 0)
  404. q["process_done"] = np.get(q["query_id"], 0)
  405. q["tools_done"] = nt.get(q["query_id"], 0)
  406. return queries
  407. def fetch_posts(query_id, mode="process"):
  408. """某方向搜索表里某 query 的全部帖子(JSON 列已解析),带 has_process/has_tools 标记。"""
  409. table = _search_table(mode)
  410. conn = _conn()
  411. try:
  412. with conn.cursor() as cur:
  413. cur.execute(f"""SELECT * FROM {table} WHERE query_id=%s
  414. ORDER BY overall_score DESC, id""", (query_id,))
  415. rows = cur.fetchall()
  416. cur.execute("SELECT DISTINCT case_id FROM mode_process WHERE query_id=%s", (query_id,))
  417. hp = {r["case_id"] for r in cur.fetchall()}
  418. cur.execute("SELECT DISTINCT case_id FROM mode_tools WHERE query_id=%s", (query_id,))
  419. ht = {r["case_id"] for r in cur.fetchall()}
  420. finally:
  421. conn.close()
  422. for r in rows:
  423. for col in ("images", "videos", "found_by", "knowledge_type", "llm_evaluation"):
  424. r[col] = _loads(r[col])
  425. r["adopted"] = is_adopted(r["overall_score"], r["llm_evaluation"], r["publish_time"])
  426. r["has_process"] = r["case_id"] in hp
  427. r["has_tools"] = r["case_id"] in ht
  428. r.pop("created_at", None); r.pop("updated_at", None)
  429. return rows
  430. def fetch_post(query_id, case_id, table="search_process"):
  431. """指定搜索表的单帖完整行(给 pipeline 脚本重建 source 用)。无则 None。"""
  432. table = _search_table(table)
  433. conn = _conn()
  434. try:
  435. with conn.cursor() as cur:
  436. cur.execute(f"SELECT * FROM {table} WHERE query_id=%s AND case_id=%s",
  437. (query_id, case_id))
  438. row = cur.fetchone()
  439. finally:
  440. conn.close()
  441. if not row:
  442. return None
  443. for col in ("images", "videos", "found_by", "knowledge_type", "llm_evaluation"):
  444. row[col] = _loads(row[col])
  445. return row
  446. # ── mode_process ─────────────────────────────────────────────────────────────
  447. def replace_process(query_id, case_id, platform, post_title, payload,
  448. model, version, cost_usd, duration_s):
  449. """写入一帖某版本的工序解构结果(payload = {source, procedures})。
  450. 删 (case_id, version) 旧行再插,同版本重跑幂等、跨版本保留历史。返回工序条数。"""
  451. source = payload.get("source")
  452. procedures = payload.get("procedures") or []
  453. conn = _conn()
  454. try:
  455. with conn.cursor() as cur:
  456. cur.execute("DELETE FROM mode_process WHERE case_id=%s AND version=%s",
  457. (case_id, version))
  458. if procedures:
  459. rows = []
  460. for p in procedures:
  461. steps = p.get("steps") or []
  462. vias = []
  463. for s in steps:
  464. v = s.get("via")
  465. if v and v not in vias:
  466. vias.append(v)
  467. rows.append((
  468. query_id, case_id, platform, (post_title or "")[:500],
  469. _j(source), p.get("id"), (p.get("name") or "")[:250],
  470. p.get("purpose"), p.get("category"),
  471. _j(p.get("declarations")), _j(p.get("type_registry")),
  472. _j(steps), len(steps), _j(vias),
  473. model, version, cost_usd, duration_s,
  474. ))
  475. cur.executemany("""
  476. INSERT INTO mode_process
  477. (query_id, case_id, platform, post_title, source, procedure_id, name,
  478. purpose, category, declarations, type_registry, steps, step_count,
  479. tools_used, model, version, cost_usd, duration_s)
  480. VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
  481. """, rows)
  482. return len(procedures)
  483. finally:
  484. conn.close()
  485. def fetch_process_versions(case_id):
  486. conn = _conn()
  487. try:
  488. with conn.cursor() as cur:
  489. cur.execute("""SELECT version, COUNT(*) AS n, MAX(model) AS model
  490. FROM mode_process WHERE case_id=%s
  491. GROUP BY version ORDER BY version DESC""", (case_id,))
  492. return cur.fetchall()
  493. finally:
  494. conn.close()
  495. def fetch_process(case_id, version=None):
  496. """重建 {case_id, version, model, source, procedures:[...]}。version=None 取最新。"""
  497. conn = _conn()
  498. try:
  499. with conn.cursor() as cur:
  500. if version is None:
  501. cur.execute("""SELECT version FROM mode_process WHERE case_id=%s
  502. ORDER BY version DESC, id DESC LIMIT 1""", (case_id,))
  503. row = cur.fetchone()
  504. if not row:
  505. return None
  506. version = row["version"]
  507. cur.execute("""SELECT * FROM mode_process WHERE case_id=%s AND version=%s
  508. ORDER BY id""", (case_id, version))
  509. rows = cur.fetchall()
  510. finally:
  511. conn.close()
  512. return _proc_payload(case_id, version, rows)
  513. def _proc_payload(case_id, version, rows):
  514. """mode_process 行集 → {case_id, version, …, procedures:[...]}。无行返回 None。"""
  515. if not rows:
  516. return None
  517. procedures = [{
  518. "id": r["procedure_id"], "name": r["name"], "purpose": r["purpose"],
  519. "category": r["category"], "declarations": _loads(r["declarations"]),
  520. "type_registry": _loads(r["type_registry"]), "steps": _loads(r["steps"], []),
  521. "tools_used": _loads(r["tools_used"], []),
  522. } for r in rows]
  523. return {"case_id": case_id, "version": version, "platform": rows[0]["platform"],
  524. "title": rows[0]["post_title"], "model": rows[0]["model"],
  525. "cost_usd": float(rows[0]["cost_usd"]) if rows[0]["cost_usd"] is not None else None,
  526. "duration_s": rows[0]["duration_s"],
  527. "source": _loads(rows[0]["source"]), "procedures": procedures}
  528. # ── mode_tools ───────────────────────────────────────────────────────────────
  529. def replace_tools(query_id, case_id, platform, post_title, tools,
  530. model, version, cost_usd, duration_s):
  531. """写入一帖某版本的工具解构结果。语义同 replace_process。返回工具条数。"""
  532. conn = _conn()
  533. try:
  534. with conn.cursor() as cur:
  535. cur.execute("DELETE FROM mode_tools WHERE case_id=%s AND version=%s",
  536. (case_id, version))
  537. if tools:
  538. rows = [(
  539. query_id, case_id, platform, (post_title or "")[:500],
  540. (t.get("工具名称") or "")[:250],
  541. _j(t.get("实质作用域")), _j(t.get("形式作用域")),
  542. t.get("创作层级"), t.get("来源链接"), t.get("输入"), t.get("输出"),
  543. _j(t.get("用法")), _j(t.get("案例")), _j(t.get("缺点")),
  544. t.get("最新更新时间"), model, version, cost_usd, duration_s,
  545. ) for t in tools]
  546. cur.executemany("""
  547. INSERT INTO mode_tools
  548. (query_id, case_id, platform, post_title, tool_name, substance_scope,
  549. form_scope, creation_layer, source_link, input_desc, output_desc,
  550. usage_json, cases_json, defects_json, updated_time, model, version,
  551. cost_usd, duration_s)
  552. VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
  553. """, rows)
  554. return len(tools)
  555. finally:
  556. conn.close()
  557. def fetch_tools_versions(case_id):
  558. conn = _conn()
  559. try:
  560. with conn.cursor() as cur:
  561. cur.execute("""SELECT version, COUNT(*) AS n, MAX(model) AS model
  562. FROM mode_tools WHERE case_id=%s
  563. GROUP BY version ORDER BY version DESC""", (case_id,))
  564. return cur.fetchall()
  565. finally:
  566. conn.close()
  567. def fetch_tools(case_id, version=None):
  568. """重建 {case_id, version, model, tool_count, tools:[...]}。version=None 取最新。"""
  569. conn = _conn()
  570. try:
  571. with conn.cursor() as cur:
  572. if version is None:
  573. cur.execute("""SELECT version FROM mode_tools WHERE case_id=%s
  574. ORDER BY version DESC, id DESC LIMIT 1""", (case_id,))
  575. row = cur.fetchone()
  576. if not row:
  577. return None
  578. version = row["version"]
  579. cur.execute("""SELECT * FROM mode_tools WHERE case_id=%s AND version=%s
  580. ORDER BY id""", (case_id, version))
  581. rows = cur.fetchall()
  582. finally:
  583. conn.close()
  584. return _tools_payload(case_id, version, rows)
  585. def _tools_payload(case_id, version, rows):
  586. """mode_tools 行集 → {case_id, version, …, tools:[...]}。无行返回 None。"""
  587. if not rows:
  588. return None
  589. tools = [{
  590. "工具名称": r["tool_name"], "实质作用域": _loads(r["substance_scope"]),
  591. "形式作用域": _loads(r["form_scope"]), "创作层级": r["creation_layer"],
  592. "来源链接": r["source_link"], "输入": r["input_desc"], "输出": r["output_desc"],
  593. "用法": _loads(r["usage_json"]), "案例": _loads(r["cases_json"]),
  594. "缺点": _loads(r["defects_json"]), "最新更新时间": r["updated_time"],
  595. } for r in rows]
  596. return {"case_id": case_id, "version": version, "platform": rows[0]["platform"],
  597. "title": rows[0]["post_title"], "model": rows[0]["model"],
  598. "cost_usd": float(rows[0]["cost_usd"]) if rows[0]["cost_usd"] is not None else None,
  599. "duration_s": rows[0]["duration_s"],
  600. "tool_count": len(tools), "tools": tools}
  601. # ── 点击帖子合一查询(单连接,最少往返;远程 RDS 每次往返 ~80ms,故按次数优化)──
  602. def fetch_extract(mode, case_id, version=None):
  603. """一次取版本列表 + 解构详情,复用同一条池连接、最少往返。
  604. 返回 {versions, data, missing}。mode: process / tools。"""
  605. is_proc = mode != "tools"
  606. mtable = _mode_table("process" if is_proc else "tools")
  607. conn = _conn()
  608. try:
  609. with conn.cursor() as cur:
  610. cur.execute(f"""SELECT version, COUNT(*) AS n, MAX(model) AS model
  611. FROM {mtable} WHERE case_id=%s
  612. GROUP BY version ORDER BY version DESC""", (case_id,))
  613. versions = cur.fetchall()
  614. # 详情:把"取最新版本"折进同一条 SQL,版本指定时直接用;省一次往返。
  615. target = version or (versions[0]["version"] if versions else None)
  616. rows = []
  617. if target is not None:
  618. cur.execute(f"SELECT * FROM {mtable} WHERE case_id=%s AND version=%s ORDER BY id",
  619. (case_id, target))
  620. rows = cur.fetchall()
  621. finally:
  622. conn.close()
  623. payload = (_proc_payload if is_proc else _tools_payload)(case_id, target, rows)
  624. return {"versions": versions, "data": payload, "missing": payload is None}
  625. # ── 跨 query 去重 / link 复制(方案A:解构前先去重,避免重复花钱)──────────────
  626. # case_id 是帖子物理身份(platform_channelContentId),与 query 无关。同一帖被多个
  627. # query 搜到时只需真实解构一次;其余 query 用 link_* 复制行补齐关联(cost=0)。
  628. def latest_real_version(case_id, mode="process"):
  629. """该 case 是否已有「真实」解构(任意 query;link_* 是复制品,不算源)。
  630. 返回最新一行 {"version","query_id"} 或 None。给解构前去重判定用。"""
  631. table = _mode_table(mode)
  632. conn = _conn()
  633. try:
  634. with conn.cursor() as cur:
  635. cur.execute(f"""SELECT version, query_id FROM {table}
  636. WHERE case_id=%s AND LEFT(version,5) <> 'link_'
  637. ORDER BY version DESC, id DESC LIMIT 1""", (case_id,))
  638. return cur.fetchone()
  639. finally:
  640. conn.close()
  641. def link_process(query_id, case_id, mode="process"):
  642. """把 case 在别处最新「真实」版本的解构行复制到目标 query
  643. (version='link_'+源版本, cost_usd=0)。幂等(先删目标同版本)。
  644. 返回复制行数;该 case 从未真实解构过则返回 0(无源可复制)。"""
  645. table = _mode_table(mode)
  646. conn = _conn()
  647. try:
  648. with conn.cursor() as cur:
  649. cur.execute(f"""SELECT version FROM {table}
  650. WHERE case_id=%s AND LEFT(version,5) <> 'link_'
  651. ORDER BY version DESC, id DESC LIMIT 1""", (case_id,))
  652. r = cur.fetchone()
  653. if not r:
  654. return 0
  655. srcver = r["version"]
  656. newver = ("link_" + srcver)[:32] # version 列 VARCHAR(32)
  657. # 复制除自增 id / 时间戳外的全部列,改写 query_id / version / cost。
  658. cur.execute(f"SHOW COLUMNS FROM {table}")
  659. cols = [c["Field"] for c in cur.fetchall()
  660. if c["Field"] not in ("id", "created_at", "updated_at")]
  661. cur.execute(f"SELECT {','.join(cols)} FROM {table} WHERE case_id=%s AND version=%s",
  662. (case_id, srcver))
  663. rows = cur.fetchall()
  664. cur.execute(f"DELETE FROM {table} WHERE query_id=%s AND case_id=%s AND version=%s",
  665. (query_id, case_id, newver))
  666. for row in rows:
  667. row = dict(row)
  668. row["query_id"] = query_id
  669. row["version"] = newver
  670. row["cost_usd"] = 0
  671. cur.execute(
  672. f"INSERT INTO {table} ({','.join(cols)}) VALUES ({','.join(['%s']*len(cols))})",
  673. [row[k] for k in cols])
  674. return len(rows)
  675. finally:
  676. conn.close()
  677. # ── Dashboard 原始行(指标计算在 server.py)─────────────────────────────────────
  678. # 采纳判定只需「和内容制作知识相关」的得分,用 SQL JSON_EXTRACT 直取这一个标量,
  679. # 避免把整块 llm_evaluation(本库 ~1.5MB)拉到 Python 再解析。得分可能直接是数字,
  680. # 也可能裹在 {"得分": x} 里,COALESCE 两条路径覆盖两种存法,口径同 is_adopted。
  681. _REL_SQL = ("JSON_UNQUOTE(COALESCE("
  682. "JSON_EXTRACT(llm_evaluation,'$.\"相关性\".\"和内容制作知识相关\".\"得分\"'),"
  683. "JSON_EXTRACT(llm_evaluation,'$.\"相关性\".\"和内容制作知识相关\"')))")
  684. # 可复现/实现门槛标量直取(口径同 is_adopted 的 _repro_score):兼容新旧 schema——
  685. # 旧版「质量.固定维度.可复现性」,新版「质量.动态维度.工序.字段完整性.实现完整性」,COALESCE 依次回退。
  686. _REPRO_SQL = ("JSON_UNQUOTE(COALESCE("
  687. "JSON_EXTRACT(llm_evaluation,'$.\"质量\".\"固定维度\".\"可复现性\".\"得分\"'),"
  688. "JSON_EXTRACT(llm_evaluation,'$.\"质量\".\"固定维度\".\"可复现性\"'),"
  689. "JSON_EXTRACT(llm_evaluation,'$.\"质量\".\"动态维度\".\"工序\".\"字段完整性\".\"实现完整性\".\"得分\"'),"
  690. "JSON_EXTRACT(llm_evaluation,'$.\"质量\".\"动态维度\".\"工序\".\"字段完整性\".\"实现完整性\"')))")
  691. def fetch_adopted_process_cases(query_id=None):
  692. """返回「已采纳且有工序解构」的 case_id 列表(供知识上传脚本用)。
  693. 采纳是帖子级属性(评估存在 search_process),工序解构存在 mode_process,故二者 JOIN:
  694. 只取两边都有的 case,再用 is_adopted_rel(口径同 Dashboard)在 Python 侧过滤。
  695. relevance 得分由 _REL_SQL 直取标量,不传整块 llm_evaluation。
  696. query_id 给定时只看该搜索任务下的 case。返回去重、按 case_id 排序的列表。
  697. """
  698. sql = (f"SELECT DISTINCT s.case_id, s.overall_score, s.publish_time, "
  699. f"{_REL_SQL} AS rel, {_REPRO_SQL} AS repro "
  700. "FROM search_process s "
  701. "JOIN (SELECT DISTINCT case_id FROM mode_process) m ON s.case_id = m.case_id")
  702. params = ()
  703. if query_id:
  704. sql += " WHERE s.query_id=%s"
  705. params = (query_id,)
  706. conn = _conn()
  707. try:
  708. with conn.cursor() as cur:
  709. cur.execute(sql, params)
  710. rows = cur.fetchall()
  711. finally:
  712. conn.close()
  713. cases = [r["case_id"] for r in rows
  714. if is_adopted_rel(r["overall_score"], r["rel"], r["publish_time"], r["repro"])]
  715. return sorted(set(cases))
  716. # ── 评估去重:复用 query 无关分,只重算 query 相关分(search_eval.py 用)──────────
  717. def fetch_existing_eval(case_id, table="search_process"):
  718. """返回该 case 在搜索表里最近一条「有效」评估 blob(任意 query)。
  719. 评估去重用:同帖在别的相似 query 下评过时,复用其 query 无关分(质量/通用相关/时效),
  720. 只重算「和 query 相关」。无有效评估(全是 _error 或没评过)返回 None。
  721. 取最近若干条逐一挑出首个非 error、结构完整的 blob。"""
  722. table = _search_table(table)
  723. conn = _conn()
  724. try:
  725. with conn.cursor() as cur:
  726. cur.execute(f"""SELECT llm_evaluation FROM {table}
  727. WHERE case_id=%s AND llm_evaluation IS NOT NULL
  728. ORDER BY updated_at DESC, id DESC LIMIT 5""", (case_id,))
  729. rows = cur.fetchall()
  730. finally:
  731. conn.close()
  732. for r in rows:
  733. e = _loads(r["llm_evaluation"])
  734. if isinstance(e, dict) and not e.get("_error") and isinstance(e.get("相关性"), dict):
  735. return e
  736. return None
  737. def update_post_eval(query_id, case_id, evaluation, table="search_process"):
  738. """用新的评估 blob 覆盖某 (query, case) 行的 llm_evaluation,并同步重算派生列
  739. overall_score、knowledge_type(口径同 upsert_search_posts)。返回受影响行数。"""
  740. table = _search_table(table)
  741. overall = overall_score(evaluation)
  742. ktype = evaluation.get("知识类型") if isinstance(evaluation, dict) else None
  743. conn = _conn()
  744. try:
  745. with conn.cursor() as cur:
  746. n = cur.execute(
  747. f"UPDATE {table} SET llm_evaluation=%s, overall_score=%s, knowledge_type=%s "
  748. "WHERE query_id=%s AND case_id=%s",
  749. (_j(evaluation), overall, _j(ktype), query_id, case_id))
  750. return n
  751. finally:
  752. conn.close()
  753. # ── 上传去重:知识库已导入台账(import_process_knowledge.py 用)────────────────
  754. def fetch_ingested_map(case_id):
  755. """返回 {proc_index: version} —— 该 case 各工序已导入知识库的版本。空表示没传过。"""
  756. conn = _conn()
  757. try:
  758. with conn.cursor() as cur:
  759. cur.execute("SELECT proc_index, version FROM knowledge_ingest_log WHERE case_id=%s",
  760. (case_id,))
  761. return {r["proc_index"]: r["version"] for r in cur.fetchall()}
  762. finally:
  763. conn.close()
  764. def mark_ingested(case_id, proc_index, version, knowledge_id=None, api_url=None):
  765. """记一条「已导入」台账(case_id+proc_index 唯一,重导同序号则更新版本/knowledge_id)。"""
  766. conn = _conn()
  767. try:
  768. with conn.cursor() as cur:
  769. cur.execute("""INSERT INTO knowledge_ingest_log
  770. (case_id, proc_index, version, knowledge_id, api_url)
  771. VALUES (%s,%s,%s,%s,%s)
  772. ON DUPLICATE KEY UPDATE version=VALUES(version),
  773. knowledge_id=VALUES(knowledge_id), api_url=VALUES(api_url)""",
  774. (case_id, proc_index, version, knowledge_id, api_url))
  775. finally:
  776. conn.close()
  777. def fetch_dashboard_rows():
  778. """拉 Dashboard 计算所需的轻量行。数据量级:百~千行,Python 聚合足够。
  779. 优化:① 不传 llm_evaluation 整块,SQL 只取采纳判定要的相关性得分;
  780. ② steps 只取每个 case 的最新版本(覆盖度只看最新版),历史/link_ 版本不传 steps。"""
  781. conn = _conn()
  782. try:
  783. with conn.cursor() as cur:
  784. # 进度分母走「采纳」口径;mode 标方向(工序帖来自 search_process)。
  785. cols = (f"query_id, case_id, platform, overall_score, publish_time, "
  786. f"{_REL_SQL} AS rel, {_REPRO_SQL} AS repro")
  787. cur.execute(f"SELECT {cols} FROM search_process")
  788. posts = cur.fetchall()
  789. for p in posts:
  790. p["mode"] = "process"
  791. cur.execute(f"SELECT {cols} FROM search_tools")
  792. st = cur.fetchall()
  793. for p in st:
  794. p["mode"] = "tools"
  795. posts += st
  796. # 成本/耗时按全部版本计;steps 仅最新版需要 → 非最新版只回 NULL,省传输。
  797. cur.execute("""SELECT p.case_id, p.version, p.cost_usd, p.duration_s, p.created_at,
  798. CASE WHEN p.version = m.maxv THEN p.steps END AS steps
  799. FROM mode_process p
  800. JOIN (SELECT case_id, MAX(version) AS maxv
  801. FROM mode_process GROUP BY case_id) m
  802. ON p.case_id = m.case_id
  803. ORDER BY p.id""")
  804. procs = cur.fetchall()
  805. cur.execute("""SELECT case_id, version, tool_name, substance_scope,
  806. form_scope, cost_usd, duration_s, created_at
  807. FROM mode_tools""")
  808. tools = cur.fetchall()
  809. finally:
  810. conn.close()
  811. for p in posts:
  812. # 采纳判定:口径同帖子列表(is_adopted),作为「需解构」分母依据
  813. p["adopted"] = is_adopted_rel(p["overall_score"], p["rel"], p["publish_time"], p["repro"])
  814. for r in procs:
  815. r["steps"] = _loads(r["steps"], [])
  816. r["cost_usd"] = float(r["cost_usd"]) if r["cost_usd"] is not None else None
  817. r["created_at"] = str(r["created_at"]) if r["created_at"] else None
  818. for r in tools:
  819. r["substance_scope"] = _loads(r["substance_scope"], [])
  820. r["form_scope"] = _loads(r["form_scope"], [])
  821. r["cost_usd"] = float(r["cost_usd"]) if r["cost_usd"] is not None else None
  822. r["created_at"] = str(r["created_at"]) if r["created_at"] else None
  823. return posts, procs, tools
  824. def check():
  825. conn = _conn()
  826. try:
  827. with conn.cursor() as cur:
  828. for t in ("search_process", "search_tools", "mode_process", "mode_tools"):
  829. cur.execute(f"SELECT COUNT(*) AS n FROM {t}")
  830. print(f"{t}: {cur.fetchone()['n']} 行")
  831. finally:
  832. conn.close()
  833. if __name__ == "__main__":
  834. cmd = sys.argv[1] if len(sys.argv) > 1 else ""
  835. if cmd == "init":
  836. init_tables()
  837. elif cmd == "check":
  838. check()
  839. elif cmd == "clear":
  840. clear_tables()
  841. else:
  842. print("用法:\n python db.py init # 建表\n python db.py check # 四表行数\n python db.py clear # 清空四表数据")