table_comparator.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  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. best_header_row = 0
  242. best_score = 0
  243. # 如果表格行数小于10,取全部行进行检测,如果大于10,取前10行
  244. for row_idx, row in enumerate(table[:10]):
  245. if not row:
  246. continue
  247. # 计算关键字匹配分数
  248. keyword_count = 0
  249. non_empty_cells = 0
  250. for cell in row:
  251. cell_text = str(cell).strip()
  252. if cell_text:
  253. non_empty_cells += 1
  254. cell_lower = cell_text.lower()
  255. for keyword in header_keywords:
  256. if keyword in cell_lower:
  257. keyword_count += 1
  258. break
  259. # 避免空行或几乎空的行
  260. if non_empty_cells < 3:
  261. continue
  262. # 计算得分:关键字比例 + 列数奖励
  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. if self._is_data_row(next_row):
  270. score += 0.2
  271. if score > best_score:
  272. best_score = score
  273. best_header_row = row_idx
  274. # 如果最佳得分太低,返回0(第一行)
  275. if best_score < 0.3:
  276. print(f" ⚠️ 未检测到明确表头,默认使用第1行 (得分: {best_score:.2f})")
  277. return 0
  278. print(f" 📍 检测到表头在第 {best_header_row + 1} 行 (得分: {best_score:.2f})")
  279. return best_header_row
  280. def _is_data_row(self, row: List[str]) -> bool:
  281. """判断是否为数据行"""
  282. if not row:
  283. return False
  284. data_pattern_count = 0
  285. non_empty_count = 0
  286. for cell in row:
  287. cell_text = str(cell).strip()
  288. if not cell_text:
  289. continue
  290. non_empty_count += 1
  291. # 包含数字
  292. if re.search(r'\d', cell_text):
  293. data_pattern_count += 1
  294. # 包含日期格式
  295. if re.search(r'\d{4}[-/年]\d{1,2}[-/月]\d{1,2}', cell_text):
  296. data_pattern_count += 1
  297. # 包含金额格式
  298. if re.search(r'-?\d+[,,]?\d*\.?\d+', cell_text):
  299. data_pattern_count += 1
  300. if non_empty_count == 0:
  301. return False
  302. # 至少30%的单元格包含数据特征
  303. return data_pattern_count / non_empty_count >= 0.3
  304. def compare_table_headers(self, headers1: List[str], headers2: List[str]) -> Dict:
  305. """比较表格表头"""
  306. result = {
  307. 'match': True,
  308. 'differences': [],
  309. 'column_mapping': {},
  310. 'similarity_scores': []
  311. }
  312. if len(headers1) != len(headers2):
  313. result['match'] = False
  314. result['differences'].append({
  315. 'type': 'table_header_critical',
  316. 'description': f'表头列数不一致: {len(headers1)} vs {len(headers2)}',
  317. 'severity': 'critical'
  318. })
  319. return result
  320. for i, (h1, h2) in enumerate(zip(headers1, headers2)):
  321. norm_h1 = self.normalize_header_text(h1)
  322. norm_h2 = self.normalize_header_text(h2)
  323. similarity = self.calculator.calculate_text_similarity(norm_h1, norm_h2)
  324. result['similarity_scores'].append({
  325. 'column_index': i,
  326. 'header1': h1,
  327. 'header2': h2,
  328. 'similarity': similarity
  329. })
  330. if similarity < self.header_similarity_threshold:
  331. result['match'] = False
  332. result['differences'].append({
  333. 'type': 'table_header_mismatch',
  334. 'column_index': i,
  335. 'header1': h1,
  336. 'header2': h2,
  337. 'similarity': similarity,
  338. 'description': f'第{i+1}列表头不匹配: "{h1}" vs "{h2}" (相似度: {similarity:.1f}%)',
  339. 'severity': 'medium' if similarity < 50 else 'high'
  340. })
  341. else:
  342. result['column_mapping'][i] = i
  343. return result
  344. def compare_cell_value(self, value1: str, value2: str, column_type: str,
  345. column_name: str = '') -> Dict:
  346. """比较单元格值"""
  347. result = {
  348. 'match': True,
  349. 'difference': None
  350. }
  351. v1 = self.text_processor.normalize_text(value1)
  352. v2 = self.text_processor.normalize_text(value2)
  353. if v1 == v2:
  354. return result
  355. if column_type == 'text_number':
  356. norm_v1 = self.detector.normalize_text_number(v1)
  357. norm_v2 = self.detector.normalize_text_number(v2)
  358. if norm_v1 == norm_v2:
  359. result['match'] = False
  360. result['difference'] = {
  361. 'type': 'table_text',
  362. 'value1': value1,
  363. 'value2': value2,
  364. 'description': f'文本型数字格式差异: "{value1}" vs "{value2}" (内容相同,空格不同)',
  365. 'severity': 'low'
  366. }
  367. else:
  368. result['match'] = False
  369. result['difference'] = {
  370. 'type': 'table_text',
  371. 'value1': value1,
  372. 'value2': value2,
  373. 'description': f'文本型数字不一致: {value1} vs {value2}',
  374. 'severity': 'high'
  375. }
  376. return result
  377. if column_type == 'numeric':
  378. if self.detector.is_numeric(v1) and self.detector.is_numeric(v2):
  379. num1 = self.detector.parse_number(v1)
  380. num2 = self.detector.parse_number(v2)
  381. if abs(num1 - num2) > 0.01:
  382. result['match'] = False
  383. result['difference'] = {
  384. 'type': 'table_amount',
  385. 'value1': value1,
  386. 'value2': value2,
  387. 'diff_amount': abs(num1 - num2),
  388. 'description': f'金额不一致: {value1} vs {value2}',
  389. 'severity': 'high' # ✅ 修改:金额差异 = high
  390. }
  391. else:
  392. result['match'] = False
  393. result['difference'] = {
  394. 'type': 'table_text',
  395. 'value1': value1,
  396. 'value2': value2,
  397. 'description': f'长数字字符串不一致: {value1} vs {value2}',
  398. 'severity': 'medium' # ✅ 修改:数字字符串差异 = medium
  399. }
  400. elif column_type == 'datetime':
  401. datetime1 = self.detector.extract_datetime(v1)
  402. datetime2 = self.detector.extract_datetime(v2)
  403. if datetime1 != datetime2:
  404. result['match'] = False
  405. result['difference'] = {
  406. 'type': 'table_datetime',
  407. 'value1': value1,
  408. 'value2': value2,
  409. 'description': f'日期时间不一致: {value1} vs {value2}',
  410. 'severity': 'medium' # 日期差异 = medium
  411. }
  412. else:
  413. similarity = self.calculator.calculate_text_similarity(v1, v2)
  414. if similarity < self.content_similarity_threshold:
  415. result['match'] = False
  416. result['difference'] = {
  417. 'type': 'table_text',
  418. 'value1': value1,
  419. 'value2': value2,
  420. 'similarity': similarity,
  421. 'description': f'文本不一致: {value1} vs {value2} (相似度: {similarity:.1f}%)',
  422. 'severity': 'low' if similarity > 80 else 'medium' # 根据相似度判断
  423. }
  424. return result
  425. def compare_tables(self, table1: List[List[str]], table2: List[List[str]]) -> List[Dict]:
  426. """标准表格比较"""
  427. differences = []
  428. max_rows = max(len(table1), len(table2))
  429. for i in range(max_rows):
  430. row1 = table1[i] if i < len(table1) else []
  431. row2 = table2[i] if i < len(table2) else []
  432. max_cols = max(len(row1), len(row2))
  433. for j in range(max_cols):
  434. cell1 = row1[j] if j < len(row1) else ""
  435. cell2 = row2[j] if j < len(row2) else ""
  436. if "[图片内容-忽略]" in cell1 or "[图片内容-忽略]" in cell2:
  437. continue
  438. if cell1 != cell2:
  439. if self.detector.is_numeric(cell1) and self.detector.is_numeric(cell2):
  440. num1 = self.detector.parse_number(cell1)
  441. num2 = self.detector.parse_number(cell2)
  442. if abs(num1 - num2) > 0.001:
  443. differences.append({
  444. 'type': 'table_amount',
  445. 'position': f'行{i+1}列{j+1}',
  446. 'file1_value': cell1,
  447. 'file2_value': cell2,
  448. 'description': f'金额不一致: {cell1} vs {cell2}',
  449. 'severity': 'high', # ✅ 添加:金额差异 = high
  450. 'row_index': i,
  451. 'col_index': j
  452. })
  453. else:
  454. differences.append({
  455. 'type': 'table_text',
  456. 'position': f'行{i+1}列{j+1}',
  457. 'file1_value': cell1,
  458. 'file2_value': cell2,
  459. 'description': f'文本不一致: {cell1} vs {cell2}',
  460. 'severity': 'medium', # ✅ 添加:文本差异 = medium
  461. 'row_index': i,
  462. 'col_index': j
  463. })
  464. return differences
  465. def compare_table_flow_list(self, table1: List[List[str]], table2: List[List[str]]) -> List[Dict]:
  466. """流水列表表格比较算法"""
  467. differences = []
  468. if not table1 or not table2:
  469. return [{
  470. 'type': 'table_empty',
  471. 'description': '表格为空',
  472. 'severity': 'critical'
  473. }]
  474. print(f"\n📋 开始流水表格对比...")
  475. # 检测表头位置
  476. header_row_idx1 = self.detect_table_header_row(table1)
  477. header_row_idx2 = self.detect_table_header_row(table2)
  478. if header_row_idx1 != header_row_idx2:
  479. differences.append({
  480. 'type': 'table_header_position',
  481. 'position': '表头位置',
  482. 'file1_value': f'第{header_row_idx1 + 1}行',
  483. 'file2_value': f'第{header_row_idx2 + 1}行',
  484. 'description': f'表头位置不一致: 文件1在第{header_row_idx1 + 1}行,文件2在第{header_row_idx2 + 1}行',
  485. 'severity': 'high'
  486. })
  487. # 比对表头前的内容
  488. if header_row_idx1 > 0 or header_row_idx2 > 0:
  489. print(f"\n📝 对比表头前的内容...")
  490. pre_header_table1 = table1[:header_row_idx1] if header_row_idx1 > 0 else []
  491. pre_header_table2 = table2[:header_row_idx2] if header_row_idx2 > 0 else []
  492. if pre_header_table1 or pre_header_table2:
  493. pre_header_diffs = self.compare_tables(pre_header_table1, pre_header_table2)
  494. for diff in pre_header_diffs:
  495. diff['type'] = 'table_pre_header'
  496. diff['position'] = f"表头前{diff['position']}"
  497. diff['severity'] = 'medium'
  498. differences.extend(pre_header_diffs)
  499. # 比较表头
  500. headers1 = table1[header_row_idx1]
  501. headers2 = table2[header_row_idx2]
  502. print(f"\n📋 对比表头...")
  503. header_result = self.compare_table_headers(headers1, headers2)
  504. if not header_result['match']:
  505. print(f"\n⚠️ 表头文字存在差异")
  506. for diff in header_result['differences']:
  507. differences.append({
  508. 'type': diff.get('type', 'table_header_mismatch'),
  509. 'position': '表头',
  510. 'file1_value': diff.get('header1', ''),
  511. 'file2_value': diff.get('header2', ''),
  512. 'description': diff['description'],
  513. 'severity': diff.get('severity', 'high'),
  514. })
  515. if diff.get('severity') == 'critical':
  516. return differences
  517. # 检测列类型并比较数据行
  518. column_types1 = self._detect_column_types(table1, header_row_idx1, headers1)
  519. column_types2 = self._detect_column_types(table2, header_row_idx2, headers2)
  520. # 处理列类型不匹配
  521. mismatched_columns = self._check_column_type_mismatch(
  522. column_types1, column_types2, headers1, headers2, differences
  523. )
  524. # 合并列类型
  525. column_types = self._merge_column_types(column_types1, column_types2, mismatched_columns)
  526. # 逐行比较数据
  527. data_diffs = self._compare_data_rows(
  528. table1, table2, header_row_idx1, header_row_idx2,
  529. headers1, column_types, mismatched_columns, header_result['match']
  530. )
  531. differences.extend(data_diffs)
  532. print(f"\n✅ 流水表格对比完成,发现 {len(differences)} 个差异")
  533. return differences
  534. def _detect_column_types(self, table: List[List[str]], header_row_idx: int,
  535. headers: List[str]) -> List[str]:
  536. """检测列类型"""
  537. column_types = []
  538. for col_idx in range(len(headers)):
  539. col_values = [
  540. row[col_idx]
  541. for row in table[header_row_idx + 1:]
  542. if col_idx < len(row)
  543. ]
  544. col_type = self.detector.detect_column_type(col_values)
  545. column_types.append(col_type)
  546. return column_types
  547. def _check_column_type_mismatch(self, column_types1: List[str], column_types2: List[str],
  548. headers1: List[str], headers2: List[str],
  549. differences: List[Dict]) -> List[int]:
  550. """检查列类型不匹配"""
  551. mismatched_columns = []
  552. for col_idx in range(min(len(column_types1), len(column_types2))):
  553. if column_types1[col_idx] != column_types2[col_idx]:
  554. mismatched_columns.append(col_idx)
  555. differences.append({
  556. 'type': 'table_column_type_mismatch',
  557. 'position': f'第{col_idx + 1}列',
  558. 'file1_value': f'{headers1[col_idx]} ({column_types1[col_idx]})',
  559. 'file2_value': f'{headers2[col_idx]} ({column_types2[col_idx]})',
  560. 'description': f'列类型不一致: {column_types1[col_idx]} vs {column_types2[col_idx]}',
  561. 'severity': 'high',
  562. 'column_index': col_idx
  563. })
  564. total_columns = min(len(column_types1), len(column_types2))
  565. mismatch_ratio = len(mismatched_columns) / total_columns if total_columns > 0 else 0
  566. if mismatch_ratio > 0.5:
  567. differences.append({
  568. 'type': 'table_header_critical',
  569. 'position': '表格列类型',
  570. 'file1_value': f'{len(mismatched_columns)}列类型不一致',
  571. 'file2_value': f'共{total_columns}列',
  572. 'description': f'列类型差异过大: {len(mismatched_columns)}/{total_columns}列不匹配 ({mismatch_ratio:.1%})',
  573. 'severity': 'critical'
  574. })
  575. return mismatched_columns
  576. def _merge_column_types(self, column_types1: List[str], column_types2: List[str],
  577. mismatched_columns: List[int]) -> List[str]:
  578. """合并列类型"""
  579. column_types = []
  580. for col_idx in range(max(len(column_types1), len(column_types2))):
  581. if col_idx >= len(column_types1):
  582. column_types.append(column_types2[col_idx])
  583. elif col_idx >= len(column_types2):
  584. column_types.append(column_types1[col_idx])
  585. elif col_idx in mismatched_columns:
  586. type1 = column_types1[col_idx]
  587. type2 = column_types2[col_idx]
  588. if type1 == 'text' or type2 == 'text':
  589. column_types.append('text')
  590. elif type1 == 'text_number' or type2 == 'text_number':
  591. column_types.append('text_number')
  592. else:
  593. column_types.append(type1)
  594. else:
  595. column_types.append(column_types1[col_idx])
  596. return column_types
  597. def _compare_data_rows(self, table1: List[List[str]], table2: List[List[str]],
  598. header_row_idx1: int, header_row_idx2: int,
  599. headers1: List[str], column_types: List[str],
  600. mismatched_columns: List[int], header_match: bool) -> List[Dict]:
  601. """逐行比较数据"""
  602. differences = []
  603. data_rows1 = table1[header_row_idx1 + 1:]
  604. data_rows2 = table2[header_row_idx2 + 1:]
  605. max_rows = max(len(data_rows1), len(data_rows2))
  606. for row_idx in range(max_rows):
  607. row1 = data_rows1[row_idx] if row_idx < len(data_rows1) else []
  608. row2 = data_rows2[row_idx] if row_idx < len(data_rows2) else []
  609. actual_row_num = header_row_idx1 + row_idx + 2
  610. if not row1:
  611. differences.append({
  612. 'type': 'table_row_missing',
  613. 'position': f'第{actual_row_num}行',
  614. 'file1_value': '',
  615. 'file2_value': ', '.join(row2),
  616. 'description': f'文件1缺少第{actual_row_num}行',
  617. 'severity': 'high',
  618. 'row_index': actual_row_num
  619. })
  620. continue
  621. if not row2:
  622. differences.append({
  623. 'type': 'table_row_missing',
  624. 'position': f'第{actual_row_num}行',
  625. 'file1_value': ', '.join(row1),
  626. 'file2_value': '',
  627. 'description': f'文件2缺少第{actual_row_num}行',
  628. 'severity': 'high',
  629. 'row_index': actual_row_num
  630. })
  631. continue
  632. # 逐列比较
  633. max_cols = max(len(row1), len(row2))
  634. for col_idx in range(max_cols):
  635. cell1 = row1[col_idx] if col_idx < len(row1) else ''
  636. cell2 = row2[col_idx] if col_idx < len(row2) else ''
  637. if "[图片内容-忽略]" in cell1 or "[图片内容-忽略]" in cell2:
  638. continue
  639. column_type = column_types[col_idx] if col_idx < len(column_types) else 'text'
  640. column_name = headers1[col_idx] if col_idx < len(headers1) else f'列{col_idx + 1}'
  641. compare_result = self.compare_cell_value(cell1, cell2, column_type, column_name)
  642. if not compare_result['match']:
  643. diff_info = compare_result['difference']
  644. type_mismatch_note = ""
  645. if col_idx in mismatched_columns:
  646. type_mismatch_note = " [列类型冲突]"
  647. # ✅ 确定最终严重度:优先使用 diff_info 的 severity
  648. base_severity = diff_info.get('severity', 'medium')
  649. # 如果列类型冲突,且基础严重度不是 high,则提升到 high
  650. final_severity = 'high' if col_idx in mismatched_columns else base_severity
  651. differences.append({
  652. 'type': diff_info['type'],
  653. 'position': f'第{actual_row_num}行第{col_idx + 1}列',
  654. 'file1_value': diff_info['value1'],
  655. 'file2_value': diff_info['value2'],
  656. 'description': diff_info['description'] + type_mismatch_note,
  657. 'severity': final_severity, # ✅ 使用计算后的严重度
  658. 'row_index': actual_row_num,
  659. 'col_index': col_idx,
  660. 'column_name': column_name,
  661. 'column_type': column_type,
  662. 'column_type_mismatch': col_idx in mismatched_columns,
  663. })
  664. return differences