docx_ingest.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. """
  2. DOCX 药典批量导入脚本
  3. 遍历指定目录下所有 DOCX 文件 → 提取药名和 sections → 向量化 → 写入 PostgreSQL
  4. 药品名以文件名(去 .docx)为准
  5. """
  6. import json
  7. import asyncio
  8. import os
  9. import sys
  10. import re
  11. import hashlib
  12. from pathlib import Path
  13. from collections import OrderedDict
  14. import httpx
  15. from docx import Document
  16. from docx.oxml.ns import qn
  17. from sqlalchemy.ext.asyncio import create_async_engine
  18. from sqlalchemy import text
  19. # ============================================
  20. # 配置
  21. # ============================================
  22. SOURCE_DIR = os.environ.get("DOCX_SOURCE_DIR", "/opt/2025")
  23. # 跳过的目录名(非药品内容:凡例、纲要、通则说明等)
  24. SKIP_DIRS = {"索引", "目录", "概述"}
  25. # 从环境变量读取
  26. PG_HOST = os.environ.get("POSTGRES_HOST", "localhost")
  27. PG_PORT = os.environ.get("POSTGRES_PORT", "5432")
  28. PG_DB = os.environ.get("POSTGRES_DB", "pharmacopoeia")
  29. PG_USER = os.environ.get("POSTGRES_USER", "postgres")
  30. PG_PASSWORD = os.environ.get("POSTGRES_PASSWORD", "postgres")
  31. DB_URL = f"postgresql+asyncpg://{PG_USER}:{PG_PASSWORD}@{PG_HOST}:{PG_PORT}/{PG_DB}"
  32. QWEN_API_KEY = os.environ.get("QWEN_API_KEY", "")
  33. EMBEDDING_URL = "https://dashscope.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding"
  34. EMBEDDING_MODEL = "text-embedding-v3"
  35. BATCH_SIZE = 10 # 每批向量化的文本数
  36. # Section 头部关键词 → 标准名称映射
  37. SECTION_HEADERS = OrderedDict([
  38. ("处方", "处方"), ("制法", "制法"), ("性状", "性状"),
  39. ("鉴别", "鉴别"), ("检查", "检查"), ("浸出物", "浸出物"),
  40. ("含量测定", "含量测定"), ("含量", "含量测定"),
  41. ("功能与主治", "功能主治"), ("功能", "功能主治"), ("主治", "功能主治"),
  42. ("用法与用量", "用法用量"), ("用法", "用法用量"), ("用量", "用法用量"),
  43. ("注意", "注意事项"), ("注意事项", "注意事项"),
  44. ("规格", "规格"), ("贮藏", "贮藏"), ("类别", "类别"),
  45. ("制剂", "制剂"), ("附注", "附注"),
  46. ("包装", "包装"), ("有效期", "有效期"),
  47. ("核准日期", "核准日期"), ("修订日期", "修订日期"),
  48. ("执行标准", "执行标准"), ("批准文号", "批准文号"),
  49. ])
  50. # 药典部别映射
  51. VOLUME_MAP = {"output": "一部", "output2": "二部", "output3": "三部", "output4": "四部"}
  52. # 四部子目录 → 具体分类
  53. CATEGORY_OVERRIDE = {
  54. "药用辅料": "药用辅料",
  55. "通用技术要求": "通则",
  56. "指导原则": "通则",
  57. "通用技术要求/指导原则": "通则",
  58. }
  59. def load_env():
  60. env_file = Path(__file__).resolve().parent.parent / ".env"
  61. if env_file.exists():
  62. with open(env_file, encoding="utf-8") as f:
  63. for line in f:
  64. line = line.strip()
  65. if line and not line.startswith("#") and "=" in line:
  66. key, _, val = line.partition("=")
  67. os.environ.setdefault(key.strip(), val.strip())
  68. def _extract_table_text(table) -> str:
  69. """将 python-docx Table 对象转换为可读文本。"""
  70. rows = []
  71. for row in table.rows:
  72. cells = [cell.text.strip() for cell in row.cells]
  73. # 跳过全空行
  74. if any(c for c in cells):
  75. rows.append(" | ".join(cells))
  76. return "\n".join(rows)
  77. def parse_docx(filepath: str) -> dict | None:
  78. """
  79. 解析单个 DOCX 文件为药典条目。
  80. 药品名 = 文件名(去掉 .docx)
  81. 凡例/纲要类:名称加上部别前缀
  82. 按文档顺序遍历段落和表格,表格内容归入当前 section。
  83. """
  84. filename = Path(filepath).stem
  85. volume = get_volume_group(filepath)
  86. parent_dir = Path(filepath).parent.name
  87. # 凡例/纲要/通则类:名称格式为"一部-凡例"以区分
  88. is_meta = parent_dir in ("凡例", "纲要", "通用技术要求", "指导原则")
  89. display_name = f"{volume}-{filename}" if is_meta else filename
  90. try:
  91. doc = Document(filepath)
  92. except Exception:
  93. return None
  94. pinyin = ""
  95. sections = OrderedDict()
  96. current_section = "正文"
  97. current_text = []
  98. # 遍历文档 body 中的所有元素(按文档顺序,同时处理段落和表格)
  99. body = doc.element.body
  100. for child in body:
  101. # --- 表格 ---
  102. if child.tag == qn("w:tbl"):
  103. # 找到对应的 python-docx Table 对象
  104. tbl = None
  105. for t in doc.tables:
  106. if t._element is child:
  107. tbl = t
  108. break
  109. if tbl is not None:
  110. tbl_text = _extract_table_text(tbl)
  111. if tbl_text:
  112. current_text.append(f"[表格]\n{tbl_text}")
  113. continue
  114. # --- 段落 ---
  115. if child.tag != qn("w:p"):
  116. continue
  117. # 从段落 XML 中提取文本和样式
  118. p_text = ""
  119. p_style = ""
  120. for p_child in child:
  121. if p_child.tag == qn("w:pPr"):
  122. for style_child in p_child:
  123. if style_child.tag == qn("w:pStyle"):
  124. p_style = style_child.get(qn("w:val"), "")
  125. elif p_child.tag == qn("w:r"):
  126. for r_child in p_child:
  127. if r_child.tag == qn("w:t"):
  128. t = r_child.text
  129. if t:
  130. p_text += t
  131. text = p_text.strip()
  132. if not text or text.isspace():
  133. continue
  134. # Heading 1 通常是药品名(与文件名一致),直接跳过,不加入 sections
  135. if p_style and (p_style.startswith("Heading") or "Heading" in p_style):
  136. continue
  137. # 拼音行(紧跟药名后)
  138. if not pinyin and is_pinyin_line(text):
  139. pinyin = text.strip()
  140. continue
  141. # 独立的 section 标题(短行,阈值放宽以适应较长标题)
  142. section_matched = detect_section_header(text)
  143. if section_matched and len(text) <= 15:
  144. if current_text:
  145. sections[current_section] = "\n".join(current_text).strip()
  146. current_text = []
  147. current_section = section_matched
  148. continue
  149. # 行内 section:【性状】xxx
  150. m = re.match(r'^【(.+?)】\s*(.*)', text)
  151. if m and detect_section_header(m.group(1)):
  152. if current_text:
  153. sections[current_section] = "\n".join(current_text).strip()
  154. current_text = []
  155. current_section = detect_section_header(m.group(1))
  156. if m.group(2):
  157. current_text.append(m.group(2))
  158. continue
  159. # 普通段落
  160. current_text.append(text)
  161. # 最后一个 section
  162. if current_text:
  163. sections[current_section] = '\n'.join(current_text).strip()
  164. # ============================================
  165. # 凡例/纲要特殊处理:按编号拆分(一、二、三... 或 1. 2. 3.)
  166. # ============================================
  167. if parent_dir in ("凡例", "纲要") and "正文" in sections:
  168. sections = split_numbered_content(sections["正文"])
  169. if len(sections) == 0:
  170. return None
  171. category = infer_category(filepath, parent_dir)
  172. return {
  173. "drug_id": generate_drug_id(display_name, filepath),
  174. "name": display_name,
  175. "name_en": "",
  176. "pinyin": pinyin,
  177. "category": category,
  178. "subcategory": infer_subcategory(filepath),
  179. "sections": dict(sections),
  180. "source": {
  181. "version": "2025年版",
  182. "volume": volume,
  183. "page": "",
  184. },
  185. }
  186. def split_numbered_content(text: str) -> OrderedDict:
  187. """
  188. 凡例/纲要类内容按编号拆分为独立 section。
  189. 匹配模式:
  190. - 一、二、三、... 十四、
  191. - (一)(二)...
  192. - 1. 2. 3. 或 1)2)3)
  193. """
  194. # 中文数字
  195. cn_nums = "一二三四五六七八九十百千"
  196. patterns = [
  197. # ^一、或 \n一、 开头(支持"二十一"等复合数字,最大3字)
  198. re.compile(r'(?:^|\n)([' + cn_nums + r']{1,3})[、,,]'),
  199. # (一)开头
  200. re.compile(r'(?:^|\n)(([' + cn_nums + r']{1,3}))'),
  201. # 数字编号
  202. re.compile(r'(?:^|\n)(\d{1,2})[\.\))]'),
  203. ]
  204. # 用第一个模式尝试
  205. result = OrderedDict()
  206. pattern = patterns[0]
  207. matches = list(pattern.finditer(text))
  208. if len(matches) < 2:
  209. # 尝试第二个模式
  210. pattern = patterns[1]
  211. matches = list(pattern.finditer(text))
  212. if len(matches) < 2:
  213. # 尝试第三个模式
  214. pattern = patterns[2]
  215. matches = list(pattern.finditer(text))
  216. if len(matches) < 2:
  217. # 确实没有编号结构,保留原样但限制长度
  218. if len(text) > 3000:
  219. # 按段落粗略切分
  220. paras = [p.strip() for p in text.split('\n') if p.strip()]
  221. buf = ""
  222. idx = 0
  223. for p in paras:
  224. if len(buf) + len(p) > 2000 and buf:
  225. result[f"第{idx + 1}段"] = buf
  226. idx += 1
  227. buf = p
  228. else:
  229. buf += ("\n" if buf else "") + p
  230. if buf:
  231. result[f"第{idx + 1}段"] = buf
  232. return result if result else OrderedDict([("正文", text)])
  233. return OrderedDict([("正文", text)])
  234. # 按编号切分
  235. for i, match in enumerate(matches):
  236. start = match.start()
  237. end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
  238. content = text[start:end].strip()
  239. # 编号字符串(去除换行和括号)
  240. raw_num = match.group(0).lstrip('\n').strip()
  241. section_name = f"凡例-{raw_num}"
  242. if len(content) > 50:
  243. result[section_name] = content
  244. return result if result else OrderedDict([("正文", text)])
  245. def is_pinyin_line(text: str) -> bool:
  246. """检测文本是否为拼音行。
  247. 判断逻辑:
  248. 1. 字母占比 > 30% 且长度在合理范围
  249. 2. 不含常见英文单词(如 drug, tablet, injection 等)
  250. 3. 不含化学元素符号(如 Na, K, HCl 等大写字母组合)
  251. 4. 拼音通常全小写或带声调符号
  252. """
  253. if len(text) <= 3 or len(text) >= 200:
  254. return False
  255. # 检查是否包含英文单词(排除化学药英文名)
  256. english_indicators = [
  257. "tablet", "injection", "capsule", "solution", "sodium",
  258. "chloride", "hydrochloride", "acid", "oxide", "sulfate",
  259. "phosphate", "acetate", "extract", "powder", "granule",
  260. "oral", "intravenous", "topical", "ophthalmic",
  261. "for", "and", "the", "with", "mg", "ml", "μg",
  262. "Tablet", "Injection", "Capsule", "Solution",
  263. ]
  264. text_lower = text.lower()
  265. if any(ind in text_lower for ind in english_indicators):
  266. return False
  267. # 检查是否含大写字母组合(化学式如 HCl, NaOH 等)
  268. if re.search(r'[A-Z]{2,}', text):
  269. return False
  270. # 计算字母占比
  271. alpha_count = sum(1 for c in text if c.isascii() and c.isalpha())
  272. total = len(text.replace(" ", ""))
  273. if total == 0:
  274. return False
  275. alpha_ratio = alpha_count / total
  276. # 拼音行通常字母占比 > 50% 且以空格分词
  277. if alpha_ratio < 0.5:
  278. return False
  279. # 检查是否有拼音声调标记(āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜ)
  280. tone_marks = set("āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜ")
  281. has_tones = any(c in tone_marks for c in text)
  282. # 拼音行特征:全小写字母 + 空格分词 + 可能带声调
  283. # 单词长度短(拼音音节通常 1-6 个字母)
  284. words = text.split()
  285. if len(words) >= 2 and all(len(w) <= 8 for w in words):
  286. if has_tones:
  287. return True
  288. # 无明确声调时提高阈值,减少误判
  289. return alpha_ratio > 0.7
  290. return has_tones
  291. def detect_section_header(text: str) -> str | None:
  292. clean = text.replace("【", "").replace("】", "").strip()
  293. if clean in SECTION_HEADERS:
  294. return SECTION_HEADERS[clean]
  295. return None
  296. def get_volume_group(filepath: str) -> str:
  297. for key, vol in VOLUME_MAP.items():
  298. if key in filepath:
  299. return vol
  300. return "一部"
  301. def infer_category(filepath: str, parent_dir: str = "") -> str:
  302. path_lower = filepath.lower()
  303. # 凡例/纲要/通用技术要求
  304. if parent_dir in ("凡例", "纲要"):
  305. return "凡例与纲要"
  306. if parent_dir in ("通用技术要求", "指导原则"):
  307. return "通则"
  308. if "output2" in path_lower: return "化学药"
  309. if "output3" in path_lower: return "生物制品"
  310. if "output4" in path_lower: return _infer_category_vol4(filepath)
  311. return "中药"
  312. def _infer_category_vol4(filepath: str) -> str:
  313. """四部特殊处理"""
  314. for key, cat in CATEGORY_OVERRIDE.items():
  315. if key in filepath:
  316. return cat
  317. return "通则"
  318. def infer_subcategory(filepath: str) -> str:
  319. """从目录层级推断子分类"""
  320. parts = Path(filepath).parts
  321. # 找到 output/output2/output3/output4 之后的子目录名
  322. for i, p in enumerate(parts):
  323. if p in ("output", "output2", "output3", "output4"):
  324. if i + 1 < len(parts):
  325. sub = parts[i + 1]
  326. # 排除数字编号前缀
  327. return sub
  328. return ""
  329. def generate_drug_id(name: str, filepath: str) -> str:
  330. vol = get_volume_group(filepath)
  331. prefix = {"一部": "Z", "二部": "H", "三部": "S", "四部": "T"}.get(vol, "Z")
  332. hash_suffix = hashlib.md5(name.encode()).hexdigest()[:6].upper()
  333. return f"{prefix}2025-{hash_suffix}"
  334. def find_docx_files(root_dir: str) -> list[str]:
  335. """扫描所有 DOCX 文件,跳过非药品目录"""
  336. files = []
  337. for dirpath, dirnames, filenames in os.walk(root_dir):
  338. dir_basename = os.path.basename(dirpath)
  339. if dir_basename in SKIP_DIRS:
  340. dirnames.clear()
  341. continue
  342. for f in sorted(filenames):
  343. if f.startswith('~') or f.startswith('.'):
  344. continue
  345. if f.endswith('.docx'):
  346. files.append(os.path.join(dirpath, f))
  347. return files
  348. async def get_embeddings(texts: list[str], text_type: str = "document") -> list[list[float]]:
  349. async with httpx.AsyncClient(timeout=60) as client:
  350. resp = await client.post(
  351. EMBEDDING_URL,
  352. headers={
  353. "Content-Type": "application/json",
  354. "Authorization": f"Bearer {QWEN_API_KEY}",
  355. },
  356. json={
  357. "model": EMBEDDING_MODEL,
  358. "input": {"texts": texts},
  359. "parameters": {"text_type": text_type},
  360. },
  361. )
  362. data = resp.json()
  363. if data.get("code") and data.get("code") != "" and data.get("code") is not None:
  364. raise RuntimeError(f"Embedding error: {data.get('message', data)}")
  365. return [item["embedding"] for item in data["output"]["embeddings"]]
  366. async def ingest_docx_entries(entries: list[dict], engine, start_idx: int = 0):
  367. """批量向量化 + 入库"""
  368. chunks = []
  369. chunk_meta = []
  370. for entry in entries:
  371. source = f"{entry['source']['version']} {entry['source']['volume']}"
  372. for section_key, section_text in entry["sections"].items():
  373. if not section_text or len(section_text.strip()) < 5:
  374. continue
  375. content = f"【{entry['name']} - {section_key}】\n{section_text}\n\n来源:{source}"
  376. chunks.append(content)
  377. chunk_meta.append({
  378. "drug_id": entry["drug_id"],
  379. "section": section_key,
  380. "content": content,
  381. "source": source,
  382. })
  383. print(f" ✂️ {len(chunks)} 个 chunks,向量化中...")
  384. all_vectors = []
  385. for i in range(0, len(chunks), BATCH_SIZE):
  386. batch = chunks[i:i + BATCH_SIZE]
  387. vecs = await get_embeddings(batch, text_type="document")
  388. all_vectors.extend(vecs)
  389. n = min(i + BATCH_SIZE, len(chunks))
  390. print(f" 向量化: {n}/{len(chunks)}")
  391. print(f" ✅ 向量化完成, 维度={len(all_vectors[0]) if all_vectors else 'N/A'}")
  392. # 写入 drug_chunks
  393. chunk_count = 0
  394. async with engine.begin() as conn:
  395. for idx, (meta, vec) in enumerate(zip(chunk_meta, all_vectors)):
  396. vec_str = f"[{','.join(str(v) for v in vec)}]"
  397. await conn.execute(
  398. text("""
  399. INSERT INTO drug_chunks (drug_id, section, content, source, chunk_index, embedding, vec)
  400. VALUES (:drug_id, :section, :content, :source, :chunk_index, :embedding, :vec)
  401. ON CONFLICT DO NOTHING
  402. """),
  403. {
  404. "drug_id": meta["drug_id"],
  405. "section": meta["section"],
  406. "content": meta["content"],
  407. "source": meta["source"],
  408. "chunk_index": start_idx + idx,
  409. "embedding": json.dumps(vec),
  410. "vec": vec_str,
  411. },
  412. )
  413. chunk_count += 1
  414. # 写入 drugs 表
  415. drug_count = 0
  416. async with engine.begin() as conn:
  417. seen = set()
  418. for entry in entries:
  419. if entry["drug_id"] in seen:
  420. continue
  421. seen.add(entry["drug_id"])
  422. await conn.execute(
  423. text("""
  424. INSERT INTO drugs (drug_id, name, name_en, pinyin, category, subcategory,
  425. sections, source_version, source_volume, source_page, is_active)
  426. VALUES (:drug_id, :name, :name_en, :pinyin, :category, :subcategory,
  427. :sections, :source_version, :source_volume, :source_page, TRUE)
  428. ON CONFLICT (drug_id) DO UPDATE SET
  429. sections = EXCLUDED.sections,
  430. category = EXCLUDED.category,
  431. subcategory = EXCLUDED.subcategory,
  432. source_version = EXCLUDED.source_version,
  433. source_volume = EXCLUDED.source_volume,
  434. updated_at = NOW()
  435. """),
  436. {
  437. "drug_id": entry["drug_id"],
  438. "name": entry["name"],
  439. "name_en": entry.get("name_en", ""),
  440. "pinyin": entry.get("pinyin", ""),
  441. "category": entry.get("category", ""),
  442. "subcategory": entry.get("subcategory", ""),
  443. "sections": json.dumps(entry.get("sections", {}), ensure_ascii=False),
  444. "source_version": entry["source"]["version"],
  445. "source_volume": entry["source"]["volume"],
  446. "source_page": entry["source"].get("page", ""),
  447. },
  448. )
  449. drug_count += 1
  450. return drug_count, chunk_count
  451. async def dedup_old_versions(engine):
  452. """覆盖性新增:同名药品如果存在非 2025 版的旧记录,标记为 inactive"""
  453. async with engine.begin() as conn:
  454. result = await conn.execute(
  455. text("""
  456. UPDATE drugs
  457. SET is_active = FALSE, updated_at = NOW()
  458. WHERE is_active = TRUE
  459. AND source_version != '2025年版'
  460. AND name IN (
  461. SELECT name FROM drugs
  462. WHERE source_version = '2025年版' AND is_active = TRUE
  463. )
  464. """)
  465. )
  466. # asyncpg 不支持 rowcount,用另一种方式
  467. count = getattr(result, 'rowcount', 0)
  468. if count > 0:
  469. print(f" 🧹 去重: 标记 {count} 个旧版药品为 inactive")
  470. async def main():
  471. load_env()
  472. global QWEN_API_KEY
  473. QWEN_API_KEY = os.environ.get("QWEN_API_KEY", "")
  474. if not QWEN_API_KEY:
  475. print("❌ 未设置 QWEN_API_KEY,请在 .env 文件中配置")
  476. sys.exit(1)
  477. print("=" * 60)
  478. print("📂 扫描 DOCX 文件...")
  479. files = find_docx_files(SOURCE_DIR)
  480. print(f" 发现 {len(files)} 个 DOCX 文件")
  481. print("=" * 60)
  482. # 解析并统计
  483. entries = []
  484. skipped = 0
  485. by_category = {}
  486. for i, fp in enumerate(files):
  487. entry = parse_docx(fp)
  488. if entry:
  489. entries.append(entry)
  490. cat = entry["category"]
  491. by_category[cat] = by_category.get(cat, 0) + 1
  492. else:
  493. skipped += 1
  494. if (i + 1) % 1000 == 0:
  495. print(f" 解析进度: {i + 1}/{len(files)} (有效: {len(entries)})")
  496. print(f"\n📦 解析完成: {len(entries)} 个有效条目 (跳过 {skipped} 个)")
  497. print(" 分类分布:")
  498. for cat, cnt in sorted(by_category.items(), key=lambda x: -x[1]):
  499. print(f" {cat}: {cnt}")
  500. if not entries:
  501. print("❌ 没有有效数据")
  502. return
  503. # 连接数据库
  504. engine = create_async_engine(DB_URL)
  505. # 分批入库
  506. total_drugs = 0
  507. total_chunks = 0
  508. BATCH = 50
  509. for i in range(0, len(entries), BATCH):
  510. batch = entries[i:i + BATCH]
  511. batch_no = i // BATCH + 1
  512. total_batches = (len(entries) + BATCH - 1) // BATCH
  513. print(f"\n🚀 第 {batch_no}/{total_batches} 批 ({len(batch)} 个药品) ...")
  514. try:
  515. dc, cc = await ingest_docx_entries(batch, engine, start_idx=total_chunks)
  516. total_drugs += dc
  517. total_chunks += cc
  518. print(f" ✅ 入库: {dc} 药品, {cc} chunks")
  519. except Exception as e:
  520. print(f" ❌ 批次失败: {e}")
  521. if batch:
  522. print(f" 首个药品: {batch[0]['name']}")
  523. # 去重:标记同名旧版药品为 inactive
  524. print("\n🧹 清理旧版重复数据...")
  525. await dedup_old_versions(engine)
  526. await engine.dispose()
  527. print("\n" + "=" * 60)
  528. print(f"🎉 全部完成!新增药品 {total_drugs} 个, chunks {total_chunks} 条")
  529. print("=" * 60)
  530. if __name__ == "__main__":
  531. asyncio.run(main())