docx_ingest.py 23 KB

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