db.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  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. seq SMALLINT NULL COMMENT '帖内序号(0-based);与 (query_id,case_id,version) 组唯一键防并发/重复写',
  125. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  126. UNIQUE KEY uk_q_case_ver_seq (query_id, case_id, version, seq),
  127. KEY idx_case_ver (case_id, version),
  128. KEY idx_qid (query_id)
  129. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='工序解构结果(每行一个工序)';
  130. """
  131. DDL_TOOLS = """
  132. CREATE TABLE IF NOT EXISTS mode_tools (
  133. id BIGINT AUTO_INCREMENT PRIMARY KEY,
  134. query_id VARCHAR(32) NOT NULL,
  135. case_id VARCHAR(128) NOT NULL,
  136. platform VARCHAR(32) NULL,
  137. post_title VARCHAR(512) NULL,
  138. source JSON NULL COMMENT '解构时帖子来源块(tool_extract._row_to_source 产出)',
  139. tool_name VARCHAR(255) NULL,
  140. substance_scope JSON NULL COMMENT '实质作用域(数组)',
  141. form_scope JSON NULL COMMENT '形式作用域(数组或null)',
  142. creation_layer VARCHAR(32) NULL COMMENT '制作层/创作层',
  143. source_link VARCHAR(1024) NULL,
  144. input_desc TEXT NULL,
  145. output_desc TEXT NULL,
  146. usage_json JSON NULL,
  147. cases_json JSON NULL,
  148. defects_json JSON NULL,
  149. updated_time VARCHAR(64) NULL COMMENT '工具最新更新时间',
  150. model VARCHAR(64) NULL,
  151. version VARCHAR(32) NULL COMMENT 'v_MMDDHHMM;link_* 为跨 query 复制(cost=0)',
  152. cost_usd DECIMAL(10,6) NULL COMMENT '同 mode_process,聚合按 case+version 去重',
  153. duration_s FLOAT NULL,
  154. seq SMALLINT NULL COMMENT '帖内序号(0-based);与 (query_id,case_id,version) 组唯一键防并发/重复写',
  155. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  156. UNIQUE KEY uk_q_case_ver_seq (query_id, case_id, version, seq),
  157. KEY idx_case_ver (case_id, version),
  158. KEY idx_qid (query_id),
  159. KEY idx_tool_name (tool_name)
  160. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='工具解构结果(每行一个工具)';
  161. """
  162. # 工序知识「已导入知识库」台账:防重复上传(stages/import_process_knowledge.py 用)。
  163. # 每条知识 = 某 case 的某个工序(proc_index 1-based)。记录导入时的 mode_process 版本:
  164. # 版本变了(重解构)说明内容已变,应重导;版本不变即视为「已传过」,跳过。
  165. # 选 DB 台账而非本地文件,是为了换机器/换链接后也不会重复写知识库。
  166. # 注:工具知识用独立的 tools_ingest_log,不与本表混用(case_id 是帖子物理身份,
  167. # 同帖可能既被工序解构又被工具解构,共表会在 (case_id, index) 上撞键)。
  168. DDL_INGEST_LOG = """
  169. CREATE TABLE IF NOT EXISTS knowledge_ingest_log (
  170. id BIGINT AUTO_INCREMENT PRIMARY KEY,
  171. case_id VARCHAR(128) NOT NULL,
  172. proc_index INT NOT NULL COMMENT '工序序号(1-based),对齐导入脚本枚举',
  173. version VARCHAR(32) NULL COMMENT '导入时 mode_process 版本;变了应重导',
  174. knowledge_id VARCHAR(128) NULL COMMENT '接口返回的 knowledge_id',
  175. api_url VARCHAR(255) NULL,
  176. ingested_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  177. updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  178. UNIQUE KEY uk_case_proc (case_id, proc_index)
  179. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='工序知识已导入台账(防重复上传)';
  180. """
  181. # 工具知识「已导入知识库」台账:语义同 knowledge_ingest_log,但针对工具方向独立成表
  182. # (stages/import_tools_knowledge.py 用)。每条知识 = 某 case 的某个工具(tool_index 1-based),
  183. # 版本记录导入时的 mode_tools 版本;变了(重解构)应重导,不变即「已传过」跳过。
  184. DDL_TOOLS_INGEST_LOG = """
  185. CREATE TABLE IF NOT EXISTS tools_ingest_log (
  186. id BIGINT AUTO_INCREMENT PRIMARY KEY,
  187. case_id VARCHAR(128) NOT NULL,
  188. tool_index INT NOT NULL COMMENT '工具序号(1-based),对齐导入脚本枚举',
  189. version VARCHAR(32) NULL COMMENT '导入时 mode_tools 版本;变了应重导',
  190. knowledge_id VARCHAR(128) NULL COMMENT '接口返回的 knowledge_id',
  191. api_url VARCHAR(255) NULL,
  192. ingested_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  193. updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  194. UNIQUE KEY uk_case_tool (case_id, tool_index)
  195. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='工具知识已导入台账(防重复上传)';
  196. """
  197. def _ensure_column(cur, table, column, column_ddl):
  198. """给已存在的表幂等补列:列已存在则跳过(MySQL ADD COLUMN 无 IF NOT EXISTS)。
  199. column_ddl 为 ADD COLUMN 后的完整定义,如 \"source JSON NULL ... AFTER post_title\"。"""
  200. cur.execute("""SELECT COUNT(*) AS n FROM information_schema.columns
  201. WHERE table_schema=DATABASE() AND table_name=%s AND column_name=%s""",
  202. (table, column))
  203. if cur.fetchone()["n"] == 0:
  204. cur.execute(f"ALTER TABLE {table} ADD COLUMN {column_ddl}")
  205. def _ensure_unique_index(cur, table, index_name, cols):
  206. """幂等加唯一索引:已存在则跳过(MySQL ADD INDEX 无 IF NOT EXISTS)。
  207. cols 为列表达式,如 "query_id, case_id, version, seq"。加之前需保证无冲突数据。"""
  208. cur.execute("""SELECT COUNT(*) AS n FROM information_schema.statistics
  209. WHERE table_schema=DATABASE() AND table_name=%s AND index_name=%s""",
  210. (table, index_name))
  211. if cur.fetchone()["n"] == 0:
  212. cur.execute(f"ALTER TABLE {table} ADD UNIQUE KEY {index_name} ({cols})")
  213. def init_tables():
  214. conn = _conn()
  215. try:
  216. with conn.cursor() as cur:
  217. cur.execute(_ddl_search("search_process", "工序方向"))
  218. cur.execute(_ddl_search("search_tools", "工具方向"))
  219. cur.execute(DDL_PROCESS)
  220. cur.execute(DDL_TOOLS)
  221. cur.execute(DDL_INGEST_LOG)
  222. cur.execute(DDL_TOOLS_INGEST_LOG)
  223. # 历史库迁移:version 由 VARCHAR(16) 放宽到 32,容纳 link_v_mopN_* 复制版本。
  224. # MODIFY 幂等(已是 32 则 MySQL 元数据无操作),建表后表必存在,可安全执行。
  225. for t in ("mode_process", "mode_tools"):
  226. cur.execute(f"ALTER TABLE {t} MODIFY COLUMN version VARCHAR(32) NULL")
  227. # 历史库迁移:给老 mode_tools 补 source 列(MySQL 的 ADD COLUMN 无 IF NOT EXISTS,
  228. # 故先查 information_schema 判存在,缺了才 ADD,幂等)。
  229. _ensure_column(cur, "mode_tools", "source",
  230. "source JSON NULL COMMENT '解构时帖子来源块' AFTER post_title")
  231. # 历史库迁移:加 seq(帖内序号)+ (query_id,case_id,version,seq) 唯一键,防并发/重复
  232. # 写入产生重复行。顺序必须是 加列 → 回填 → 加唯一键。MySQL 5.7 无窗口函数,seq 在
  233. # 应用层按 (query_id,case_id,version) 内 id 升序回填(现有数据该粒度已无重复)。
  234. for t in ("mode_process", "mode_tools"):
  235. _ensure_column(cur, t, "seq",
  236. "seq SMALLINT NULL COMMENT '帖内序号(0-based)' AFTER duration_s")
  237. for t in ("mode_process", "mode_tools"):
  238. cur.execute(f"""SELECT id, query_id, case_id, version FROM {t}
  239. WHERE seq IS NULL ORDER BY query_id, case_id, version, id""")
  240. key, n, ups = None, 0, []
  241. for r in cur.fetchall():
  242. k = (r["query_id"], r["case_id"], r["version"])
  243. if k != key:
  244. key, n = k, 0
  245. ups.append((n, r["id"])); n += 1
  246. if ups:
  247. cur.executemany(f"UPDATE {t} SET seq=%s WHERE id=%s", ups)
  248. print(f" ↳ {t}: 回填 seq {len(ups)} 行")
  249. for t in ("mode_process", "mode_tools"):
  250. _ensure_unique_index(cur, t, "uk_q_case_ver_seq",
  251. "query_id, case_id, version, seq")
  252. print("✅ 建表完成:search_process, search_tools, mode_process, mode_tools, "
  253. "knowledge_ingest_log, tools_ingest_log")
  254. finally:
  255. conn.close()
  256. def clear_tables():
  257. """清空四张表的数据(TRUNCATE,表结构保留)。"""
  258. conn = _conn()
  259. try:
  260. with conn.cursor() as cur:
  261. for t in ("search_process", "search_tools", "mode_process", "mode_tools"):
  262. cur.execute(f"TRUNCATE TABLE {t}")
  263. print(f"🧹 已清空 {t}")
  264. finally:
  265. conn.close()
  266. # ── 工具函数 ──────────────────────────────────────────────────────────────────
  267. def _loads(v, default=None):
  268. """pymysql 的 JSON 列可能返回字符串,统一解析。"""
  269. if v is None:
  270. return default
  271. if isinstance(v, (list, dict)):
  272. return v
  273. try:
  274. return json.loads(v)
  275. except Exception:
  276. return default
  277. def _j(v):
  278. """写入 JSON 列:None 保持 NULL,其余 dumps。"""
  279. return None if v is None else json.dumps(v, ensure_ascii=False)
  280. def _collect_scores(node):
  281. """递归收集嵌套评估里所有「得分」。LLM 直出的得分多为字符串("1"/"4"),
  282. 个别为数字(如 时效性 10),统一按 float 解析;非数值(如 "N/A")跳过不计入。"""
  283. out = []
  284. if isinstance(node, dict):
  285. for k, v in node.items():
  286. if k == "得分":
  287. try:
  288. out.append(float(v))
  289. except (TypeError, ValueError):
  290. pass
  291. else:
  292. out.extend(_collect_scores(v))
  293. elif isinstance(node, list):
  294. for v in node:
  295. out.extend(_collect_scores(v))
  296. return out
  297. def overall_score(e):
  298. """综合分 = (相关性各项均值 + 质量各项均值) / 可得部分数。算不出返回 None。"""
  299. parts = []
  300. for key in ("相关性", "质量"):
  301. scores = _collect_scores((e or {}).get(key))
  302. if scores:
  303. parts.append(sum(scores) / len(scores))
  304. return round(sum(parts) / len(parts), 2) if parts else None
  305. def _recency_hard(date_str):
  306. """硬时效(同 mode_procedure/server.py:_recency_hard):半年内=3 / 两年内=2 / 更早=1。
  307. publish_time 头 10 字符按 YYYY-MM-DD 解析,失败返回 None(不参与判定)。"""
  308. try:
  309. d = datetime.strptime(str(date_str or "")[:10], "%Y-%m-%d")
  310. except (ValueError, TypeError):
  311. return None
  312. days = (datetime.now() - d).days
  313. if days <= 180:
  314. return 3
  315. if days <= 730:
  316. return 2
  317. return 1
  318. def _fixed_dim_score(evaluation, name):
  319. """取 质量.固定维度.<name>.得分 标量,缺失/非数值返回 None(不参与判定)。"""
  320. v = (((evaluation or {}).get("质量") or {}).get("固定维度") or {}).get(name)
  321. if isinstance(v, dict):
  322. v = v.get("得分")
  323. try:
  324. return float(v) if v is not None else None
  325. except (TypeError, ValueError):
  326. return None
  327. def _impl_score(evaluation):
  328. """取 质量.动态维度.工序.字段完整性.实现完整性.得分 标量,缺失/非数值返回 None。
  329. 新版 prompt 把旧「可复现性」的硬封顶规则并入了「实现完整性」,故采纳门槛改读此处。"""
  330. v = ((((((evaluation or {}).get("质量") or {}).get("动态维度") or {})
  331. .get("工序") or {}).get("字段完整性") or {}).get("实现完整性"))
  332. if isinstance(v, dict):
  333. v = v.get("得分")
  334. try:
  335. return float(v) if v is not None else None
  336. except (TypeError, ValueError):
  337. return None
  338. def _repro_score(evaluation):
  339. """采纳门槛用的「可复现/可实现」得分:优先旧版「可复现性」(固定维度),
  340. 缺失则回退新版「实现完整性」(动态维度.工序)。这样新旧两套评估 blob 都能正确判定。"""
  341. v = _fixed_dim_score(evaluation, "可复现性")
  342. return v if v is not None else _impl_score(evaluation)
  343. def is_adopted(overall, evaluation, publish_time):
  344. """采纳/命中判定,口径对齐 mode_procedure 的 decision=="report":
  345. 制作相关性<4、可复现/实现完整性<4、发布超两年、综合分<6 —— 任一命中即不采纳;指标缺失不参与判定。
  346. (意图可控性暂只采分不设门槛,留待阈值标定后再开。)
  347. 可复现/实现门槛兼容新旧 schema:旧版读「可复现性」,新版读「实现完整性」(见 _repro_score)。
  348. fail-closed:评估失败(_error)、blob 缺失/为空、或综合分算不出(None)→ 直接判不采纳。
  349. 评不出的帖子不该混进命中集(此前 fail-open 会因各指标取不到值而误判采纳)。"""
  350. if not isinstance(evaluation, dict) or not evaluation or evaluation.get("_error"):
  351. return False
  352. if overall is None:
  353. return False
  354. rel = None
  355. v = ((evaluation or {}).get("相关性") or {}).get("和内容制作知识相关")
  356. if isinstance(v, dict):
  357. v = v.get("得分")
  358. try:
  359. rel = float(v) if v is not None else None
  360. except (TypeError, ValueError):
  361. rel = None
  362. if rel is not None and rel < 4:
  363. return False
  364. repro = _repro_score(evaluation)
  365. if repro is not None and repro < 4:
  366. return False
  367. rh = _recency_hard(publish_time)
  368. if rh is not None and rh < 2:
  369. return False
  370. if overall is not None and float(overall) < 6:
  371. return False
  372. return True
  373. def is_adopted_rel(overall, rel, publish_time, repro=None):
  374. """is_adopted 的轻量版:相关性得分(rel)、可复现/实现门槛(repro)已由 SQL JSON_EXTRACT
  375. 直接取出(repro 由 _REPRO_SQL 兼容新旧 schema 取值),无需传输/解析整块 llm_evaluation。
  376. 判定口径与 is_adopted 完全一致(含 fail-closed:综合分算不出→不采纳;失败帖的 overall_score 列为 NULL)。"""
  377. if overall is None:
  378. return False
  379. try:
  380. rel = float(rel) if rel is not None else None
  381. except (TypeError, ValueError):
  382. rel = None
  383. if rel is not None and rel < 4:
  384. return False
  385. try:
  386. repro = float(repro) if repro is not None else None
  387. except (TypeError, ValueError):
  388. repro = None
  389. if repro is not None and repro < 4:
  390. return False
  391. rh = _recency_hard(publish_time)
  392. if rh is not None and rh < 2:
  393. return False
  394. if overall is not None and float(overall) < 6:
  395. return False
  396. return True
  397. # ── search_process / search_tools ────────────────────────────────────────────
  398. def upsert_search_posts(query_id, query_text, results, table="search_process"):
  399. """一组搜索结果写入指定搜索表(按 (query_id, case_id) upsert)。返回写入条数。
  400. table:search_process(工序方向) / search_tools(工具方向)。"""
  401. table = _search_table(table)
  402. if not results:
  403. return 0
  404. rows = []
  405. for r in results:
  406. post = r.get("post") or {}
  407. e = r.get("llm_evaluation") or {}
  408. rows.append((
  409. query_id, query_text, r.get("case_id"), r.get("platform"),
  410. r.get("channel_content_id"),
  411. (post.get("title") or post.get("desc") or "")[:500],
  412. r.get("source_url"), post.get("content_type"),
  413. post.get("body_text") or post.get("desc") or "",
  414. _j(post.get("images") or []), _j(post.get("videos") or []),
  415. post.get("like_count"),
  416. str(post.get("publish_time") or post.get("publish_timestamp") or "")[:64],
  417. post.get("_quality_score"), post.get("_quality_grade"),
  418. _j(r.get("found_by_queries") or []),
  419. _j(e.get("知识类型") or []),
  420. overall_score(e),
  421. _j(e),
  422. ))
  423. sql = f"""
  424. INSERT INTO {table}
  425. (query_id, query_text, case_id, platform, channel_content_id, title, url,
  426. content_type, body, images, videos, like_count, publish_time,
  427. quality_score, quality_grade, found_by, knowledge_type,
  428. overall_score, llm_evaluation)
  429. VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
  430. ON DUPLICATE KEY UPDATE
  431. query_text=VALUES(query_text), platform=VALUES(platform),
  432. channel_content_id=VALUES(channel_content_id), title=VALUES(title), url=VALUES(url),
  433. content_type=VALUES(content_type), body=VALUES(body), images=VALUES(images),
  434. videos=VALUES(videos), like_count=VALUES(like_count), publish_time=VALUES(publish_time),
  435. quality_score=VALUES(quality_score), quality_grade=VALUES(quality_grade),
  436. found_by=VALUES(found_by), knowledge_type=VALUES(knowledge_type),
  437. overall_score=VALUES(overall_score), llm_evaluation=VALUES(llm_evaluation);
  438. """
  439. conn = _conn()
  440. try:
  441. with conn.cursor() as cur:
  442. cur.executemany(sql, rows)
  443. return len(rows)
  444. finally:
  445. conn.close()
  446. def fetch_queries(mode="process"):
  447. """某方向搜索表的 query 列表 + 帖子数 + 采纳/命中数 + 解构进度。"""
  448. table = _search_table(mode)
  449. conn = _conn()
  450. try:
  451. with conn.cursor() as cur:
  452. cur.execute(f"""SELECT query_id, MAX(query_text) AS query_text,
  453. COUNT(*) AS post_count
  454. FROM {table} GROUP BY query_id ORDER BY query_id""")
  455. queries = cur.fetchall()
  456. cur.execute(f"""SELECT query_id, overall_score, llm_evaluation, publish_time
  457. FROM {table}""")
  458. hits = {}
  459. for r in cur.fetchall():
  460. if is_adopted(r["overall_score"], _loads(r["llm_evaluation"]), r["publish_time"]):
  461. hits[r["query_id"]] = hits.get(r["query_id"], 0) + 1
  462. cur.execute("SELECT query_id, COUNT(DISTINCT case_id) AS n FROM mode_process GROUP BY query_id")
  463. np = {r["query_id"]: r["n"] for r in cur.fetchall()}
  464. cur.execute("SELECT query_id, COUNT(DISTINCT case_id) AS n FROM mode_tools GROUP BY query_id")
  465. nt = {r["query_id"]: r["n"] for r in cur.fetchall()}
  466. finally:
  467. conn.close()
  468. for q in queries:
  469. q["hit_count"] = hits.get(q["query_id"], 0)
  470. q["process_done"] = np.get(q["query_id"], 0)
  471. q["tools_done"] = nt.get(q["query_id"], 0)
  472. return queries
  473. def fetch_posts(query_id, mode="process"):
  474. """某方向搜索表里某 query 的全部帖子(JSON 列已解析),带 has_process/has_tools 标记。"""
  475. table = _search_table(mode)
  476. conn = _conn()
  477. try:
  478. with conn.cursor() as cur:
  479. cur.execute(f"""SELECT * FROM {table} WHERE query_id=%s
  480. ORDER BY overall_score DESC, id""", (query_id,))
  481. rows = cur.fetchall()
  482. cur.execute("SELECT DISTINCT case_id FROM mode_process WHERE query_id=%s", (query_id,))
  483. hp = {r["case_id"] for r in cur.fetchall()}
  484. cur.execute("SELECT DISTINCT case_id FROM mode_tools WHERE query_id=%s", (query_id,))
  485. ht = {r["case_id"] for r in cur.fetchall()}
  486. finally:
  487. conn.close()
  488. for r in rows:
  489. for col in ("images", "videos", "found_by", "knowledge_type", "llm_evaluation"):
  490. r[col] = _loads(r[col])
  491. r["adopted"] = is_adopted(r["overall_score"], r["llm_evaluation"], r["publish_time"])
  492. r["has_process"] = r["case_id"] in hp
  493. r["has_tools"] = r["case_id"] in ht
  494. r.pop("created_at", None); r.pop("updated_at", None)
  495. return rows
  496. def fetch_post(query_id, case_id, table="search_process"):
  497. """指定搜索表的单帖完整行(给 pipeline 脚本重建 source 用)。无则 None。"""
  498. table = _search_table(table)
  499. conn = _conn()
  500. try:
  501. with conn.cursor() as cur:
  502. cur.execute(f"SELECT * FROM {table} WHERE query_id=%s AND case_id=%s",
  503. (query_id, case_id))
  504. row = cur.fetchone()
  505. finally:
  506. conn.close()
  507. if not row:
  508. return None
  509. for col in ("images", "videos", "found_by", "knowledge_type", "llm_evaluation"):
  510. row[col] = _loads(row[col])
  511. return row
  512. # ── mode_process ─────────────────────────────────────────────────────────────
  513. def replace_process(query_id, case_id, platform, post_title, payload,
  514. model, version, cost_usd, duration_s):
  515. """写入一帖某版本的工序解构结果(payload = {source, procedures})。
  516. 删 (case_id, version) 旧行再插,同版本重跑幂等、跨版本保留历史。返回工序条数。"""
  517. source = payload.get("source")
  518. procedures = payload.get("procedures") or []
  519. conn = _conn()
  520. try:
  521. conn.begin() # DELETE+INSERT 原子化:配合 uk_q_case_ver_seq,并发/重复写入不会留下重复行
  522. with conn.cursor() as cur:
  523. cur.execute("DELETE FROM mode_process WHERE case_id=%s AND version=%s",
  524. (case_id, version))
  525. if procedures:
  526. rows = []
  527. for i, p in enumerate(procedures):
  528. steps = p.get("steps") or []
  529. vias = []
  530. for s in steps:
  531. v = s.get("via")
  532. if v and v not in vias:
  533. vias.append(v)
  534. rows.append((
  535. query_id, case_id, platform, (post_title or "")[:500],
  536. _j(source), p.get("id"), (p.get("name") or "")[:250],
  537. p.get("purpose"), p.get("category"),
  538. _j(p.get("declarations")), _j(p.get("type_registry")),
  539. _j(steps), len(steps), _j(vias),
  540. model, version, cost_usd, duration_s, i,
  541. ))
  542. cur.executemany("""
  543. INSERT INTO mode_process
  544. (query_id, case_id, platform, post_title, source, procedure_id, name,
  545. purpose, category, declarations, type_registry, steps, step_count,
  546. tools_used, model, version, cost_usd, duration_s, seq)
  547. VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
  548. """, rows)
  549. conn.commit()
  550. return len(procedures)
  551. except Exception:
  552. conn.rollback()
  553. raise
  554. finally:
  555. conn.close()
  556. def fetch_process_versions(case_id):
  557. conn = _conn()
  558. try:
  559. with conn.cursor() as cur:
  560. cur.execute("""SELECT version, COUNT(*) AS n, MAX(model) AS model
  561. FROM mode_process WHERE case_id=%s
  562. GROUP BY version
  563. ORDER BY (LEFT(version,5)='link_') ASC, MAX(id) DESC""", (case_id,))
  564. return cur.fetchall()
  565. finally:
  566. conn.close()
  567. def fetch_process(case_id, version=None):
  568. """重建 {case_id, version, model, source, procedures:[...]}。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_process WHERE case_id=%s
  574. ORDER BY (LEFT(version,5)='link_') ASC, 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_process 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 _proc_payload(case_id, version, rows)
  585. def _proc_payload(case_id, version, rows):
  586. """mode_process 行集 → {case_id, version, …, procedures:[...]}。无行返回 None。"""
  587. if not rows:
  588. return None
  589. procedures = [{
  590. "id": r["procedure_id"], "name": r["name"], "purpose": r["purpose"],
  591. "category": r["category"], "declarations": _loads(r["declarations"]),
  592. "type_registry": _loads(r["type_registry"]), "steps": _loads(r["steps"], []),
  593. "tools_used": _loads(r["tools_used"], []),
  594. } for r in rows]
  595. return {"case_id": case_id, "version": version, "platform": rows[0]["platform"],
  596. "title": rows[0]["post_title"], "model": rows[0]["model"],
  597. "cost_usd": float(rows[0]["cost_usd"]) if rows[0]["cost_usd"] is not None else None,
  598. "duration_s": rows[0]["duration_s"],
  599. "source": _loads(rows[0]["source"]), "procedures": procedures}
  600. # ── mode_tools ───────────────────────────────────────────────────────────────
  601. def replace_tools(query_id, case_id, platform, post_title, tools,
  602. model, version, cost_usd, duration_s, source=None):
  603. """写入一帖某版本的工具解构结果。语义同 replace_process。返回工具条数。
  604. source:帖子来源块(同 mode_process,每行重复存),供知识上传脚本重建 source 用。"""
  605. src = _j(source)
  606. conn = _conn()
  607. try:
  608. conn.begin() # DELETE+INSERT 原子化:配合 uk_q_case_ver_seq,并发/重复写入不会留下重复行
  609. with conn.cursor() as cur:
  610. cur.execute("DELETE FROM mode_tools WHERE case_id=%s AND version=%s",
  611. (case_id, version))
  612. if tools:
  613. rows = [(
  614. query_id, case_id, platform, (post_title or "")[:500], src,
  615. (t.get("工具名称") or "")[:250],
  616. _j(t.get("实质作用域")), _j(t.get("形式作用域")),
  617. t.get("创作层级"), t.get("来源链接"), t.get("输入"), t.get("输出"),
  618. _j(t.get("用法")), _j(t.get("案例")), _j(t.get("缺点")),
  619. t.get("最新更新时间"), model, version, cost_usd, duration_s, i,
  620. ) for i, t in enumerate(tools)]
  621. cur.executemany("""
  622. INSERT INTO mode_tools
  623. (query_id, case_id, platform, post_title, source, tool_name, substance_scope,
  624. form_scope, creation_layer, source_link, input_desc, output_desc,
  625. usage_json, cases_json, defects_json, updated_time, model, version,
  626. cost_usd, duration_s, seq)
  627. VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
  628. """, rows)
  629. conn.commit()
  630. return len(tools)
  631. except Exception:
  632. conn.rollback()
  633. raise
  634. finally:
  635. conn.close()
  636. def fetch_tools_versions(case_id):
  637. conn = _conn()
  638. try:
  639. with conn.cursor() as cur:
  640. cur.execute("""SELECT version, COUNT(*) AS n, MAX(model) AS model
  641. FROM mode_tools WHERE case_id=%s
  642. GROUP BY version
  643. ORDER BY (LEFT(version,5)='link_') ASC, MAX(id) DESC""", (case_id,))
  644. return cur.fetchall()
  645. finally:
  646. conn.close()
  647. def fetch_tools(case_id, version=None):
  648. """重建 {case_id, version, model, tool_count, tools:[...]}。version=None 取最新。"""
  649. conn = _conn()
  650. try:
  651. with conn.cursor() as cur:
  652. if version is None:
  653. cur.execute("""SELECT version FROM mode_tools WHERE case_id=%s
  654. ORDER BY (LEFT(version,5)='link_') ASC, id DESC LIMIT 1""", (case_id,))
  655. row = cur.fetchone()
  656. if not row:
  657. return None
  658. version = row["version"]
  659. cur.execute("""SELECT * FROM mode_tools WHERE case_id=%s AND version=%s
  660. ORDER BY id""", (case_id, version))
  661. rows = cur.fetchall()
  662. finally:
  663. conn.close()
  664. return _tools_payload(case_id, version, rows)
  665. def _tools_payload(case_id, version, rows):
  666. """mode_tools 行集 → {case_id, version, …, tools:[...]}。无行返回 None。"""
  667. if not rows:
  668. return None
  669. tools = [{
  670. "工具名称": r["tool_name"], "实质作用域": _loads(r["substance_scope"]),
  671. "形式作用域": _loads(r["form_scope"]), "创作层级": r["creation_layer"],
  672. "来源链接": r["source_link"], "输入": r["input_desc"], "输出": r["output_desc"],
  673. "用法": _loads(r["usage_json"]), "案例": _loads(r["cases_json"]),
  674. "缺点": _loads(r["defects_json"]), "最新更新时间": r["updated_time"],
  675. } for r in rows]
  676. return {"case_id": case_id, "version": version, "platform": rows[0]["platform"],
  677. "title": rows[0]["post_title"], "model": rows[0]["model"],
  678. "cost_usd": float(rows[0]["cost_usd"]) if rows[0]["cost_usd"] is not None else None,
  679. "duration_s": rows[0]["duration_s"],
  680. "source": _loads(rows[0].get("source")),
  681. "tool_count": len(tools), "tools": tools}
  682. # ── 点击帖子合一查询(单连接,最少往返;远程 RDS 每次往返 ~80ms,故按次数优化)──
  683. def fetch_extract(mode, case_id, version=None):
  684. """一次取版本列表 + 解构详情,复用同一条池连接、最少往返。
  685. 返回 {versions, data, missing}。mode: process / tools。"""
  686. is_proc = mode != "tools"
  687. mtable = _mode_table("process" if is_proc else "tools")
  688. conn = _conn()
  689. try:
  690. with conn.cursor() as cur:
  691. cur.execute(f"""SELECT version, COUNT(*) AS n, MAX(model) AS model
  692. FROM {mtable} WHERE case_id=%s
  693. GROUP BY version
  694. ORDER BY (LEFT(version,5)='link_') ASC, MAX(id) DESC""", (case_id,))
  695. versions = cur.fetchall()
  696. # 详情:把"取最新版本"折进同一条 SQL,版本指定时直接用;省一次往返。
  697. target = version or (versions[0]["version"] if versions else None)
  698. rows = []
  699. if target is not None:
  700. cur.execute(f"SELECT * FROM {mtable} WHERE case_id=%s AND version=%s ORDER BY id",
  701. (case_id, target))
  702. rows = cur.fetchall()
  703. finally:
  704. conn.close()
  705. payload = (_proc_payload if is_proc else _tools_payload)(case_id, target, rows)
  706. return {"versions": versions, "data": payload, "missing": payload is None}
  707. # ── 跨 query 去重 / link 复制(方案A:解构前先去重,避免重复花钱)──────────────
  708. # case_id 是帖子物理身份(platform_channelContentId),与 query 无关。同一帖被多个
  709. # query 搜到时只需真实解构一次;其余 query 用 link_* 复制行补齐关联(cost=0)。
  710. def latest_real_version(case_id, mode="process"):
  711. """该 case 是否已有「真实」解构(任意 query;link_* 是复制品,不算源)。
  712. 返回最新一行 {"version","query_id"} 或 None。给解构前去重判定用。"""
  713. table = _mode_table(mode)
  714. conn = _conn()
  715. try:
  716. with conn.cursor() as cur:
  717. cur.execute(f"""SELECT version, query_id FROM {table}
  718. WHERE case_id=%s AND LEFT(version,5) <> 'link_'
  719. ORDER BY id DESC LIMIT 1""", (case_id,))
  720. return cur.fetchone()
  721. finally:
  722. conn.close()
  723. def link_process(query_id, case_id, mode="process"):
  724. """把 case 在别处最新「真实」版本的解构行复制到目标 query
  725. (version='link_'+源版本, cost_usd=0)。幂等(先删目标同版本)。
  726. 返回复制行数;该 case 从未真实解构过则返回 0(无源可复制)。"""
  727. table = _mode_table(mode)
  728. conn = _conn()
  729. try:
  730. with conn.cursor() as cur:
  731. cur.execute(f"""SELECT version FROM {table}
  732. WHERE case_id=%s AND LEFT(version,5) <> 'link_'
  733. ORDER BY id DESC LIMIT 1""", (case_id,))
  734. r = cur.fetchone()
  735. if not r:
  736. return 0
  737. srcver = r["version"]
  738. newver = ("link_" + srcver)[:32] # version 列 VARCHAR(32)
  739. # 复制除自增 id / 时间戳外的全部列,改写 query_id / version / cost。
  740. cur.execute(f"SHOW COLUMNS FROM {table}")
  741. cols = [c["Field"] for c in cur.fetchall()
  742. if c["Field"] not in ("id", "created_at", "updated_at")]
  743. cur.execute(f"SELECT {','.join(cols)} FROM {table} WHERE case_id=%s AND version=%s",
  744. (case_id, srcver))
  745. rows = cur.fetchall()
  746. cur.execute(f"DELETE FROM {table} WHERE query_id=%s AND case_id=%s AND version=%s",
  747. (query_id, case_id, newver))
  748. for row in rows:
  749. row = dict(row)
  750. row["query_id"] = query_id
  751. row["version"] = newver
  752. row["cost_usd"] = 0
  753. cur.execute(
  754. f"INSERT INTO {table} ({','.join(cols)}) VALUES ({','.join(['%s']*len(cols))})",
  755. [row[k] for k in cols])
  756. return len(rows)
  757. finally:
  758. conn.close()
  759. # ── Dashboard 原始行(指标计算在 server.py)─────────────────────────────────────
  760. # 采纳判定只需「和内容制作知识相关」的得分,用 SQL JSON_EXTRACT 直取这一个标量,
  761. # 避免把整块 llm_evaluation(本库 ~1.5MB)拉到 Python 再解析。得分可能直接是数字,
  762. # 也可能裹在 {"得分": x} 里,COALESCE 两条路径覆盖两种存法,口径同 is_adopted。
  763. _REL_SQL = ("JSON_UNQUOTE(COALESCE("
  764. "JSON_EXTRACT(llm_evaluation,'$.\"相关性\".\"和内容制作知识相关\".\"得分\"'),"
  765. "JSON_EXTRACT(llm_evaluation,'$.\"相关性\".\"和内容制作知识相关\"')))")
  766. # 可复现/实现门槛标量直取(口径同 is_adopted 的 _repro_score):兼容新旧 schema——
  767. # 旧版「质量.固定维度.可复现性」,新版「质量.动态维度.工序.字段完整性.实现完整性」,COALESCE 依次回退。
  768. _REPRO_SQL = ("JSON_UNQUOTE(COALESCE("
  769. "JSON_EXTRACT(llm_evaluation,'$.\"质量\".\"固定维度\".\"可复现性\".\"得分\"'),"
  770. "JSON_EXTRACT(llm_evaluation,'$.\"质量\".\"固定维度\".\"可复现性\"'),"
  771. "JSON_EXTRACT(llm_evaluation,'$.\"质量\".\"动态维度\".\"工序\".\"字段完整性\".\"实现完整性\".\"得分\"'),"
  772. "JSON_EXTRACT(llm_evaluation,'$.\"质量\".\"动态维度\".\"工序\".\"字段完整性\".\"实现完整性\"')))")
  773. def fetch_adopted_process_cases(query_id=None):
  774. """返回「已采纳且有工序解构」的 case_id 列表(供知识上传脚本用)。
  775. 采纳是帖子级属性(评估存在 search_process),工序解构存在 mode_process,故二者 JOIN:
  776. 只取两边都有的 case,再用 is_adopted_rel(口径同 Dashboard)在 Python 侧过滤。
  777. relevance 得分由 _REL_SQL 直取标量,不传整块 llm_evaluation。
  778. query_id 给定时只看该搜索任务下的 case。返回去重、按 case_id 排序的列表。
  779. """
  780. sql = (f"SELECT DISTINCT s.case_id, s.overall_score, s.publish_time, "
  781. f"{_REL_SQL} AS rel, {_REPRO_SQL} AS repro "
  782. "FROM search_process s "
  783. "JOIN (SELECT DISTINCT case_id FROM mode_process) m ON s.case_id = m.case_id")
  784. params = ()
  785. if query_id:
  786. sql += " WHERE s.query_id=%s"
  787. params = (query_id,)
  788. conn = _conn()
  789. try:
  790. with conn.cursor() as cur:
  791. cur.execute(sql, params)
  792. rows = cur.fetchall()
  793. finally:
  794. conn.close()
  795. cases = [r["case_id"] for r in rows
  796. if is_adopted_rel(r["overall_score"], r["rel"], r["publish_time"], r["repro"])]
  797. return sorted(set(cases))
  798. def fetch_adopted_tools_cases(query_id=None):
  799. """返回「已采纳且有工具解构」的 case_id 列表(供工具知识上传脚本用)。
  800. 与 fetch_adopted_process_cases 完全同构,只把搜索/解构表换成工具方向:
  801. 采纳是帖子级属性(评估存在 search_tools),工具解构存在 mode_tools,故二者 JOIN,
  802. 只取两边都有的 case,再用 is_adopted_rel(口径同 Dashboard)在 Python 侧过滤。
  803. query_id 给定时只看该搜索任务下的 case。返回去重、按 case_id 排序的列表。
  804. """
  805. sql = (f"SELECT DISTINCT s.case_id, s.overall_score, s.publish_time, "
  806. f"{_REL_SQL} AS rel, {_REPRO_SQL} AS repro "
  807. "FROM search_tools s "
  808. "JOIN (SELECT DISTINCT case_id FROM mode_tools) m ON s.case_id = m.case_id")
  809. params = ()
  810. if query_id:
  811. sql += " WHERE s.query_id=%s"
  812. params = (query_id,)
  813. conn = _conn()
  814. try:
  815. with conn.cursor() as cur:
  816. cur.execute(sql, params)
  817. rows = cur.fetchall()
  818. finally:
  819. conn.close()
  820. cases = [r["case_id"] for r in rows
  821. if is_adopted_rel(r["overall_score"], r["rel"], r["publish_time"], r["repro"])]
  822. return sorted(set(cases))
  823. def route_tables(knowledge_types):
  824. """知识类型标签 → 落表列表(有序去重)。
  825. 工序/能力 → search_process;工具 → search_tools;两者都含写两表;空/None 兜底 search_process。
  826. 评估是统一一套(同一 llm_evaluation blob),故同帖落多表不重复打分,只是多写一行。"""
  827. kt = set(knowledge_types or [])
  828. tables = []
  829. if (kt & {"工序", "能力"}) or not kt:
  830. tables.append("search_process")
  831. if kt & {"工具"}:
  832. tables.append("search_tools")
  833. return tables
  834. # ── 评估去重:复用 query 无关分,只重算 query 相关分(search_eval.py 用)──────────
  835. def fetch_existing_eval(case_id, table="search_process"):
  836. """返回该 case 在搜索表里最近一条「有效」评估 blob(任意 query)。
  837. 评估去重用:同帖在别的相似 query 下评过时,复用其 query 无关分(质量/通用相关/时效),
  838. 只重算「和 query 相关」。无有效评估(全是 _error 或没评过)返回 None。
  839. 取最近若干条逐一挑出首个非 error、结构完整的 blob。"""
  840. table = _search_table(table)
  841. conn = _conn()
  842. try:
  843. with conn.cursor() as cur:
  844. cur.execute(f"""SELECT llm_evaluation FROM {table}
  845. WHERE case_id=%s AND llm_evaluation IS NOT NULL
  846. ORDER BY updated_at DESC, id DESC LIMIT 5""", (case_id,))
  847. rows = cur.fetchall()
  848. finally:
  849. conn.close()
  850. for r in rows:
  851. e = _loads(r["llm_evaluation"])
  852. if isinstance(e, dict) and not e.get("_error") and isinstance(e.get("相关性"), dict):
  853. return e
  854. return None
  855. def fetch_existing_eval_any(case_id):
  856. """跨两张搜索表找该 case 最近一条有效评估 blob。
  857. 评估与表无关(统一一套),任一表评过即可复用,避免同帖在两表各评一次。无则 None。"""
  858. for table in ("search_process", "search_tools"):
  859. e = fetch_existing_eval(case_id, table)
  860. if e:
  861. return e
  862. return None
  863. def update_post_eval(query_id, case_id, evaluation, table="search_process"):
  864. """用新的评估 blob 覆盖某 (query, case) 行的 llm_evaluation,并同步重算派生列
  865. overall_score、knowledge_type(口径同 upsert_search_posts)。返回受影响行数。"""
  866. table = _search_table(table)
  867. overall = overall_score(evaluation)
  868. ktype = evaluation.get("知识类型") if isinstance(evaluation, dict) else None
  869. conn = _conn()
  870. try:
  871. with conn.cursor() as cur:
  872. n = cur.execute(
  873. f"UPDATE {table} SET llm_evaluation=%s, overall_score=%s, knowledge_type=%s "
  874. "WHERE query_id=%s AND case_id=%s",
  875. (_j(evaluation), overall, _j(ktype), query_id, case_id))
  876. return n
  877. finally:
  878. conn.close()
  879. # ── 上传去重:知识库已导入台账(stages/import_process_knowledge.py 用)────────────────
  880. def fetch_ingested_map(case_id):
  881. """返回 {proc_index: version} —— 该 case 各工序已导入知识库的版本。空表示没传过。"""
  882. conn = _conn()
  883. try:
  884. with conn.cursor() as cur:
  885. cur.execute("SELECT proc_index, version FROM knowledge_ingest_log WHERE case_id=%s",
  886. (case_id,))
  887. return {r["proc_index"]: r["version"] for r in cur.fetchall()}
  888. finally:
  889. conn.close()
  890. def mark_ingested(case_id, proc_index, version, knowledge_id=None, api_url=None):
  891. """记一条「已导入」台账(case_id+proc_index 唯一,重导同序号则更新版本/knowledge_id)。"""
  892. conn = _conn()
  893. try:
  894. with conn.cursor() as cur:
  895. cur.execute("""INSERT INTO knowledge_ingest_log
  896. (case_id, proc_index, version, knowledge_id, api_url)
  897. VALUES (%s,%s,%s,%s,%s)
  898. ON DUPLICATE KEY UPDATE version=VALUES(version),
  899. knowledge_id=VALUES(knowledge_id), api_url=VALUES(api_url)""",
  900. (case_id, proc_index, version, knowledge_id, api_url))
  901. finally:
  902. conn.close()
  903. def fetch_tools_ingested_map(case_id):
  904. """返回 {tool_index: version} —— 该 case 各工具已导入知识库的版本。空表示没传过。
  905. 工具方向独立台账(tools_ingest_log),与工序的 knowledge_ingest_log 互不干扰。"""
  906. conn = _conn()
  907. try:
  908. with conn.cursor() as cur:
  909. cur.execute("SELECT tool_index, version FROM tools_ingest_log WHERE case_id=%s",
  910. (case_id,))
  911. return {r["tool_index"]: r["version"] for r in cur.fetchall()}
  912. finally:
  913. conn.close()
  914. def mark_tools_ingested(case_id, tool_index, version, knowledge_id=None, api_url=None):
  915. """记一条工具「已导入」台账(case_id+tool_index 唯一,重导同序号则更新版本/knowledge_id)。"""
  916. conn = _conn()
  917. try:
  918. with conn.cursor() as cur:
  919. cur.execute("""INSERT INTO tools_ingest_log
  920. (case_id, tool_index, version, knowledge_id, api_url)
  921. VALUES (%s,%s,%s,%s,%s)
  922. ON DUPLICATE KEY UPDATE version=VALUES(version),
  923. knowledge_id=VALUES(knowledge_id), api_url=VALUES(api_url)""",
  924. (case_id, tool_index, version, knowledge_id, api_url))
  925. finally:
  926. conn.close()
  927. def fetch_dashboard_rows():
  928. """拉 Dashboard 计算所需的轻量行。数据量级:百~千行,Python 聚合足够。
  929. 优化:① 不传 llm_evaluation 整块,SQL 只取采纳判定要的相关性得分;
  930. ② steps 只取每个 case 的最新版本(覆盖度只看最新版),历史/link_ 版本不传 steps。"""
  931. conn = _conn()
  932. try:
  933. with conn.cursor() as cur:
  934. # 进度分母走「采纳」口径;mode 标方向(工序帖来自 search_process)。
  935. cols = (f"query_id, case_id, platform, overall_score, publish_time, "
  936. f"{_REL_SQL} AS rel, {_REPRO_SQL} AS repro")
  937. cur.execute(f"SELECT {cols} FROM search_process")
  938. posts = cur.fetchall()
  939. for p in posts:
  940. p["mode"] = "process"
  941. cur.execute(f"SELECT {cols} FROM search_tools")
  942. st = cur.fetchall()
  943. for p in st:
  944. p["mode"] = "tools"
  945. posts += st
  946. # 成本/耗时按全部版本计;steps 仅最新版需要 → 非最新版只回 NULL,省传输。
  947. cur.execute("""SELECT p.id, p.case_id, p.version, p.cost_usd, p.duration_s, p.created_at,
  948. CASE WHEN p.version = m.maxv THEN p.steps END AS steps
  949. FROM mode_process p
  950. JOIN (SELECT t.case_id, t.version AS maxv FROM mode_process t
  951. JOIN (SELECT case_id, MAX(id) AS mid FROM mode_process
  952. WHERE LEFT(version,5) <> 'link_' GROUP BY case_id) x
  953. ON t.id = x.mid) m
  954. ON p.case_id = m.case_id
  955. ORDER BY p.id""")
  956. procs = cur.fetchall()
  957. cur.execute("""SELECT id, case_id, version, tool_name, substance_scope,
  958. form_scope, cost_usd, duration_s, created_at
  959. FROM mode_tools""")
  960. tools = cur.fetchall()
  961. finally:
  962. conn.close()
  963. for p in posts:
  964. # 采纳判定:口径同帖子列表(is_adopted),作为「需解构」分母依据
  965. p["adopted"] = is_adopted_rel(p["overall_score"], p["rel"], p["publish_time"], p["repro"])
  966. for r in procs:
  967. r["steps"] = _loads(r["steps"], [])
  968. r["cost_usd"] = float(r["cost_usd"]) if r["cost_usd"] is not None else None
  969. r["created_at"] = str(r["created_at"]) if r["created_at"] else None
  970. for r in tools:
  971. r["substance_scope"] = _loads(r["substance_scope"], [])
  972. r["form_scope"] = _loads(r["form_scope"], [])
  973. r["cost_usd"] = float(r["cost_usd"]) if r["cost_usd"] is not None else None
  974. r["created_at"] = str(r["created_at"]) if r["created_at"] else None
  975. return posts, procs, tools
  976. def check():
  977. conn = _conn()
  978. try:
  979. with conn.cursor() as cur:
  980. for t in ("search_process", "search_tools", "mode_process", "mode_tools"):
  981. cur.execute(f"SELECT COUNT(*) AS n FROM {t}")
  982. print(f"{t}: {cur.fetchone()['n']} 行")
  983. finally:
  984. conn.close()
  985. if __name__ == "__main__":
  986. cmd = sys.argv[1] if len(sys.argv) > 1 else ""
  987. if cmd == "init":
  988. init_tables()
  989. elif cmd == "check":
  990. check()
  991. elif cmd == "clear":
  992. clear_tables()
  993. else:
  994. print("用法:\n python db.py init # 建表\n python db.py check # 四表行数\n python db.py clear # 清空四表数据")