table_comparator.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. import re
  2. from typing import Dict, List, Tuple, Optional
  3. try:
  4. from .data_type_detector import DataTypeDetector
  5. from .similarity_calculator import SimilarityCalculator
  6. from .text_processor import TextProcessor
  7. except ImportError:
  8. from data_type_detector import DataTypeDetector
  9. from similarity_calculator import SimilarityCalculator
  10. from text_processor import TextProcessor
  11. class TableComparator:
  12. """表格数据比较"""
  13. def __init__(self):
  14. self.detector = DataTypeDetector()
  15. self.calculator = SimilarityCalculator()
  16. self.text_processor = TextProcessor()
  17. self.header_similarity_threshold = 90
  18. self.content_similarity_threshold = 95
  19. self.max_paragraph_window = 6
  20. def find_matching_tables(self, tables1: List[List[List[str]]],
  21. tables2: List[List[List[str]]]) -> List[Tuple[int, int, float]]:
  22. """
  23. 智能匹配两个文件中的表格
  24. Returns:
  25. List[Tuple[int, int, float]]: (table1_index, table2_index, similarity_score)
  26. """
  27. matches = []
  28. for i, table1 in enumerate(tables1):
  29. if not table1:
  30. continue
  31. best_match = None
  32. best_score = 0
  33. for j, table2 in enumerate(tables2):
  34. if not table2:
  35. continue
  36. # 计算表格相似度
  37. score = self._calculate_table_similarity(table1, table2)
  38. if score > best_score:
  39. best_score = score
  40. best_match = j
  41. if best_match is not None and best_score > 50: # 至少50%相似度
  42. matches.append((i, best_match, best_score))
  43. print(f" 📊 表格匹配: 文件1表格{i+1} ↔ 文件2表格{best_match+1} (相似度: {best_score:.1f}%)")
  44. return matches
  45. def _get_max_columns(self, table: List[List[str]]) -> int:
  46. """获取表格的最大列数"""
  47. if not table:
  48. return 0
  49. return max(len(row) for row in table)
  50. def _calculate_table_similarity(self, table1: List[List[str]],
  51. table2: List[List[str]]) -> float:
  52. """计算两个表格的相似度"""
  53. if not table1 or not table2:
  54. return 0.0
  55. # 1. 行数相似度 (权重: 15%)
  56. row_count1 = len(table1)
  57. row_count2 = len(table2)
  58. row_similarity = 100 * (1 - abs(row_count1 - row_count2) / max(row_count1, row_count2))
  59. # 2. 列数相似度 (权重: 15%) - ✅ 使用最大列数
  60. col_count1 = self._get_max_columns(table1)
  61. col_count2 = self._get_max_columns(table2)
  62. max_cols = max(col_count1, col_count2)
  63. min_cols = min(col_count1, col_count2)
  64. if max_cols == 0:
  65. col_similarity = 0
  66. else:
  67. # 如果列数差异在合理范围内(比如差1-2列),给予较高分数
  68. col_diff = abs(col_count1 - col_count2)
  69. if col_diff == 0:
  70. col_similarity = 100
  71. elif col_diff <= 2:
  72. # 差1-2列,给予80-95分
  73. col_similarity = 100 - (col_diff * 10)
  74. else:
  75. # 差异较大时,使用比例计算
  76. col_similarity = 100 * (min_cols / max_cols)
  77. print(f" 行数对比: {row_count1} vs {row_count2}, 相似度: {row_similarity:.1f}%")
  78. print(f" 列数对比: {col_count1} vs {col_count2}, 相似度: {col_similarity:.1f}%")
  79. # 3. 表头相似度 (权重: 50%) - ✅ 先检测表头位置
  80. header_row_idx1 = self.detect_table_header_row(table1)
  81. header_row_idx2 = self.detect_table_header_row(table2)
  82. print(f" 表头位置: 文件1第{header_row_idx1+1}行, 文件2第{header_row_idx2+1}行")
  83. header_similarity = 0
  84. if header_row_idx1 < len(table1) and header_row_idx2 < len(table2):
  85. header1 = table1[header_row_idx1]
  86. header2 = table2[header_row_idx2]
  87. if header1 and header2:
  88. # ✅ 智能表头匹配
  89. header_similarity = self._calculate_header_similarity_smart(header1, header2)
  90. print(f" 表头相似度: {header_similarity:.1f}%")
  91. # 4. 内容特征相似度 (权重: 20%)
  92. content_similarity = self._calculate_content_features_similarity(table1, table2)
  93. print(f" 内容特征相似度: {content_similarity:.1f}%")
  94. # ✅ 调整权重分配
  95. total_similarity = (
  96. row_similarity * 0.15 + # 行数 15%
  97. col_similarity * 0.15 + # 列数 15%
  98. header_similarity * 0.50 + # 表头 50% (最重要)
  99. content_similarity * 0.20 # 内容 20%
  100. )
  101. return total_similarity
  102. def _calculate_header_similarity_smart(self, header1: List[str],
  103. header2: List[str]) -> float:
  104. """
  105. 智能计算表头相似度
  106. 处理以下情况:
  107. 1. 列数不同但表头内容相似
  108. 2. PaddleOCR可能将多行表头合并
  109. 3. 表头顺序可能不同
  110. """
  111. if not header1 or not header2:
  112. return 0.0
  113. # 标准化表头
  114. norm_headers1 = [self.normalize_header_text(h) for h in header1]
  115. norm_headers2 = [self.normalize_header_text(h) for h in header2]
  116. # 方法1: 精确匹配 (最高优先级)
  117. common_headers = set(norm_headers1) & set(norm_headers2)
  118. max_len = max(len(norm_headers1), len(norm_headers2))
  119. if max_len == 0:
  120. return 0.0
  121. exact_match_ratio = len(common_headers) / max_len
  122. # 方法2: 模糊匹配 (针对列数不同的情况)
  123. fuzzy_matches = 0
  124. # 使用较短的表头作为基准
  125. if len(norm_headers1) <= len(norm_headers2):
  126. base_headers = norm_headers1
  127. compare_headers = norm_headers2
  128. else:
  129. base_headers = norm_headers2
  130. compare_headers = norm_headers1
  131. for base_h in base_headers:
  132. best_similarity = 0
  133. for comp_h in compare_headers:
  134. similarity = self.calculator.calculate_text_similarity(base_h, comp_h)
  135. if similarity > best_similarity:
  136. best_similarity = similarity
  137. if best_similarity == 100:
  138. break
  139. # 如果相似度超过70%,认为是匹配的
  140. if best_similarity > 70:
  141. fuzzy_matches += 1
  142. fuzzy_match_ratio = fuzzy_matches / max_len if max_len > 0 else 0
  143. # 方法3: 关键字匹配 (识别常见表头)
  144. key_headers = {
  145. 'date': ['日期', 'date', '时间', 'time'],
  146. 'type': ['类型', 'type', '业务', 'business'],
  147. 'number': ['号', 'no', '编号', 'id', '票据', 'bill'],
  148. 'description': ['摘要', 'description', '说明', 'remark'],
  149. 'amount': ['金额', 'amount', '借方', 'debit', '贷方', 'credit'],
  150. 'balance': ['余额', 'balance'],
  151. 'counterparty': ['对手', 'counterparty', '账户', 'account', '户名', 'name']
  152. }
  153. def categorize_header(h: str) -> set:
  154. categories = set()
  155. h_lower = h.lower()
  156. for category, keywords in key_headers.items():
  157. for keyword in keywords:
  158. if keyword in h_lower:
  159. categories.add(category)
  160. return categories
  161. categories1 = set()
  162. for h in norm_headers1:
  163. categories1.update(categorize_header(h))
  164. categories2 = set()
  165. for h in norm_headers2:
  166. categories2.update(categorize_header(h))
  167. common_categories = categories1 & categories2
  168. all_categories = categories1 | categories2
  169. category_match_ratio = len(common_categories) / len(all_categories) if all_categories else 0
  170. # ✅ 综合三种方法,加权计算
  171. final_similarity = (
  172. exact_match_ratio * 0.4 + # 精确匹配 40%
  173. fuzzy_match_ratio * 0.4 + # 模糊匹配 40%
  174. category_match_ratio * 0.2 # 语义匹配 20%
  175. ) * 100
  176. print(f" 精确匹配: {exact_match_ratio:.1%}, 模糊匹配: {fuzzy_match_ratio:.1%}, 语义匹配: {category_match_ratio:.1%}")
  177. return final_similarity
  178. def _calculate_content_features_similarity(self, table1: List[List[str]],
  179. table2: List[List[str]]) -> float:
  180. """计算表格内容特征相似度"""
  181. # 统计数字、日期等特征
  182. features1 = self._extract_table_features(table1)
  183. features2 = self._extract_table_features(table2)
  184. # 比较特征
  185. similarity_scores = []
  186. for key in ['numeric_ratio', 'date_ratio', 'empty_ratio']:
  187. if key in features1 and key in features2:
  188. diff = abs(features1[key] - features2[key])
  189. similarity_scores.append(100 * (1 - diff))
  190. return sum(similarity_scores) / len(similarity_scores) if similarity_scores else 0
  191. def _extract_table_features(self, table: List[List[str]]) -> Dict:
  192. """提取表格特征"""
  193. total_cells = 0
  194. numeric_cells = 0
  195. date_cells = 0
  196. empty_cells = 0
  197. for row in table:
  198. for cell in row:
  199. total_cells += 1
  200. if not cell or cell.strip() == '':
  201. empty_cells += 1
  202. continue
  203. if self.detector.is_numeric(cell):
  204. numeric_cells += 1
  205. if self.detector.extract_datetime(cell):
  206. date_cells += 1
  207. return {
  208. 'numeric_ratio': numeric_cells / total_cells if total_cells > 0 else 0,
  209. 'date_ratio': date_cells / total_cells if total_cells > 0 else 0,
  210. 'empty_ratio': empty_cells / total_cells if total_cells > 0 else 0,
  211. 'total_cells': total_cells
  212. }
  213. def normalize_header_text(self, text: str) -> str:
  214. """标准化表头文本"""
  215. # 移除括号内容
  216. text = re.sub(r'[((].*?[))]', '', text)
  217. # 移除空格
  218. text = re.sub(r'\s+', '', text)
  219. # 只保留字母、数字和中文
  220. text = re.sub(r'[^\w\u4e00-\u9fff]', '', text)
  221. return text.lower().strip()
  222. def detect_table_header_row(self, table: List[List[str]]) -> int:
  223. """
  224. 智能检测表格的表头行索引
  225. 检测策略:
  226. 1. 查找包含表头关键字最多的行
  227. 2. 确认下一行是数据行(或分类行)
  228. 3. 特殊处理:资产负债表等多层表头
  229. """
  230. if not table:
  231. return 0
  232. header_keywords = [
  233. '日期', 'date', '时间', 'time',
  234. '类型', 'type', '业务', 'business',
  235. '号', 'no', '编号', 'id', '票据', 'bill',
  236. '摘要', 'description', '说明', 'remark',
  237. '金额', 'amount', '借方', 'debit', '贷方', 'credit',
  238. '余额', 'balance',
  239. '对手', 'counterparty', '账户', 'account', '户名', 'name',
  240. # ✅ 新增:资产负债表关键词
  241. # '资产', 'asset', '负债', 'liability', '期末', 'period', '期初'
  242. '期末', 'period', '期初'
  243. ]
  244. best_header_row = 0
  245. best_score = 0
  246. for row_idx, row in enumerate(table[:10]):
  247. if not row:
  248. continue
  249. # 计算关键字匹配分数
  250. keyword_count = 0
  251. non_empty_cells = 0
  252. for cell in row:
  253. cell_text = str(cell).strip()
  254. if cell_text:
  255. non_empty_cells += 1
  256. cell_lower = cell_text.lower()
  257. for keyword in header_keywords:
  258. if keyword in cell_lower:
  259. keyword_count += 1
  260. break
  261. if non_empty_cells < 3:
  262. continue
  263. keyword_ratio = keyword_count / non_empty_cells if non_empty_cells > 0 else 0
  264. column_bonus = min(non_empty_cells / 5, 1.0)
  265. score = keyword_ratio * 0.7 + column_bonus * 0.3
  266. # ✅ 改进:跳过分类行和数据行检测
  267. if row_idx + 1 < len(table):
  268. next_row = table[row_idx + 1]
  269. # 如果下一行是数据行,加分
  270. if self._is_data_row(next_row):
  271. score += 0.2
  272. # ✅ 新增:如果下一行是分类行(如"流动资产:"),小幅加分
  273. elif self._is_category_row(next_row):
  274. score += 0.1
  275. if score > best_score:
  276. best_score = score
  277. best_header_row = row_idx
  278. if best_score < 0.3:
  279. print(f" ⚠️ 未检测到明确表头,默认使用第1行 (得分: {best_score:.2f})")
  280. return 0
  281. print(f" 📍 检测到表头在第 {best_header_row + 1} 行 (得分: {best_score:.2f})")
  282. return best_header_row
  283. def _is_category_row(self, row: List[str]) -> bool:
  284. """
  285. ✅ 新增:判断是否为分类行(如"流动资产:")
  286. """
  287. if not row:
  288. return False
  289. category_patterns = [
  290. # r'流动[资产负债]',
  291. # r'非流动[资产负债]',
  292. r'.*:$', # 以冒号结尾
  293. ]
  294. for cell in row:
  295. cell_text = str(cell).strip()
  296. if not cell_text:
  297. continue
  298. for pattern in category_patterns:
  299. if re.search(pattern, cell_text):
  300. return True
  301. return False
  302. def _is_data_row(self, row: List[str]) -> bool:
  303. """
  304. 判断是否为数据行(改进版)
  305. ✅ "-" 符号表示金额为0或空,应该被认为是有效的数据单元格
  306. """
  307. if not row:
  308. return False
  309. data_pattern_count = 0
  310. non_empty_count = 0
  311. for cell in row:
  312. cell_text = str(cell).strip()
  313. if not cell_text:
  314. continue
  315. non_empty_count += 1
  316. # ✅ "-" 符号也是有效的数据(表示0或空)
  317. if cell_text == '-' or cell_text == '—' or cell_text == '--':
  318. data_pattern_count += 1
  319. continue
  320. # 包含数字
  321. if re.search(r'\d', cell_text):
  322. data_pattern_count += 1
  323. # 包含日期格式
  324. if re.search(r'\d{4}[-/年]\d{1,2}[-/月]\d{1,2}', cell_text):
  325. data_pattern_count += 1
  326. # 包含金额格式
  327. if re.search(r'-?\d+[,,]?\d*\.?\d+', cell_text):
  328. data_pattern_count += 1
  329. if non_empty_count == 0:
  330. return False
  331. # 至少30%的单元格包含数据特征
  332. return data_pattern_count / non_empty_count >= 0.3
  333. def compare_table_headers(self, headers1: List[str], headers2: List[str]) -> Dict:
  334. """比较表格表头"""
  335. result = {
  336. 'match': True,
  337. 'differences': [],
  338. 'column_mapping': {},
  339. 'similarity_scores': []
  340. }
  341. if len(headers1) != len(headers2):
  342. result['match'] = False
  343. result['differences'].append({
  344. 'type': 'table_header_critical',
  345. 'description': f'表头列数不一致: {len(headers1)} vs {len(headers2)}',
  346. 'severity': 'critical'
  347. })
  348. return result
  349. for i, (h1, h2) in enumerate(zip(headers1, headers2)):
  350. norm_h1 = self.normalize_header_text(h1)
  351. norm_h2 = self.normalize_header_text(h2)
  352. similarity = self.calculator.calculate_text_similarity(norm_h1, norm_h2)
  353. result['similarity_scores'].append({
  354. 'column_index': i,
  355. 'header1': h1,
  356. 'header2': h2,
  357. 'similarity': similarity
  358. })
  359. if similarity < self.header_similarity_threshold:
  360. result['match'] = False
  361. result['differences'].append({
  362. 'type': 'table_header_mismatch',
  363. 'column_index': i,
  364. 'header1': h1,
  365. 'header2': h2,
  366. 'similarity': similarity,
  367. 'description': f'第{i+1}列表头不匹配: "{h1}" vs "{h2}" (相似度: {similarity:.1f}%)',
  368. 'severity': 'medium' if similarity < 50 else 'high'
  369. })
  370. else:
  371. result['column_mapping'][i] = i
  372. return result
  373. def compare_cell_value(self, value1: str, value2: str, column_type: str,
  374. column_name: str = '') -> Dict:
  375. """比较单元格值"""
  376. result = {
  377. 'match': True,
  378. 'difference': None
  379. }
  380. v1 = self.text_processor.normalize_text(value1)
  381. v2 = self.text_processor.normalize_text(value2)
  382. if v1 == v2:
  383. return result
  384. if column_type == 'text_number':
  385. norm_v1 = self.detector.normalize_text_number(v1)
  386. norm_v2 = self.detector.normalize_text_number(v2)
  387. if norm_v1 == norm_v2:
  388. result['match'] = False
  389. result['difference'] = {
  390. 'type': 'table_text',
  391. 'value1': value1,
  392. 'value2': value2,
  393. 'description': f'文本型数字格式差异: "{value1}" vs "{value2}" (内容相同,空格不同)',
  394. 'severity': 'low'
  395. }
  396. else:
  397. result['match'] = False
  398. result['difference'] = {
  399. 'type': 'table_text',
  400. 'value1': value1,
  401. 'value2': value2,
  402. 'description': f'文本型数字不一致: {value1} vs {value2}',
  403. 'severity': 'high'
  404. }
  405. return result
  406. if column_type == 'numeric':
  407. if self.detector.is_numeric(v1) and self.detector.is_numeric(v2):
  408. num1 = self.detector.parse_number(v1)
  409. num2 = self.detector.parse_number(v2)
  410. if abs(num1 - num2) > 0.01:
  411. result['match'] = False
  412. result['difference'] = {
  413. 'type': 'table_amount',
  414. 'value1': value1,
  415. 'value2': value2,
  416. 'diff_amount': abs(num1 - num2),
  417. 'description': f'金额不一致: {value1} vs {value2}',
  418. 'severity': 'high' # ✅ 修改:金额差异 = high
  419. }
  420. else:
  421. result['match'] = False
  422. result['difference'] = {
  423. 'type': 'table_text',
  424. 'value1': value1,
  425. 'value2': value2,
  426. 'description': f'长数字字符串不一致: {value1} vs {value2}',
  427. 'severity': 'medium' # ✅ 修改:数字字符串差异 = medium
  428. }
  429. elif column_type == 'datetime':
  430. datetime1 = self.detector.extract_datetime(v1)
  431. datetime2 = self.detector.extract_datetime(v2)
  432. if datetime1 != datetime2:
  433. result['match'] = False
  434. result['difference'] = {
  435. 'type': 'table_datetime',
  436. 'value1': value1,
  437. 'value2': value2,
  438. 'description': f'日期时间不一致: {value1} vs {value2}',
  439. 'severity': 'medium' # 日期差异 = medium
  440. }
  441. else:
  442. similarity = self.calculator.calculate_text_similarity(v1, v2)
  443. if similarity < self.content_similarity_threshold:
  444. result['match'] = False
  445. result['difference'] = {
  446. 'type': 'table_text',
  447. 'value1': value1,
  448. 'value2': value2,
  449. 'similarity': similarity,
  450. 'description': f'文本不一致: {value1} vs {value2} (相似度: {similarity:.1f}%)',
  451. 'severity': 'low' if similarity > 80 else 'medium' # 根据相似度判断
  452. }
  453. return result
  454. def compare_tables(self, table1: List[List[str]], table2: List[List[str]]) -> List[Dict]:
  455. """标准表格比较"""
  456. differences = []
  457. max_rows = max(len(table1), len(table2))
  458. for i in range(max_rows):
  459. row1 = table1[i] if i < len(table1) else []
  460. row2 = table2[i] if i < len(table2) else []
  461. max_cols = max(len(row1), len(row2))
  462. for j in range(max_cols):
  463. cell1 = row1[j] if j < len(row1) else ""
  464. cell2 = row2[j] if j < len(row2) else ""
  465. if "[图片内容-忽略]" in cell1 or "[图片内容-忽略]" in cell2:
  466. continue
  467. if cell1 != cell2:
  468. if self.detector.is_numeric(cell1) and self.detector.is_numeric(cell2):
  469. num1 = self.detector.parse_number(cell1)
  470. num2 = self.detector.parse_number(cell2)
  471. if abs(num1 - num2) > 0.001:
  472. differences.append({
  473. 'type': 'table_amount',
  474. 'position': f'行{i+1}列{j+1}',
  475. 'file1_value': cell1,
  476. 'file2_value': cell2,
  477. 'description': f'金额不一致: {cell1} vs {cell2}',
  478. 'severity': 'high', # ✅ 添加:金额差异 = high
  479. 'row_index': i,
  480. 'col_index': j
  481. })
  482. else:
  483. differences.append({
  484. 'type': 'table_text',
  485. 'position': f'行{i+1}列{j+1}',
  486. 'file1_value': cell1,
  487. 'file2_value': cell2,
  488. 'description': f'文本不一致: {cell1} vs {cell2}',
  489. 'severity': 'medium', # ✅ 添加:文本差异 = medium
  490. 'row_index': i,
  491. 'col_index': j
  492. })
  493. return differences
  494. def compare_table_flow_list(self, table1: List[List[str]], table2: List[List[str]]) -> List[Dict]:
  495. """流水列表表格比较算法"""
  496. differences = []
  497. if not table1 or not table2:
  498. return [{
  499. 'type': 'table_empty',
  500. 'description': '表格为空',
  501. 'severity': 'critical'
  502. }]
  503. print(f"\n📋 开始流水表格对比...")
  504. # 检测表头位置
  505. header_row_idx1 = self.detect_table_header_row(table1)
  506. header_row_idx2 = self.detect_table_header_row(table2)
  507. if header_row_idx1 != header_row_idx2:
  508. differences.append({
  509. 'type': 'table_header_position',
  510. 'position': '表头位置',
  511. 'file1_value': f'第{header_row_idx1 + 1}行',
  512. 'file2_value': f'第{header_row_idx2 + 1}行',
  513. 'description': f'表头位置不一致: 文件1在第{header_row_idx1 + 1}行,文件2在第{header_row_idx2 + 1}行',
  514. 'severity': 'high'
  515. })
  516. # 比对表头前的内容
  517. if header_row_idx1 > 0 or header_row_idx2 > 0:
  518. print(f"\n📝 对比表头前的内容...")
  519. pre_header_table1 = table1[:header_row_idx1] if header_row_idx1 > 0 else []
  520. pre_header_table2 = table2[:header_row_idx2] if header_row_idx2 > 0 else []
  521. if pre_header_table1 or pre_header_table2:
  522. pre_header_diffs = self.compare_tables(pre_header_table1, pre_header_table2)
  523. for diff in pre_header_diffs:
  524. diff['type'] = 'table_pre_header'
  525. diff['position'] = f"表头前{diff['position']}"
  526. diff['severity'] = 'medium'
  527. differences.extend(pre_header_diffs)
  528. # 比较表头
  529. headers1 = table1[header_row_idx1]
  530. headers2 = table2[header_row_idx2]
  531. print(f"\n📋 对比表头...")
  532. header_result = self.compare_table_headers(headers1, headers2)
  533. if not header_result['match']:
  534. print(f"\n⚠️ 表头文字存在差异")
  535. for diff in header_result['differences']:
  536. differences.append({
  537. 'type': diff.get('type', 'table_header_mismatch'),
  538. 'position': '表头',
  539. 'file1_value': diff.get('header1', ''),
  540. 'file2_value': diff.get('header2', ''),
  541. 'description': diff['description'],
  542. 'severity': diff.get('severity', 'high'),
  543. })
  544. if diff.get('severity') == 'critical':
  545. return differences
  546. # 检测列类型并比较数据行
  547. column_types1 = self._detect_column_types(table1, header_row_idx1, headers1)
  548. column_types2 = self._detect_column_types(table2, header_row_idx2, headers2)
  549. # 处理列类型不匹配
  550. mismatched_columns = self._check_column_type_mismatch(
  551. column_types1, column_types2, headers1, headers2, differences
  552. )
  553. # 合并列类型
  554. column_types = self._merge_column_types(column_types1, column_types2, mismatched_columns)
  555. # 逐行比较数据
  556. data_diffs = self._compare_data_rows(
  557. table1, table2, header_row_idx1, header_row_idx2,
  558. headers1, column_types, mismatched_columns, header_result['match']
  559. )
  560. differences.extend(data_diffs)
  561. print(f"\n✅ 流水表格对比完成,发现 {len(differences)} 个差异")
  562. return differences
  563. def _detect_column_types(self, table: List[List[str]], header_row_idx: int,
  564. headers: List[str]) -> List[str]:
  565. """检测列类型"""
  566. column_types = []
  567. for col_idx in range(len(headers)):
  568. col_values = [
  569. row[col_idx]
  570. for row in table[header_row_idx + 1:]
  571. if col_idx < len(row)
  572. ]
  573. col_type = self.detector.detect_column_type(col_values)
  574. column_types.append(col_type)
  575. return column_types
  576. def _check_column_type_mismatch(self, column_types1: List[str], column_types2: List[str],
  577. headers1: List[str], headers2: List[str],
  578. differences: List[Dict]) -> List[int]:
  579. """检查列类型不匹配"""
  580. mismatched_columns = []
  581. for col_idx in range(min(len(column_types1), len(column_types2))):
  582. if column_types1[col_idx] != column_types2[col_idx]:
  583. mismatched_columns.append(col_idx)
  584. differences.append({
  585. 'type': 'table_column_type_mismatch',
  586. 'position': f'第{col_idx + 1}列',
  587. 'file1_value': f'{headers1[col_idx]} ({column_types1[col_idx]})',
  588. 'file2_value': f'{headers2[col_idx]} ({column_types2[col_idx]})',
  589. 'description': f'列类型不一致: {column_types1[col_idx]} vs {column_types2[col_idx]}',
  590. 'severity': 'high',
  591. 'column_index': col_idx
  592. })
  593. total_columns = min(len(column_types1), len(column_types2))
  594. mismatch_ratio = len(mismatched_columns) / total_columns if total_columns > 0 else 0
  595. if mismatch_ratio > 0.5:
  596. differences.append({
  597. 'type': 'table_header_critical',
  598. 'position': '表格列类型',
  599. 'file1_value': f'{len(mismatched_columns)}列类型不一致',
  600. 'file2_value': f'共{total_columns}列',
  601. 'description': f'列类型差异过大: {len(mismatched_columns)}/{total_columns}列不匹配 ({mismatch_ratio:.1%})',
  602. 'severity': 'critical'
  603. })
  604. return mismatched_columns
  605. def _merge_column_types(self, column_types1: List[str], column_types2: List[str],
  606. mismatched_columns: List[int]) -> List[str]:
  607. """合并列类型"""
  608. column_types = []
  609. for col_idx in range(max(len(column_types1), len(column_types2))):
  610. if col_idx >= len(column_types1):
  611. column_types.append(column_types2[col_idx])
  612. elif col_idx >= len(column_types2):
  613. column_types.append(column_types1[col_idx])
  614. elif col_idx in mismatched_columns:
  615. type1 = column_types1[col_idx]
  616. type2 = column_types2[col_idx]
  617. if type1 == 'text' or type2 == 'text':
  618. column_types.append('text')
  619. elif type1 == 'text_number' or type2 == 'text_number':
  620. column_types.append('text_number')
  621. else:
  622. column_types.append(type1)
  623. else:
  624. column_types.append(column_types1[col_idx])
  625. return column_types
  626. def _compare_data_rows(self, table1: List[List[str]], table2: List[List[str]],
  627. header_row_idx1: int, header_row_idx2: int,
  628. headers1: List[str], column_types: List[str],
  629. mismatched_columns: List[int], header_match: bool) -> List[Dict]:
  630. """逐行比较数据"""
  631. differences = []
  632. data_rows1 = table1[header_row_idx1 + 1:]
  633. data_rows2 = table2[header_row_idx2 + 1:]
  634. max_rows = max(len(data_rows1), len(data_rows2))
  635. for row_idx in range(max_rows):
  636. row1 = data_rows1[row_idx] if row_idx < len(data_rows1) else []
  637. row2 = data_rows2[row_idx] if row_idx < len(data_rows2) else []
  638. actual_row_num = header_row_idx1 + row_idx + 2
  639. if not row1:
  640. differences.append({
  641. 'type': 'table_row_missing',
  642. 'position': f'第{actual_row_num}行',
  643. 'file1_value': '',
  644. 'file2_value': ', '.join(row2),
  645. 'description': f'文件1缺少第{actual_row_num}行',
  646. 'severity': 'high',
  647. 'row_index': actual_row_num
  648. })
  649. continue
  650. if not row2:
  651. differences.append({
  652. 'type': 'table_row_missing',
  653. 'position': f'第{actual_row_num}行',
  654. 'file1_value': ', '.join(row1),
  655. 'file2_value': '',
  656. 'description': f'文件2缺少第{actual_row_num}行',
  657. 'severity': 'high',
  658. 'row_index': actual_row_num
  659. })
  660. continue
  661. # 逐列比较
  662. max_cols = max(len(row1), len(row2))
  663. for col_idx in range(max_cols):
  664. cell1 = row1[col_idx] if col_idx < len(row1) else ''
  665. cell2 = row2[col_idx] if col_idx < len(row2) else ''
  666. if "[图片内容-忽略]" in cell1 or "[图片内容-忽略]" in cell2:
  667. continue
  668. column_type = column_types[col_idx] if col_idx < len(column_types) else 'text'
  669. column_name = headers1[col_idx] if col_idx < len(headers1) else f'列{col_idx + 1}'
  670. compare_result = self.compare_cell_value(cell1, cell2, column_type, column_name)
  671. if not compare_result['match']:
  672. diff_info = compare_result['difference']
  673. type_mismatch_note = ""
  674. if col_idx in mismatched_columns:
  675. type_mismatch_note = " [列类型冲突]"
  676. # ✅ 确定最终严重度:优先使用 diff_info 的 severity
  677. base_severity = diff_info.get('severity', 'medium')
  678. # 如果列类型冲突,且基础严重度不是 high,则提升到 high
  679. final_severity = 'high' if col_idx in mismatched_columns else base_severity
  680. differences.append({
  681. 'type': diff_info['type'],
  682. 'position': f'第{actual_row_num}行第{col_idx + 1}列',
  683. 'file1_value': diff_info['value1'],
  684. 'file2_value': diff_info['value2'],
  685. 'description': diff_info['description'] + type_mismatch_note,
  686. 'severity': final_severity, # ✅ 使用计算后的严重度
  687. 'row_index': actual_row_num,
  688. 'col_index': col_idx,
  689. 'column_name': column_name,
  690. 'column_type': column_type,
  691. 'column_type_mismatch': col_idx in mismatched_columns,
  692. })
  693. return differences