pdf2020_ingest.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. """
  2. 2020 年版药典 PDF 导入脚本
  3. 解析 pharmacopoeia_2020_volume1_toc.pdf → 提取药品条目 → 向量化 → 写入 PostgreSQL
  4. """
  5. import json, os, sys, re, hashlib, asyncio
  6. from pathlib import Path
  7. from collections import OrderedDict
  8. import httpx
  9. import fitz # pymupdf
  10. from sqlalchemy.ext.asyncio import create_async_engine
  11. from sqlalchemy import text
  12. # ============================================
  13. # 配置
  14. # ============================================
  15. PDF_PATH = os.environ.get("PDF_2020_PATH", os.path.join(
  16. os.path.dirname(__file__), "..", "data", "pharmacopoeia_2020_volume1_toc.pdf"))
  17. PG_HOST = os.environ.get("POSTGRES_HOST", "localhost")
  18. PG_PORT = os.environ.get("POSTGRES_PORT", "5432")
  19. PG_DB = os.environ.get("POSTGRES_DB", "pharmacopoeia")
  20. PG_USER = os.environ.get("POSTGRES_USER", "postgres")
  21. PG_PASSWORD = os.environ.get("POSTGRES_PASSWORD", "postgres")
  22. DB_URL = f"postgresql+asyncpg://{PG_USER}:{PG_PASSWORD}@{PG_HOST}:{PG_PORT}/{PG_DB}"
  23. QWEN_API_KEY = os.environ.get("QWEN_API_KEY", "")
  24. EMBEDDING_URL = "https://dashscope.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding"
  25. EMBEDDING_MODEL = "text-embedding-v3"
  26. BATCH_SIZE = 10
  27. # 2020 药典 section 标题识别
  28. SECTION_HEADERS = OrderedDict([
  29. ("性状", "性状"), ("鉴别", "鉴别"), ("检查", "检查"),
  30. ("含量测定", "含量测定"), ("浸出物", "浸出物"),
  31. ("性味与归经", "性味与归经"), ("性味", "性味与归经"),
  32. ("功能与主治", "功能主治"), ("功能", "功能主治"), ("主治", "功能主治"),
  33. ("用法与用量", "用法用量"), ("用法", "用法用量"), ("用量", "用法用量"),
  34. ("注意", "注意事项"), ("注意事项", "注意事项"),
  35. ("规格", "规格"), ("贮藏", "贮藏"), ("类别", "类别"),
  36. ("制剂", "制剂"), ("附注", "附注"), ("禁忌", "禁忌"),
  37. ("不良反应", "不良反应"),
  38. ("处方", "处方"), ("制法", "制法"),
  39. ("包装", "包装"), ("有效期", "有效期"),
  40. ("执行标准", "执行标准"), ("批准文号", "批准文号"),
  41. ])
  42. def load_env():
  43. env_file = Path(__file__).resolve().parent.parent / ".env"
  44. if env_file.exists():
  45. for line in open(env_file, encoding="utf-8"):
  46. line = line.strip()
  47. if line and not line.startswith("#") and "=" in line:
  48. key, _, val = line.partition("=")
  49. os.environ.setdefault(key.strip(), val.strip())
  50. def is_cjk_name(s):
  51. """严格药名检测:2-6 个纯 CJK 字符"""
  52. if not s or len(s) < 2 or len(s) > 6:
  53. return False
  54. cjk = sum(1 for c in s if ord(c) >= 0x4E00 and ord(c) <= 0x9FFF)
  55. return cjk >= 2 and cjk == len(s)
  56. def is_pinyin_line(s):
  57. """拼音行:纯拉丁字母空格,首字母大写"""
  58. if not s or len(s) < 3 or len(s) > 80:
  59. return False
  60. alpha_spaces = sum(1 for c in s if c.isalpha() or c.isspace())
  61. return alpha_spaces == len(s) and any(c.isalpha() for c in s) and s[0].isupper()
  62. def extract_drug_entries(pdf_path: str) -> list[dict]:
  63. """解析策略:扫描【性状】锚点,向前找药名。
  64. 药名特征:2-6 纯 CJK + 下一行是拼音(首字母大写)或全大写拉丁名。
  65. 只有通过拼音/拉丁名确认的才作为药名候选。
  66. """
  67. doc = fitz.open(pdf_path)
  68. print(f"PDF: {doc.page_count} pages")
  69. # 跳过前言(前 50 页)
  70. all_text = ""
  71. for i in range(32, doc.page_count):
  72. all_text += doc[i].get_text() + "\n"
  73. doc.close()
  74. lines = all_text.split('\n')
  75. clean_lines = []
  76. for line in lines:
  77. s = line.strip()
  78. if not s: continue
  79. if s.startswith("中国药典") and len(s) < 30: continue
  80. if "ISBN" in s or "CIP" in s: continue
  81. if re.match(r'^[・•·]\s*\d+\s*[・•·]$', s): continue
  82. clean_lines.append(s)
  83. # 第一遍:标记所有"已确认的药名"——CJK + 下一行是拼音或拉丁名
  84. confirmed_names = set()
  85. for i in range(len(clean_lines) - 2):
  86. s = clean_lines[i]
  87. nxt = clean_lines[i + 1]
  88. if is_cjk_name(s):
  89. if is_pinyin_line(nxt) or (nxt.isupper() and len(nxt) > 5):
  90. confirmed_names.add(s)
  91. print(f" 确认药名: {len(confirmed_names)} 个")
  92. # 第二遍:以已确认药名为锚点,提取药品条目
  93. entries = []
  94. current_drug = None
  95. current_sections = OrderedDict()
  96. current_section = "正文"
  97. current_text = []
  98. in_drug = False
  99. for s in clean_lines:
  100. # 检测 section
  101. m = re.match(r'^【(.+?)】\s*(.*)', s)
  102. if m:
  103. sec_raw = m.group(1)
  104. sec_content = m.group(2)
  105. section_found = None
  106. for key, std_name in SECTION_HEADERS.items():
  107. if key in sec_raw:
  108. section_found = std_name
  109. break
  110. if section_found and in_drug:
  111. if current_text:
  112. current_sections[current_section] = '\n'.join(current_text).strip()
  113. current_text = []
  114. current_section = section_found
  115. if sec_content:
  116. current_text.append(sec_content)
  117. continue
  118. # 检测已确认的药名
  119. if s in confirmed_names:
  120. # 保存上一个药品
  121. if in_drug and current_drug and current_sections:
  122. if current_text:
  123. current_sections[current_section] = '\n'.join(current_text).strip()
  124. entries.append({"name": current_drug, "sections": dict(current_sections)})
  125. # 开始新药品
  126. current_drug = s
  127. in_drug = True
  128. current_sections = OrderedDict()
  129. current_section = "正文"
  130. current_text = []
  131. # 描述段落(药名和【性状】之间的文本)归入"正文"
  132. continue
  133. # 跳过拼音行和拉丁名行
  134. if in_drug and not current_sections and (is_pinyin_line(s) or (s.isupper() and len(s) > 5)):
  135. continue
  136. # 正文内容
  137. if in_drug:
  138. current_text.append(s)
  139. # 最后一个
  140. if in_drug and current_drug and current_sections:
  141. if current_text:
  142. current_sections[current_section] = '\n'.join(current_text).strip()
  143. entries.append({"name": current_drug, "sections": dict(current_sections)})
  144. print(f" 初步提取: {len(entries)} 个条目")
  145. # 去重:同一药名保留内容最多的条目
  146. best = {}
  147. for e in entries:
  148. content_len = sum(len(v) for v in e["sections"].values())
  149. if len(e["sections"]) >= 1 and content_len > 50:
  150. name = e["name"]
  151. if name not in best or content_len > sum(len(v) for v in best[name]["sections"].values()):
  152. hash_suffix = hashlib.md5(name.encode()).hexdigest()[:6].upper()
  153. e["drug_id"] = f"Z2020-{hash_suffix}"
  154. e["category"] = "中药"
  155. e["subcategory"] = ""
  156. e["name_en"] = ""
  157. e["pinyin"] = ""
  158. e["source"] = {"version": "2020年版", "volume": "一部", "page": ""}
  159. best[name] = e
  160. return list(best.values())
  161. async def get_embeddings(texts: list[str], text_type: str = "document") -> list[list[float]]:
  162. async with httpx.AsyncClient(timeout=60) as client:
  163. resp = await client.post(
  164. EMBEDDING_URL,
  165. headers={
  166. "Content-Type": "application/json",
  167. "Authorization": f"Bearer {QWEN_API_KEY}",
  168. },
  169. json={
  170. "model": EMBEDDING_MODEL,
  171. "input": {"texts": texts},
  172. "parameters": {"text_type": text_type},
  173. },
  174. )
  175. data = resp.json()
  176. if data.get("code") and data.get("code") != "" and data.get("code") is not None:
  177. raise RuntimeError(f"Embedding error: {data.get('message', data)}")
  178. return [item["embedding"] for item in data["output"]["embeddings"]]
  179. async def ingest_entries(entries: list[dict]):
  180. """向量化 + 入库"""
  181. engine = create_async_engine(DB_URL)
  182. chunks = []
  183. chunk_meta = []
  184. for entry in entries:
  185. source = f"{entry['source']['version']} {entry['source']['volume']}"
  186. for section_key, section_text in entry["sections"].items():
  187. if not section_text or len(section_text.strip()) < 5:
  188. continue
  189. content = f"【{entry['name']} - {section_key}】\n{section_text}\n\n来源:{source}"
  190. chunks.append(content)
  191. chunk_meta.append({
  192. "drug_id": entry["drug_id"],
  193. "section": section_key,
  194. "content": content,
  195. "source": source,
  196. })
  197. print(f" {len(chunks)} chunks,向量化中...")
  198. all_vectors = []
  199. for i in range(0, len(chunks), BATCH_SIZE):
  200. batch = chunks[i:i + BATCH_SIZE]
  201. vecs = await get_embeddings(batch, text_type="document")
  202. all_vectors.extend(vecs)
  203. n = min(i + BATCH_SIZE, len(chunks))
  204. print(f" 向量化: {n}/{len(chunks)}")
  205. print(f" [OK] 向量化完成, 维度={len(all_vectors[0]) if all_vectors else 'N/A'}")
  206. # 写入 drug_chunks
  207. chunk_count = 0
  208. async with engine.begin() as conn:
  209. for idx, (meta, vec) in enumerate(zip(chunk_meta, all_vectors)):
  210. vec_str = f"[{','.join(str(v) for v in vec)}]"
  211. await conn.execute(
  212. text("""
  213. INSERT INTO drug_chunks (drug_id, section, content, source, chunk_index, embedding, vec)
  214. VALUES (:drug_id, :section, :content, :source, :chunk_index, :embedding, :vec)
  215. ON CONFLICT DO NOTHING
  216. """),
  217. {
  218. "drug_id": meta["drug_id"],
  219. "section": meta["section"],
  220. "content": meta["content"],
  221. "source": meta["source"],
  222. "chunk_index": idx,
  223. "embedding": json.dumps(vec),
  224. "vec": vec_str,
  225. },
  226. )
  227. chunk_count += 1
  228. # 写入 drugs 表
  229. drug_count = 0
  230. async with engine.begin() as conn:
  231. for entry in entries:
  232. await conn.execute(
  233. text("""
  234. INSERT INTO drugs (drug_id, name, name_en, pinyin, category, subcategory,
  235. sections, source_version, source_volume, source_page, is_active)
  236. VALUES (:drug_id, :name, :name_en, :pinyin, :category, :subcategory,
  237. :sections, :source_version, :source_volume, :source_page, TRUE)
  238. ON CONFLICT (drug_id) DO UPDATE SET
  239. sections = EXCLUDED.sections,
  240. updated_at = NOW()
  241. """),
  242. {
  243. "drug_id": entry["drug_id"],
  244. "name": entry["name"],
  245. "name_en": entry.get("name_en", ""),
  246. "pinyin": entry.get("pinyin", ""),
  247. "category": entry.get("category", ""),
  248. "subcategory": entry.get("subcategory", ""),
  249. "sections": json.dumps(entry.get("sections", {}), ensure_ascii=False),
  250. "source_version": entry["source"]["version"],
  251. "source_volume": entry["source"]["volume"],
  252. "source_page": entry["source"].get("page", ""),
  253. },
  254. )
  255. drug_count += 1
  256. await engine.dispose()
  257. print(f"\n[DONE] 2020 药典入库完成!药品 {drug_count} 个,chunk {chunk_count} 条")
  258. async def main():
  259. load_env()
  260. global QWEN_API_KEY
  261. QWEN_API_KEY = os.environ.get("QWEN_API_KEY", "")
  262. if not QWEN_API_KEY:
  263. print("❌ 未设置 QWEN_API_KEY")
  264. sys.exit(1)
  265. print("=" * 60)
  266. print("解析 2020 年版药典 PDF...")
  267. entries = extract_drug_entries(PDF_PATH)
  268. print(f" 提取药品条目: {len(entries)}")
  269. print("=" * 60)
  270. if not entries:
  271. print("❌ 未提取到有效条目,请检查 PDF 解析逻辑")
  272. return
  273. # 打印前 5 个条目作为样品
  274. print("\n前 5 个条目预览:")
  275. for e in entries[:5]:
  276. secs = list(e["sections"].keys())
  277. total_len = sum(len(v) for v in e["sections"].values())
  278. print(f" {e['name']} | {len(secs)} sections ({total_len} 字) | {secs}")
  279. print(f"\n[>] 开始向量化入库...")
  280. await ingest_entries(entries)
  281. if __name__ == "__main__":
  282. asyncio.run(main())