File size: 4,693 Bytes
48a689b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
complexity.py — 正式复杂度分层 complexity_v1(策略文档 §4.1/§4.3)
================================================================================
输入: GT 逻辑网格(canonical_teds.parse_table 的输出)。
输出特征:
  R,C,N          逻辑行/列/单元格数
  M              合并格数 / N
  Amax           max(rowspan*colspan)
  H              表头层级(可靠识别规则: GT 中含 <th> 或 OTSL 无标记 => 未知=0;
                 对 HTML GT, 首个非表头行之前含 th 的连续行数为 H;
                 无法可靠识别时 H=0 表示"未知", 不凭模型猜测)
  n_merge_cells  合并格数(rowspan>1 或 colspan>1)
  n_merge_both   同时跨行跨列格数
  n_merge_rowspan/n_merge_colspan
  covered_ratio  被合并覆盖的网格比例(1 - N/(R*C))
  tags           long=(R>=30), wide=(C>=12),
                 merge_dense=(n_merge>=10 或 M>=0.20),
                 extreme_long=(R>=60), very_long=(R>=100),
                 extreme_wide=(C>=20), very_wide=(C>=30)
分层(frozen, 复杂优先、再简单、其余中等):
  complex : R>=30 | C>=12 | N>=200 | M>=0.20 | n_merge>=10 | Amax>=8 | H>=3
            | 存在同时跨行跨列合并格
  simple  : 非 complex 且 R<=10 & C<=6 & N<=60 & 所有跨度=1 & H<=1
  medium  : 其余可解析 GT
GT 解析失败 => complexity="unparseable", 进数据问题队列。

版本: COMPLEXITY_VERSION = "complexity_v1" (2026-09-15 冻结)
"""
from typing import Any, Dict

COMPLEXITY_VERSION = "complexity_v1"


def gt_header_level(tbl: Dict[str, Any], th_cells=None) -> int:
    """可核验表头层级: HTML GT 提供 th 单元格坐标时, 取首部连续 th 行数(0=未知)。"""
    if not th_cells:
        return 0
    rows = sorted({r for r, c in th_cells})
    h = 0
    for r in range(tbl["num_rows"]):
        row_cells = [c for rr, c in th_cells if rr == r]
        n_cells_row = sum(1 for cell in tbl["cells"] if cell.r0 == r)
        if row_cells and len(row_cells) >= max(1, n_cells_row):
            h += 1
        else:
            break
    return h


def grid_features(tbl: Dict[str, Any], th_cells=None) -> Dict[str, Any]:
    cells = tbl["cells"]
    R, C = tbl["num_rows"], tbl["num_cols"]
    N = len(cells)
    n_merge = sum(1 for c in cells if c.row_span > 1 or c.col_span > 1)
    n_both = sum(1 for c in cells if c.row_span > 1 and c.col_span > 1)
    n_rs = sum(1 for c in cells if c.row_span > 1)
    n_cs = sum(1 for c in cells if c.col_span > 1)
    amax = max((c.row_span * c.col_span for c in cells), default=1)
    M = (n_merge / N) if N else 0.0
    covered = 0.0 if R * C == 0 else max(0.0, 1.0 - N / (R * C))
    H = gt_header_level(tbl, th_cells)
    feats = {
        "R": R, "C": C, "N": N, "M": round(M, 4), "Amax": amax,
        "n_merge_cells": n_merge, "n_merge_both": n_both,
        "n_merge_rowspan": n_rs, "n_merge_colspan": n_cs,
        "covered_ratio": round(covered, 4), "H": H,
    }
    tags = []
    if R >= 30:
        tags.append("long")
    if C >= 12:
        tags.append("wide")
    if n_merge >= 10 or M >= 0.20:
        tags.append("merge_dense")
    if R >= 100:
        tags.append("very_long")
    elif R >= 60:
        tags.append("extreme_long")
    if C >= 30:
        tags.append("very_wide")
    elif C >= 20:
        tags.append("extreme_wide")
    feats["tags"] = tags

    is_complex = (R >= 30 or C >= 12 or N >= 200 or M >= 0.20
                  or n_merge >= 10 or amax >= 8 or H >= 3 or n_both > 0)
    if is_complex:
        level = "complex"
    else:
        all_span1 = (n_merge == 0)
        if R <= 10 and C <= 6 and N <= 60 and all_span1 and H <= 1:
            level = "simple"
        else:
            level = "medium"
    feats["complexity"] = level
    return feats


def features_from_html(raw_html: str, text_profile: str = "canonical"):
    """HTML GT -> (features, th_cells)。"""
    from canonical_teds import parse_html_table
    tbl = parse_html_table(raw_html, text_profile)
    th = set()
    try:
        from lxml import html as _h
        doc = _h.document_fromstring(raw_html.strip())
        table = doc.xpath("//table")[0]
        for r, tr in enumerate(table.xpath(".//tr")):
            for el in tr.xpath("./th|.//th"):
                th.add((r, 0))
    except Exception:  # noqa: BLE001
        th = set()
    return grid_features(tbl, th), tbl


def features_from_otsl(raw_otsl: str, text_profile: str = "canonical"):
    """OTSL GT -> (features, tbl)。OTSL 无表头标记, H=0(未知)。"""
    from canonical_teds import otsl_to_cells
    tbl = otsl_to_cells(raw_otsl, text_profile)
    return grid_features(tbl), tbl