pdf_parser.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. """
  2. 菌群报告 PDF 解析器
  3. 从 extract_full_report_v5.py 提取核心逻辑,封装为可调用函数
  4. """
  5. import re
  6. from PyPDF2 import PdfReader
  7. # === 常量 ===
  8. RADICAL_MAP = {
  9. '\u2f52': '\u6c0f', '\u2f51': '\u6bcd', '\u2f59': '\u6b6f',
  10. '\u2f04': '\u4e59', '\u2f20': '\u4e00', '\u2f21': '\u4e28',
  11. '\u2f22': '\u4e3f', '\u2f23': '\u4e39', '\u2f2b': '\u5c38',
  12. '\u2f2d': '\u5c71', '\u2f44': '\u4e59', '\u2f53': '\u6c14',
  13. '\u2f55': '\u6c34', '\u2f5c': '\u725b', '\u2f5f': '\u7389',
  14. '\u2f7a': '\u7f8a', '\u2f81': '\u8089', '\u2f83': '\u81ea',
  15. '\u2f8a': '\u8272', '\u2f8e': '\u8840', '\u2f95': '\u79be',
  16. '\u2f96': '\u8c46', '\u2faf': '\u9762', '\u2fb9': '\u9999',
  17. '\u2fca': '\u9ed1', '\u2ec9': '\u8d1d', '\u2edd': '\u98df',
  18. '\u2ee2': '\u9a6c', '\u2ee9': '\u9ec4',
  19. }
  20. KNOWN_MACRO = ['碳水化合物', '蛋白质', '脂肪', '纤维素', '乳制品']
  21. KNOWN_AMINO = ['苏氨酸', '异亮氨酸', '亮氨酸', '赖氨酸', '蛋氨酸', '胱氨酸',
  22. '苯丙氨酸', '酪氨酸', '缬氨酸', '组氨酸', '丙氨酸', '丝氨酸', '甘氨酸',
  23. '脯氨酸', '谷氨酸', '天门冬氨酸', '天冬氨酸', '天冬酰胺', '谷氨酰胺',
  24. '精氨酸', '色氨酸']
  25. KNOWN_VITAMINS = ['维生素A', '维生素B1', '维生素B2', '维生素B5', '维生素B6',
  26. '叶酸', '维生素B12', '维生素C', '维生素D', '维生素K2', '维生素E']
  27. KNOWN_TRACE = ['铁', '锌']
  28. KNOWN_DISEASE_RISKS = ['炎症性肠炎', '肠易激综合征', '感染性腹泻', '自闭症',
  29. '抑郁症', '甲状腺疾病', '肺部感染或疾病', '自体免疫病', '结直肠癌',
  30. '肥胖', '便秘', '过敏', '失眠', '肝病', '肾病', '胃病', '胆病',
  31. '心脑血管疾病', 'II型糖尿病']
  32. KNOWN_BARRIER = ['肠道炎症水平', '肠道产气', '肠道屏障', '脂多糖LPS',
  33. '次级胆汁酸', '对甲酚(p-Cresol)', '吲哚', '苯酚', '腐胺', '硫化氢', '尸胺']
  34. KNOWN_SCFA = ['丁酸盐(Butyrate)', '丙酸盐(Propionate)', '乙酸盐(Acetate)', '异戊酸盐(Isovaleric)']
  35. KNOWN_NEURO = ['血清素(5-HT)', 'γ-氨基丁酸(GABA)', '谷氨酸(Glutamate)',
  36. '色氨酸(Tryptophan)', 'DOPAC', '多巴胺', '组胺(Histamine)', '一氧化氮',
  37. '喹啉(Quinolinic)', '维生素K2', '肌醇(Inositol)', '肾上腺素',
  38. '去甲肾上腺素', '乙酰胆碱', '皮质醇']
  39. KNOWN_ANTIBIOTICS = ['β-内酰胺酶类', '氨基糖苷类', '大环内酯类', '呋喃类',
  40. '喹诺酮类', '磺胺类', '甲氧苄啶类', '氯霉素类', '四环素类']
  41. KNOWN_PATHOGENS = ['幽门螺杆菌', '艰难梭菌', '沙门氏菌', '志贺氏菌', '弯曲杆菌']
  42. def norm(s):
  43. return ''.join(RADICAL_MAP.get(c, c) for c in s)
  44. def detect_format(lines):
  45. """检测 triplet / inline 格式"""
  46. text = '\n'.join(lines)
  47. has_triplet = '指标范围' in text and '疾病风险评估' in text
  48. for line in lines:
  49. if len(line) > 15 and re.search(r'[\u4e00-\u9fff]+[\d.]+[\u4e00-\u9fff/]+', line):
  50. for known in KNOWN_DISEASE_RISKS:
  51. if known in line:
  52. return 'inline'
  53. return 'triplet' if has_triplet else 'inline'
  54. def extract_text(file_path):
  55. """读取 PDF 并提取文本"""
  56. reader = PdfReader(file_path)
  57. lines = []
  58. for page in reader.pages:
  59. text = norm(page.extract_text() or '')
  60. for line in text.split('\n'):
  61. ls = line.strip()
  62. if ls:
  63. lines.append(ls)
  64. return lines
  65. def parse_overview(lines):
  66. """提取报告概述"""
  67. text = '\n'.join(lines)
  68. r = {}
  69. m = re.search(r'编号[::\s]*(\d+)', text)
  70. if m: r['report_number'] = m.group(1)
  71. m = re.search(r'姓名[::\s]*([\u4e00-\u9fff]{2,10})', text)
  72. if m: r['person_name'] = re.sub(r'(编号|年龄|性别|备注|肠道).*', '', m.group(1))[:4]
  73. m = re.search(r'年龄[::\s]*(\d+)', text)
  74. if m: r['age'] = int(m.group(1))
  75. m = re.search(r'性别[::\s]*([\u4e00-\u9fff])', text)
  76. if m: r['gender'] = 'male' if m.group(1) == '男' else 'female'
  77. for kw in ['健康总分', '菌群健康', '慢病控制', '营养均衡', '肠道菌群平衡',
  78. '菌群多样性', '有益菌', '有害菌', '核心菌属']:
  79. m = re.search(rf'{kw}\s*(\d+)', text)
  80. if m: r[kw] = int(m.group(1))
  81. m = re.search(r'肠道预测年龄[::\s]*([\d.]+)', text)
  82. if m: r['gut_age'] = m.group(1)
  83. m = re.search(r'肠型[::\s]*(\S+)', text)
  84. if m: r['gut_type'] = m.group(1)
  85. return r
  86. def parse_triplet_until(lines, stop_markers):
  87. """三元组解析:3行一组 名称/数值/状态"""
  88. results = []
  89. i = 0
  90. while i < len(lines):
  91. if any(lines[i] == sm or lines[i].startswith(sm) for sm in stop_markers):
  92. break
  93. if lines[i] in ('指标范围', '名称', '丰度', '评估'):
  94. i += 1
  95. continue
  96. name = lines[i]
  97. if i + 2 >= len(lines): break
  98. val = lines[i + 1]
  99. status = lines[i + 2]
  100. if re.match(r'^-?\d+\.?\d*$', val):
  101. results.append({'name': name, 'value': val, 'status': status})
  102. i += 3
  103. else:
  104. i += 1
  105. return results
  106. def parse_report_pdf(file_path: str) -> dict:
  107. """主函数:解析 PDF 返回结构化数据"""
  108. lines = extract_text(file_path)
  109. fmt = detect_format(lines)
  110. result = {'format': fmt, 'overview': parse_overview(lines)}
  111. # 疾病风险评估
  112. for i, line in enumerate(lines):
  113. if '疾病风险评估' in line and '注' not in line:
  114. risks = parse_triplet_until(lines[i+1:],
  115. ['主要营养评估', '氨基酸评估', '维生素评估', '微量元素评估', '抗生素风险评估'])
  116. result['disease_risks'] = [r for r in risks if '注' not in r['name']]
  117. break
  118. # 主要营养评估
  119. for i, line in enumerate(lines):
  120. if '主要营养评估' in line:
  121. nutrients = parse_triplet_until(lines[i+1:], ['氨基酸评估'])
  122. result['nutrition'] = nutrients[:5]
  123. break
  124. # 氨基酸评估
  125. for i, line in enumerate(lines):
  126. if '氨基酸评估' in line:
  127. aminos = parse_triplet_until(lines[i+1:], ['维生素评估', '微量元素评估'])
  128. result['amino_acids'] = aminos
  129. break
  130. # 维生素评估
  131. for i, line in enumerate(lines):
  132. if '维生素评估' in line:
  133. vits = parse_triplet_until(lines[i+1:], ['微量元素评估', '抗生素风险评估'])
  134. result['vitamins'] = [r for r in vits if '维生素' in r['name']]
  135. result['trace_elements'] = [r for r in vits if '维生素' not in r['name']]
  136. break
  137. return result
  138. def parse_report_pdf_with_fallback(file_path: str) -> dict:
  139. """算法解析 + 简单校验,返回结构化数据"""
  140. result = parse_report_pdf(file_path)
  141. # 简单校验:如果关键字段缺失,标记为解析不完整
  142. if not result.get('overview', {}).get('overallScore') and \
  143. not result.get('overview', {}).get('健康总分'):
  144. result['_parse_incomplete'] = True
  145. return result