pdf2020_ingest.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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-10 字符,CJK 占 70% 以上,允许破折号/连接符/括号"""
  52. if not s or len(s) < 2 or len(s) > 10:
  53. return False
  54. # Skip pure digits/punctuation
  55. if re.match(r'^[\d\s\.\,\;\:\!\?\(\)\[\]\{\}<>@#$%^&*+=|\\/\"\']+$', s):
  56. return False
  57. cjk = sum(1 for c in s if ord(c) >= 0x4E00 and ord(c) <= 0x9FFF)
  58. return cjk >= 2 and cjk >= len(s) * 0.7
  59. def is_pinyin_line(s):
  60. """拼音行:纯拉丁字母空格,首字母大写"""
  61. if not s or len(s) < 3 or len(s) > 80:
  62. return False
  63. alpha_spaces = sum(1 for c in s if c.isalpha() or c.isspace())
  64. return alpha_spaces == len(s) and any(c.isalpha() for c in s) and s[0].isupper()
  65. def extract_drug_entries(pdf_path: str) -> list[dict]:
  66. """解析策略:扫描【性状】锚点,向前找药名。
  67. 药名特征:2-6 纯 CJK + 下一行是拼音(首字母大写)或全大写拉丁名。
  68. 只有通过拼音/拉丁名确认的才作为药名候选。
  69. """
  70. doc = fitz.open(pdf_path)
  71. print(f"PDF: {doc.page_count} pages")
  72. # 跳过前言(前 50 页)
  73. all_text = ""
  74. for i in range(32, doc.page_count):
  75. all_text += doc[i].get_text() + "\n"
  76. doc.close()
  77. lines = all_text.split('\n')
  78. clean_lines = []
  79. for line in lines:
  80. s = line.strip()
  81. if not s: continue
  82. if s.startswith("中国药典") and len(s) < 30: continue
  83. if "ISBN" in s or "CIP" in s: continue
  84. if re.match(r'^[・•·]\s*\d+\s*[・•·]$', s): continue
  85. clean_lines.append(s)
  86. # 第一遍:标记所有"已确认的药名"
  87. # 方式1:CJK + 下一行是拼音或拉丁名(药材和饮片)
  88. # 方式2:CJK + 下一行是【处方】或【制法】(成方制剂,无拼音)
  89. confirmed_names = set()
  90. for i in range(len(clean_lines) - 2):
  91. s = clean_lines[i]
  92. nxt = clean_lines[i + 1]
  93. if is_cjk_name(s):
  94. if is_pinyin_line(nxt) or (nxt.isupper() and len(nxt) > 5):
  95. confirmed_names.add(s)
  96. elif nxt.startswith('【处方】') or nxt.startswith('【制法】'):
  97. confirmed_names.add(s)
  98. print(f" 确认药名: {len(confirmed_names)} 个")
  99. # 第二遍:以已确认药名为锚点,提取药品条目
  100. entries = []
  101. current_drug = None
  102. current_sections = OrderedDict()
  103. current_section = "正文"
  104. current_text = []
  105. in_drug = False
  106. for s in clean_lines:
  107. # 检测 section
  108. m = re.match(r'^【(.+?)】\s*(.*)', s)
  109. if m:
  110. sec_raw = m.group(1)
  111. sec_content = m.group(2)
  112. section_found = None
  113. for key, std_name in SECTION_HEADERS.items():
  114. if key in sec_raw:
  115. section_found = std_name
  116. break
  117. if section_found and in_drug:
  118. if current_text:
  119. current_sections[current_section] = '\n'.join(current_text).strip()
  120. current_text = []
  121. current_section = section_found
  122. if sec_content:
  123. current_text.append(sec_content)
  124. continue
  125. # 检测已确认的药名
  126. if s in confirmed_names:
  127. # 保存上一个药品
  128. if in_drug and current_drug and current_sections:
  129. if current_text:
  130. current_sections[current_section] = '\n'.join(current_text).strip()
  131. entries.append({"name": current_drug, "sections": dict(current_sections)})
  132. # 开始新药品
  133. current_drug = s
  134. in_drug = True
  135. current_sections = OrderedDict()
  136. current_section = "正文"
  137. current_text = []
  138. # 描述段落(药名和【性状】之间的文本)归入"正文"
  139. continue
  140. # 跳过拼音行和拉丁名行
  141. if in_drug and not current_sections and (is_pinyin_line(s) or (s.isupper() and len(s) > 5)):
  142. continue
  143. # 正文内容
  144. if in_drug:
  145. current_text.append(s)
  146. # 最后一个
  147. if in_drug and current_drug and current_sections:
  148. if current_text:
  149. current_sections[current_section] = '\n'.join(current_text).strip()
  150. entries.append({"name": current_drug, "sections": dict(current_sections)})
  151. print(f" 初步提取: {len(entries)} 个条目")
  152. # 去重:同一药名保留内容最多的条目
  153. best = {}
  154. for e in entries:
  155. content_len = sum(len(v) for v in e["sections"].values())
  156. if len(e["sections"]) >= 1 and content_len > 50:
  157. name = e["name"]
  158. if name not in best or content_len > sum(len(v) for v in best[name]["sections"].values()):
  159. hash_suffix = hashlib.md5(name.encode()).hexdigest()[:6].upper()
  160. e["drug_id"] = f"Z2020-{hash_suffix}"
  161. e["category"] = "中药"
  162. e["subcategory"] = ""
  163. e["name_en"] = ""
  164. e["pinyin"] = ""
  165. e["source"] = {"version": "2020年版", "volume": "一部", "page": ""}
  166. best[name] = e
  167. return list(best.values())
  168. async def get_embeddings(texts: list[str], text_type: str = "document") -> list[list[float]]:
  169. async with httpx.AsyncClient(timeout=60) as client:
  170. resp = await client.post(
  171. EMBEDDING_URL,
  172. headers={
  173. "Content-Type": "application/json",
  174. "Authorization": f"Bearer {QWEN_API_KEY}",
  175. },
  176. json={
  177. "model": EMBEDDING_MODEL,
  178. "input": {"texts": texts},
  179. "parameters": {"text_type": text_type},
  180. },
  181. )
  182. data = resp.json()
  183. if data.get("code") and data.get("code") != "" and data.get("code") is not None:
  184. raise RuntimeError(f"Embedding error: {data.get('message', data)}")
  185. return [item["embedding"] for item in data["output"]["embeddings"]]
  186. async def ingest_entries(entries: list[dict]):
  187. """向量化 + 入库"""
  188. engine = create_async_engine(DB_URL)
  189. chunks = []
  190. chunk_meta = []
  191. for entry in entries:
  192. source = f"{entry['source']['version']} {entry['source']['volume']}"
  193. for section_key, section_text in entry["sections"].items():
  194. if not section_text or len(section_text.strip()) < 5:
  195. continue
  196. content = f"【{entry['name']} - {section_key}】\n{section_text}\n\n来源:{source}"
  197. chunks.append(content)
  198. chunk_meta.append({
  199. "drug_id": entry["drug_id"],
  200. "section": section_key,
  201. "content": content,
  202. "source": source,
  203. })
  204. print(f" {len(chunks)} chunks,向量化中...")
  205. all_vectors = []
  206. for i in range(0, len(chunks), BATCH_SIZE):
  207. batch = chunks[i:i + BATCH_SIZE]
  208. vecs = await get_embeddings(batch, text_type="document")
  209. all_vectors.extend(vecs)
  210. n = min(i + BATCH_SIZE, len(chunks))
  211. print(f" 向量化: {n}/{len(chunks)}")
  212. print(f" [OK] 向量化完成, 维度={len(all_vectors[0]) if all_vectors else 'N/A'}")
  213. # 写入 drug_chunks
  214. chunk_count = 0
  215. async with engine.begin() as conn:
  216. for idx, (meta, vec) in enumerate(zip(chunk_meta, all_vectors)):
  217. vec_str = f"[{','.join(str(v) for v in vec)}]"
  218. await conn.execute(
  219. text("""
  220. INSERT INTO drug_chunks (drug_id, section, content, source, chunk_index, embedding, vec)
  221. VALUES (:drug_id, :section, :content, :source, :chunk_index, :embedding, :vec)
  222. ON CONFLICT DO NOTHING
  223. """),
  224. {
  225. "drug_id": meta["drug_id"],
  226. "section": meta["section"],
  227. "content": meta["content"],
  228. "source": meta["source"],
  229. "chunk_index": idx,
  230. "embedding": json.dumps(vec),
  231. "vec": vec_str,
  232. },
  233. )
  234. chunk_count += 1
  235. # 写入 drugs 表
  236. drug_count = 0
  237. async with engine.begin() as conn:
  238. for entry in entries:
  239. await conn.execute(
  240. text("""
  241. INSERT INTO drugs (drug_id, name, name_en, pinyin, category, subcategory,
  242. sections, source_version, source_volume, source_page, is_active)
  243. VALUES (:drug_id, :name, :name_en, :pinyin, :category, :subcategory,
  244. :sections, :source_version, :source_volume, :source_page, TRUE)
  245. ON CONFLICT (drug_id) DO UPDATE SET
  246. sections = EXCLUDED.sections,
  247. updated_at = NOW()
  248. """),
  249. {
  250. "drug_id": entry["drug_id"],
  251. "name": entry["name"],
  252. "name_en": entry.get("name_en", ""),
  253. "pinyin": entry.get("pinyin", ""),
  254. "category": entry.get("category", ""),
  255. "subcategory": entry.get("subcategory", ""),
  256. "sections": json.dumps(entry.get("sections", {}), ensure_ascii=False),
  257. "source_version": entry["source"]["version"],
  258. "source_volume": entry["source"]["volume"],
  259. "source_page": entry["source"].get("page", ""),
  260. },
  261. )
  262. drug_count += 1
  263. await engine.dispose()
  264. print(f"\n[DONE] 2020 药典入库完成!药品 {drug_count} 个,chunk {chunk_count} 条")
  265. async def main():
  266. load_env()
  267. global QWEN_API_KEY
  268. QWEN_API_KEY = os.environ.get("QWEN_API_KEY", "")
  269. if not QWEN_API_KEY:
  270. print("❌ 未设置 QWEN_API_KEY")
  271. sys.exit(1)
  272. print("=" * 60)
  273. print("解析 2020 年版药典 PDF...")
  274. entries = extract_drug_entries(PDF_PATH)
  275. print(f" 提取药品条目: {len(entries)}")
  276. print("=" * 60)
  277. if not entries:
  278. print("❌ 未提取到有效条目,请检查 PDF 解析逻辑")
  279. return
  280. # 打印前 5 个条目作为样品
  281. print("\n前 5 个条目预览:")
  282. for e in entries[:5]:
  283. secs = list(e["sections"].keys())
  284. total_len = sum(len(v) for v in e["sections"].values())
  285. print(f" {e['name']} | {len(secs)} sections ({total_len} 字) | {secs}")
  286. print(f"\n[>] 开始向量化入库...")
  287. await ingest_entries(entries)
  288. if __name__ == "__main__":
  289. asyncio.run(main())