| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174 |
- # -*- coding: utf-8 -*-
- """
- 统一报告指纹检测引擎
- 从数据库加载指纹规则(由 Java 后端传入 JSON),对 PDF 文本进行加权评分,
- 返回匹配的报告类型。支持任意报告家族(DAN/菌群/其他)。
- 用法(由 Java 后端通过 ProcessBuilder 调用):
- python3 fingerprint_engine.py --rules <rules.json> --text <text.txt> --filename <name>
- python3 fingerprint_engine.py --rules <rules.json> --pdf <file.pdf> --filename <name>
- 输出 JSON:
- {"typeId": "dan_a1", "score": 35, "confidence": "high", "scores": {...}, "parserPath": "..."}
- 未匹配时 typeId 为 "unknown"
- """
- import argparse
- import json
- import os
- import re
- import sys
- sys.stdout.reconfigure(encoding='utf-8')
- sys.stderr.reconfigure(encoding='utf-8')
- THRESHOLD = 10
- FILENAME_BONUS = 50
- def normalize_chinese(text):
- KANGXI_MAP = {
- '\u2f52': '\u6c0f', '\u2f51': '\u6bcd', '\u2f59': '\u6b6f',
- '\u2f04': '\u4e59', '\u2f20': '\u4e00', '\u2f21': '\u4e28',
- '\u2f22': '\u4e3f', '\u2f23': '\u4e39', '\u2f2b': '\u5c38',
- '\u2f2d': '\u5c71', '\u2f44': '\u4e59', '\u2f53': '\u6c14',
- '\u2f55': '\u6c34', '\u2f5c': '\u725b', '\u2f5f': '\u7389',
- '\u2f7a': '\u7f8a', '\u2f81': '\u8089', '\u2f83': '\u81ea',
- '\u2f8a': '\u8272', '\u2f8e': '\u8840', '\u2f95': '\u79be',
- '\u2f96': '\u8c46', '\u2faf': '\u9762', '\u2fb9': '\u9999',
- '\u2fca': '\u9ed1', '\u2ec9': '\u8d1d', '\u2edd': '\u98df',
- '\u2ee2': '\u9a6c', '\u2ee9': '\u9ec4',
- }
- return ''.join(KANGXI_MAP.get(c, c) for c in text)
- def extract_pdf_text(pdf_path):
- try:
- from PyPDF2 import PdfReader
- reader = PdfReader(pdf_path)
- return '\n'.join(page.extract_text() or '' for page in reader.pages)
- except ImportError:
- try:
- import fitz
- doc = fitz.open(pdf_path)
- return '\n'.join(page.get_text() for page in doc)
- except ImportError:
- return ''
- _FILENAME_CODE_RE = re.compile(
- r'(?<![A-Z0-9])(A1|A2|B2|B3|B4|B5|B6|C1)(?![A-Z0-9])'
- )
- def fallback_by_filename(filename):
- name = (filename or '').upper()
- m = _FILENAME_CODE_RE.search(name)
- return 'dan_' + m.group(1).lower() if m else None
- def match_filename_type_id(filename, types):
- fb = fallback_by_filename(filename)
- if fb and fb in types:
- return fb
- return None
- def detect(rules, text, filename=''):
- """对文本进行指纹评分,返回最佳匹配。
- rules: [{"typeId": "...", "minConfidence": 10, "parserPath": "...",
- "fingerprints": [{"pattern": "...", "weight": 10, "isExclusion": false}]}]
- isExclusion=true 的指纹会对该类型自身扣分(排除自身),
- 同时所有其他类型检出该特征时也会被扣分(排除他者)。
- """
- if not text or not text.strip():
- return {'typeId': 'unknown', 'score': 0, 'confidence': 'none',
- 'scores': {}, 'parserPath': None, 'reason': 'empty_text'}
- text = normalize_chinese(text)
- type_map = {r['typeId']: r for r in rules if r.get('typeId')}
- scores = {}
- exclusion_penalties = {} # typeId -> total_penalty
- for type_id, rule in type_map.items():
- score = 0
- penalty = 0
- for fp in rule.get('fingerprints', []):
- pattern = fp.get('pattern', '')
- weight = fp.get('weight', 10)
- is_excl = fp.get('isExclusion', False)
- if pattern and pattern in text:
- if is_excl:
- penalty += abs(weight)
- else:
- score += weight
- scores[type_id] = score
- if penalty:
- exclusion_penalties[type_id] = penalty
- # 排除规则: 某类型匹配了排除指纹 → 从所有其他类型扣分
- for excl_type, penalty in exclusion_penalties.items():
- for tid in scores:
- if tid != excl_type:
- scores[tid] -= penalty
- content_scores = dict(scores)
- # 文件名加成
- fb_type = match_filename_type_id(filename, type_map)
- if fb_type and fb_type in scores:
- scores[fb_type] += FILENAME_BONUS
- if not scores:
- return {'typeId': 'unknown', 'score': 0, 'confidence': 'none',
- 'scores': {}, 'parserPath': None, 'reason': 'no_rules'}
- top_type = max(scores, key=scores.get)
- rule = type_map.get(top_type, {})
- min_conf = rule.get('minConfidence', THRESHOLD)
- if content_scores.get(top_type, 0) < min_conf:
- return {'typeId': 'unknown', 'score': content_scores.get(top_type, 0),
- 'confidence': 'low', 'scores': content_scores,
- 'parserPath': None, 'reason': 'below_threshold',
- 'closest': top_type, 'closestScore': content_scores.get(top_type, 0)}
- confidence = 'high' if content_scores.get(top_type, 0) >= min_conf * 2 else 'medium'
- return {
- 'typeId': top_type,
- 'score': content_scores.get(top_type, 0),
- 'confidence': confidence,
- 'scores': dict(sorted(content_scores.items(), key=lambda x: -x[1])),
- 'parserPath': rule.get('parserPath'),
- }
- def main():
- parser = argparse.ArgumentParser(description='统一报告指纹检测引擎')
- parser.add_argument('--rules', required=True, help='指纹规则JSON文件路径')
- parser.add_argument('--text', help='报告文本文件路径')
- parser.add_argument('--pdf', help='PDF文件路径')
- parser.add_argument('--filename', default='', help='文件名(用于回退匹配)')
- args = parser.parse_args()
- with open(args.rules, 'r', encoding='utf-8') as f:
- rules = json.load(f)
- if args.pdf and os.path.exists(args.pdf):
- text = extract_pdf_text(args.pdf)
- elif args.text and os.path.exists(args.text):
- with open(args.text, 'r', encoding='utf-8') as f:
- text = f.read()
- else:
- text = ''
- result = detect(rules, text, args.filename)
- print(json.dumps(result, ensure_ascii=False))
- if __name__ == '__main__':
- main()
|