table_comparator.py 33 KB

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