fingerprint_engine.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. # -*- coding: utf-8 -*-
  2. """
  3. 统一报告指纹检测引擎
  4. 从数据库加载指纹规则(由 Java 后端传入 JSON),对 PDF 文本进行加权评分,
  5. 返回匹配的报告类型。支持任意报告家族(DAN/菌群/其他)。
  6. 用法(由 Java 后端通过 ProcessBuilder 调用):
  7. python3 fingerprint_engine.py --rules <rules.json> --text <text.txt> --filename <name>
  8. python3 fingerprint_engine.py --rules <rules.json> --pdf <file.pdf> --filename <name>
  9. 输出 JSON:
  10. {"typeId": "dan_a1", "score": 35, "confidence": "high", "scores": {...}, "parserPath": "..."}
  11. 未匹配时 typeId 为 "unknown"
  12. """
  13. import argparse
  14. import json
  15. import os
  16. import re
  17. import sys
  18. sys.stdout.reconfigure(encoding='utf-8')
  19. sys.stderr.reconfigure(encoding='utf-8')
  20. THRESHOLD = 10
  21. FILENAME_BONUS = 50
  22. def normalize_chinese(text):
  23. KANGXI_MAP = {
  24. '\u2f52': '\u6c0f', '\u2f51': '\u6bcd', '\u2f59': '\u6b6f',
  25. '\u2f04': '\u4e59', '\u2f20': '\u4e00', '\u2f21': '\u4e28',
  26. '\u2f22': '\u4e3f', '\u2f23': '\u4e39', '\u2f2b': '\u5c38',
  27. '\u2f2d': '\u5c71', '\u2f44': '\u4e59', '\u2f53': '\u6c14',
  28. '\u2f55': '\u6c34', '\u2f5c': '\u725b', '\u2f5f': '\u7389',
  29. '\u2f7a': '\u7f8a', '\u2f81': '\u8089', '\u2f83': '\u81ea',
  30. '\u2f8a': '\u8272', '\u2f8e': '\u8840', '\u2f95': '\u79be',
  31. '\u2f96': '\u8c46', '\u2faf': '\u9762', '\u2fb9': '\u9999',
  32. '\u2fca': '\u9ed1', '\u2ec9': '\u8d1d', '\u2edd': '\u98df',
  33. '\u2ee2': '\u9a6c', '\u2ee9': '\u9ec4',
  34. }
  35. return ''.join(KANGXI_MAP.get(c, c) for c in text)
  36. def extract_pdf_text(pdf_path):
  37. try:
  38. from PyPDF2 import PdfReader
  39. reader = PdfReader(pdf_path)
  40. return '\n'.join(page.extract_text() or '' for page in reader.pages)
  41. except ImportError:
  42. try:
  43. import fitz
  44. doc = fitz.open(pdf_path)
  45. return '\n'.join(page.get_text() for page in doc)
  46. except ImportError:
  47. return ''
  48. _FILENAME_CODE_RE = re.compile(
  49. r'(?<![A-Z0-9])(A1|A2|B2|B3|B4|B5|B6|C1)(?![A-Z0-9])'
  50. )
  51. def fallback_by_filename(filename):
  52. name = (filename or '').upper()
  53. m = _FILENAME_CODE_RE.search(name)
  54. return 'dan_' + m.group(1).lower() if m else None
  55. def match_filename_type_id(filename, types):
  56. fb = fallback_by_filename(filename)
  57. if fb and fb in types:
  58. return fb
  59. return None
  60. def detect(rules, text, filename=''):
  61. """对文本进行指纹评分,返回最佳匹配。
  62. rules: [{"typeId": "...", "minConfidence": 10, "parserPath": "...",
  63. "fingerprints": [{"pattern": "...", "weight": 10, "isExclusion": false}]}]
  64. isExclusion=true 的指纹会对该类型自身扣分(排除自身),
  65. 同时所有其他类型检出该特征时也会被扣分(排除他者)。
  66. """
  67. if not text or not text.strip():
  68. return {'typeId': 'unknown', 'score': 0, 'confidence': 'none',
  69. 'scores': {}, 'parserPath': None, 'reason': 'empty_text'}
  70. text = normalize_chinese(text)
  71. type_map = {r['typeId']: r for r in rules if r.get('typeId')}
  72. scores = {}
  73. exclusion_penalties = {} # typeId -> total_penalty
  74. for type_id, rule in type_map.items():
  75. score = 0
  76. penalty = 0
  77. for fp in rule.get('fingerprints', []):
  78. pattern = fp.get('pattern', '')
  79. weight = fp.get('weight', 10)
  80. is_excl = fp.get('isExclusion', False)
  81. if pattern and pattern in text:
  82. if is_excl:
  83. penalty += abs(weight)
  84. else:
  85. score += weight
  86. scores[type_id] = score
  87. if penalty:
  88. exclusion_penalties[type_id] = penalty
  89. # 排除规则: 某类型匹配了排除指纹 → 从所有其他类型扣分
  90. for excl_type, penalty in exclusion_penalties.items():
  91. for tid in scores:
  92. if tid != excl_type:
  93. scores[tid] -= penalty
  94. content_scores = dict(scores)
  95. # 文件名加成
  96. fb_type = match_filename_type_id(filename, type_map)
  97. if fb_type and fb_type in scores:
  98. scores[fb_type] += FILENAME_BONUS
  99. if not scores:
  100. return {'typeId': 'unknown', 'score': 0, 'confidence': 'none',
  101. 'scores': {}, 'parserPath': None, 'reason': 'no_rules'}
  102. top_type = max(scores, key=scores.get)
  103. rule = type_map.get(top_type, {})
  104. min_conf = rule.get('minConfidence', THRESHOLD)
  105. if content_scores.get(top_type, 0) < min_conf:
  106. return {'typeId': 'unknown', 'score': content_scores.get(top_type, 0),
  107. 'confidence': 'low', 'scores': content_scores,
  108. 'parserPath': None, 'reason': 'below_threshold',
  109. 'closest': top_type, 'closestScore': content_scores.get(top_type, 0)}
  110. confidence = 'high' if content_scores.get(top_type, 0) >= min_conf * 2 else 'medium'
  111. return {
  112. 'typeId': top_type,
  113. 'score': content_scores.get(top_type, 0),
  114. 'confidence': confidence,
  115. 'scores': dict(sorted(content_scores.items(), key=lambda x: -x[1])),
  116. 'parserPath': rule.get('parserPath'),
  117. }
  118. def main():
  119. parser = argparse.ArgumentParser(description='统一报告指纹检测引擎')
  120. parser.add_argument('--rules', required=True, help='指纹规则JSON文件路径')
  121. parser.add_argument('--text', help='报告文本文件路径')
  122. parser.add_argument('--pdf', help='PDF文件路径')
  123. parser.add_argument('--filename', default='', help='文件名(用于回退匹配)')
  124. args = parser.parse_args()
  125. with open(args.rules, 'r', encoding='utf-8') as f:
  126. rules = json.load(f)
  127. if args.pdf and os.path.exists(args.pdf):
  128. text = extract_pdf_text(args.pdf)
  129. elif args.text and os.path.exists(args.text):
  130. with open(args.text, 'r', encoding='utf-8') as f:
  131. text = f.read()
  132. else:
  133. text = ''
  134. result = detect(rules, text, args.filename)
  135. print(json.dumps(result, ensure_ascii=False))
  136. if __name__ == '__main__':
  137. main()