listract 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,16 @@
1
+ """Template-free structural list extraction.
2
+
3
+ The package is intentionally small and dependency-light:
4
+ - DOM parsing: lxml
5
+ - static fetch: requests
6
+ - browser fallback: playwright (optional at runtime)
7
+ """
8
+
9
+ from .extractor import ListExtractor
10
+ from .features import analyze_html
11
+ from .manifest import build_manifest, diff_manifest, verify_click_entries, verify_link
12
+ from .production_gate import input_health, production_decision
13
+
14
+ __version__ = "0.1.0"
15
+
16
+ __all__ = ["ListExtractor", "analyze_html", "build_manifest", "diff_manifest", "verify_link", "verify_click_entries", "production_decision", "input_health"]
@@ -0,0 +1,286 @@
1
+ """Generic click-only list resolver.
2
+
3
+ Some list rows are ``div``/``li`` elements with no ``<a href>``: the detail URL
4
+ only exists after the row's click handler runs (``window.open``, Vue router,
5
+ ``location.href``, ...). This module discovers such repeated rows structurally
6
+ and resolves the final URL with a trusted Playwright click.
7
+
8
+ There are no school names, domains or fixed selectors here.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ import time
14
+ from typing import Any
15
+ from urllib.parse import urlparse
16
+
17
+ from lxml import html as LH
18
+
19
+ from .features import (
20
+ DATE_RE,
21
+ SCORE_RE,
22
+ _boilerplate_score,
23
+ canonicalize_url,
24
+ clean_title,
25
+ norm_text,
26
+ textlen,
27
+ )
28
+
29
+ SKIP_TAGS = {
30
+ "head", "html", "body", "script", "style", "noscript",
31
+ "nav", "header", "footer", "aside",
32
+ }
33
+
34
+
35
+ def _clean_tree(raw: str) -> Any:
36
+ d = LH.fromstring(raw)
37
+ for bad in d.xpath("//script|//style|//noscript"):
38
+ parent = bad.getparent()
39
+ if parent is not None:
40
+ parent.remove(bad)
41
+ return d
42
+
43
+
44
+ def _text_len(s: str) -> int:
45
+ return len(re.sub(r"\s+", "", s or ""))
46
+
47
+
48
+ def find_clickable_lists(raw: str, max_results: int = 5) -> list[dict[str, Any]]:
49
+ """Return repeated href-less row groups, ordered by structural score.
50
+
51
+ A row group is a set of sibling children sharing a class signature. It is
52
+ click-only when almost none of the rows contain an ``<a href>`` and the
53
+ rows carry title/date-sized text.
54
+ """
55
+ d = _clean_tree(raw)
56
+ page_text = norm_text(d.text_content())
57
+ page_len = max(1, textlen(page_text))
58
+ out: list[dict[str, Any]] = []
59
+ for el in d.iter():
60
+ if not isinstance(el.tag, str) or el.tag in SKIP_TAGS:
61
+ continue
62
+ kids = [c for c in el if isinstance(c.tag, str)]
63
+ if len(kids) < 3:
64
+ continue
65
+ groups: dict[tuple[str, tuple[str, ...]], list[Any]] = {}
66
+ for child in kids:
67
+ key = (child.tag, tuple(sorted((child.get("class") or "").split())))
68
+ groups.setdefault(key, []).append(child)
69
+ specs: list[tuple[Any, list[Any], bool]] = [
70
+ (key, group, False) for key, group in groups.items() if len(group) >= 3
71
+ ]
72
+ # Loose fallback only when exact classes are too fragmented. If one
73
+ # exact group already covers most children, mixing breadcrumbs or
74
+ # "view more" rows into it would corrupt the row count.
75
+ largest_exact = max((len(g) for g in groups.values()), default=0)
76
+ if largest_exact < 3:
77
+ by_tag: dict[str, list[Any]] = {}
78
+ for child in kids:
79
+ by_tag.setdefault(child.tag, []).append(child)
80
+ for tag, group in by_tag.items():
81
+ if len(group) >= 3:
82
+ specs.append((f"LOOSE|{tag}", group, True))
83
+ for key, rows, loose in specs:
84
+ hrefs = sum(len(r.xpath(".//a[@href]")) for r in rows)
85
+ if hrefs > max(1, len(rows) * 0.2):
86
+ continue
87
+ texts = [norm_text(r.text_content()) for r in rows]
88
+ lens = [_text_len(t) for t in texts]
89
+ if not lens or sum(lens) / len(lens) < 8:
90
+ continue
91
+ dates = sum(1 for t in texts if DATE_RE.search(t))
92
+ date_ratio = dates / len(rows)
93
+ titleish = sum(1 for t in texts if len(clean_title(re.sub(DATE_RE, "", t))) >= 6)
94
+ share = textlen(el.text_content()) / page_len
95
+ bl = _boilerplate_score(el)
96
+ if share > 0.85 or bl > 3:
97
+ continue
98
+ score = 4 * min(len(rows), 10) + 2 * dates + titleish
99
+ if date_ratio >= 0.4:
100
+ score += 3
101
+ score -= 2 * bl
102
+ out.append({
103
+ "container_xpath": d.getroottree().getpath(el),
104
+ "container_tag": el.tag,
105
+ "container_class": (el.get("class") or "")[:120],
106
+ "selector_path": _selector_path(el),
107
+ "n": len(rows),
108
+ "date_ratio": round(date_ratio, 3),
109
+ "avg_len": round(sum(lens) / len(lens), 1),
110
+ "share": round(share, 3),
111
+ "loose": loose,
112
+ "score": round(score, 1),
113
+ "rows": [
114
+ {
115
+ "xpath": d.getroottree().getpath(r),
116
+ "tag": r.tag,
117
+ "class": (r.get("class") or "")[:120],
118
+ "text": t[:300],
119
+ "title": clean_title(re.sub(DATE_RE, "", t)),
120
+ "date": (DATE_RE.search(t).group(0) if DATE_RE.search(t) else ""),
121
+ }
122
+ for r, t in zip(rows, texts)
123
+ ],
124
+ })
125
+ seen: set[str] = set()
126
+ final: list[dict[str, Any]] = []
127
+ for c in sorted(out, key=lambda x: x["score"], reverse=True):
128
+ if c["container_xpath"] in seen:
129
+ continue
130
+ seen.add(c["container_xpath"])
131
+ final.append(c)
132
+ return final[:max_results]
133
+
134
+
135
+ def _selector_path(el: Any) -> str:
136
+ """Compact selector used only for display/gold alignment."""
137
+ parts: list[str] = []
138
+ cur = el
139
+ while cur is not None and isinstance(cur.tag, str) and len(parts) < 4:
140
+ bit = cur.tag
141
+ if cur.get("id"):
142
+ bit += f"#{cur.get('id')}"
143
+ elif cur.get("class"):
144
+ bit += "." + ".".join((cur.get("class") or "").split()[:2])
145
+ parts.append(bit)
146
+ cur = cur.getparent()
147
+ return " > ".join(reversed(parts))
148
+
149
+
150
+ def is_relevant_click_candidate(candidate: dict[str, Any], page_text: str = "") -> bool:
151
+ """Cheap business gate before spending clicks.
152
+
153
+ A click-only group should look like an article/score list, not a homepage
154
+ news carousel or a map filter. This is a content/structural signal, not a
155
+ site rule; the downstream page-status and semantic models still decide.
156
+ """
157
+ if int(candidate.get("n") or 0) < 4:
158
+ return False
159
+ if float(candidate.get("date_ratio") or 0) < 0.5:
160
+ return False
161
+ if float(candidate.get("avg_len") or 0) < 10:
162
+ return False
163
+ group_text = " ".join(r.get("text") or "" for r in candidate.get("rows") or [])
164
+ return bool(SCORE_RE.search(group_text) or SCORE_RE.search(page_text[:3000]))
165
+
166
+
167
+ def _click_target(page: Any, row_xpath: str) -> tuple[str, str]:
168
+ """Return (url, target_kind) for one row; no fake URL is produced."""
169
+ target = page.locator("xpath=" + row_xpath)
170
+ before = page.url
171
+ popups: list[Any] = []
172
+
173
+ def on_popup(p: Any) -> None:
174
+ popups.append(p)
175
+
176
+ page.once("popup", on_popup)
177
+ try:
178
+ target.click(timeout=5000)
179
+ page.wait_for_timeout(1800)
180
+ if popups:
181
+ p = popups[0]
182
+ try:
183
+ p.wait_for_load_state("domcontentloaded", timeout=5000)
184
+ except Exception:
185
+ pass
186
+ url = p.url
187
+ try:
188
+ p.close()
189
+ except Exception:
190
+ pass
191
+ if url and url != "about:blank":
192
+ return url, "row"
193
+ if page.url != before:
194
+ return page.url, "row"
195
+ except Exception:
196
+ pass
197
+ # A handler can be on a nested title node instead of the row itself.
198
+ for xp in (
199
+ ".//span[@title or @aria-label]",
200
+ ".//span[normalize-space()]",
201
+ ".//p[normalize-space()]",
202
+ ".//a",
203
+ ".//div[normalize-space()]",
204
+ ):
205
+ try:
206
+ child = target.locator("xpath=" + xp).first
207
+ if child.count() == 0:
208
+ continue
209
+ except Exception:
210
+ continue
211
+ popups.clear()
212
+ page.once("popup", on_popup)
213
+ before2 = page.url
214
+ try:
215
+ child.click(timeout=5000)
216
+ page.wait_for_timeout(1800)
217
+ if popups:
218
+ p = popups[0]
219
+ try:
220
+ p.wait_for_load_state("domcontentloaded", timeout=5000)
221
+ except Exception:
222
+ pass
223
+ url = p.url
224
+ try:
225
+ p.close()
226
+ except Exception:
227
+ pass
228
+ if url and url != "about:blank":
229
+ return url, "child"
230
+ if page.url != before2:
231
+ return page.url, "child"
232
+ except Exception:
233
+ continue
234
+ return "", "none"
235
+
236
+
237
+ def _restore(page: Any, base_url: str) -> None:
238
+ if page.url.split("#")[0] == base_url.split("#")[0]:
239
+ return
240
+ try:
241
+ page.go_back(timeout=10000)
242
+ page.wait_for_timeout(1000)
243
+ except Exception:
244
+ try:
245
+ page.goto(base_url, wait_until="domcontentloaded", timeout=30000)
246
+ page.wait_for_timeout(1500)
247
+ except Exception:
248
+ pass
249
+
250
+
251
+ def resolve_click_candidate(
252
+ page: Any,
253
+ base_url: str,
254
+ candidate: dict[str, Any],
255
+ max_rows: int | None = None,
256
+ ) -> dict[str, dict[str, Any]]:
257
+ """Click every row in one candidate and return a row-xpath -> link map.
258
+
259
+ A row whose click produces no URL is recorded as ``linkless``; it is never
260
+ assigned an invented detail URL. The main page is restored after same-tab
261
+ navigation, and popup pages are closed immediately.
262
+ """
263
+ links: dict[str, dict[str, Any]] = {}
264
+ rows = candidate.get("rows") or []
265
+ if max_rows is not None:
266
+ rows = rows[:max_rows]
267
+ for row in rows:
268
+ _restore(page, base_url)
269
+ url, target_kind = _click_target(page, row["xpath"])
270
+ title = clean_title(row.get("title") or row.get("text") or "")
271
+ date = row.get("date") or ""
272
+ if url:
273
+ url = canonicalize_url(base_url, url)
274
+ status = "resolved"
275
+ else:
276
+ status = "linkless"
277
+ links[row["xpath"]] = {
278
+ "title": title[:200],
279
+ "date": date,
280
+ "url": url,
281
+ "link_mode": "click",
282
+ "link_status": status,
283
+ "target": target_kind,
284
+ }
285
+ _restore(page, base_url)
286
+ return links
@@ -0,0 +1,371 @@
1
+ """v4 extraction: DOM candidates -> candidate ranker -> page list/no-list model.
2
+
3
+ There is one decision path and no post-hoc rules:
4
+
5
+ HTML -> candidates -> P(candidate is the main list)
6
+ -> page vector (top candidates + page evidence)
7
+ -> P(the main content is a list) -> list / no_list
8
+
9
+ The container shown to the caller is the highest candidate under a fixed
10
+ blend of model score and structural evidence (0.75 / 0.25). The page status
11
+ does not use that blend; it uses the model-ranked candidates, exactly the
12
+ feature distribution the page model was trained on.
13
+
14
+ Only two questions are answered here: is the main content a list, and which
15
+ container holds it. Entry semantics are left to the downstream rule layer.
16
+ Input is one HTML document, rendered or not; fetching is only the separate
17
+ ``extract_url`` convenience and never changes what ``extract_html`` saw.
18
+ """
19
+ from __future__ import annotations
20
+ import json
21
+ import os
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ from .features import (
26
+ PAGE_META_KEYS, analyze_html, canonicalize_url, clean_title,
27
+ feature_vector_v3, page_vector_v3,
28
+ )
29
+ from .fetch import FetchResult, browser_fetch, fetch_static
30
+ from .manifest import build_manifest, verify_click_entries
31
+ from .model import TreeEnsemble
32
+ from .production_gate import input_health, production_decision
33
+
34
+ def _model_dir() -> Path:
35
+ """Locate the shared JSON model directory.
36
+
37
+ Priority: explicit env var, repo ``model/``, model bundled in the
38
+ ``listract`` wheel, legacy ``data_v4`` package data, current ``model/``.
39
+ """
40
+ env = os.environ.get("LIST_EXTRACT_MODEL_DIR", "").strip()
41
+ here = Path(__file__).resolve()
42
+ bundled = here.parents[1] / "listract" / "model"
43
+ candidates = [
44
+ Path(env) if env else None,
45
+ here.parents[2] / "model",
46
+ bundled,
47
+ here.parent / "data_v4",
48
+ Path.cwd() / "model",
49
+ ]
50
+ for candidate in candidates:
51
+ if candidate is not None and (candidate / "ranker_v4.json").exists():
52
+ return candidate
53
+ return bundled
54
+
55
+
56
+ PACKAGE_DATA = _model_dir()
57
+ DEFAULT_RANKER = PACKAGE_DATA / "ranker_v4.json"
58
+ DEFAULT_PAGE = PACKAGE_DATA / "page_status_v4.json"
59
+ DEFAULT_POLICY = PACKAGE_DATA / "policy_v4.json"
60
+
61
+ STATUS_LIST = "list"
62
+ STATUS_NO_LIST = "no_list"
63
+ STATUS_MANUAL = "manual_check" # compatibility only; v4 never emits it
64
+ STATUS_FETCH_ERROR = "fetch_error"
65
+ STATUS_RANK = {STATUS_LIST: 3, STATUS_NO_LIST: 1, STATUS_FETCH_ERROR: 0}
66
+
67
+ # v4 has two binary states. The threshold lives in policy_v4.json and is
68
+ # read from host-grouped OOF; it is not an abstention band.
69
+ DEFAULT_THRESHOLD = 0.35
70
+ CONTAINER_MODEL_WEIGHT = 0.75
71
+
72
+
73
+ def load_policy(path: Path = DEFAULT_POLICY) -> dict[str, Any]:
74
+ policy: dict[str, Any] = {"threshold": DEFAULT_THRESHOLD, "source": "", "score_calibration": []}
75
+ if path.exists():
76
+ data = json.loads(path.read_text(encoding="utf-8"))
77
+ policy["threshold"] = float(data.get("threshold", DEFAULT_THRESHOLD))
78
+ policy["source"] = data.get("source", "")
79
+ policy["score_calibration"] = data.get("score_calibration") or []
80
+ return policy
81
+
82
+
83
+ class ListExtractor:
84
+ def __init__(
85
+ self,
86
+ ranker: TreeEnsemble | None = None,
87
+ page_model: TreeEnsemble | None = None,
88
+ semantic_model: TreeEnsemble | None = None, # accepted, unused
89
+ semantic_click_model: TreeEnsemble | None = None, # accepted, unused
90
+ templates: Any | None = None, # accepted, unused
91
+ fetcher: Any | None = None,
92
+ review_policy: Path | None = None,
93
+ ) -> None:
94
+ self.ranker = ranker or TreeEnsemble.load(DEFAULT_RANKER)
95
+ self.page_model = page_model or TreeEnsemble.load(DEFAULT_PAGE)
96
+ policy = load_policy(review_policy or DEFAULT_POLICY)
97
+ self.threshold = float(policy["threshold"])
98
+ self.score_calibration = policy.get("score_calibration") or []
99
+ self._static = fetcher.static if fetcher else fetch_static
100
+ self._browser = fetcher.browser if fetcher else browser_fetch
101
+
102
+ # -- scoring ---------------------------------------------------------
103
+ def _rank(self, analysis: dict[str, Any]) -> list[dict[str, Any]]:
104
+ for c in analysis.get("candidates") or []:
105
+ raw = float(self.ranker.score(feature_vector_v3(c, analysis)))
106
+ c["model_score"] = round(self._calibrate(raw), 6)
107
+ return sorted(analysis.get("candidates") or [], key=lambda c: float(c["model_score"]), reverse=True)
108
+
109
+ def _calibrate(self, raw: float) -> float:
110
+ cal = self.score_calibration
111
+ if not cal:
112
+ return raw
113
+ xs = [float(x) for x, _ in cal]
114
+ ys = [float(y) for _, y in cal]
115
+ if raw <= xs[0]:
116
+ return ys[0]
117
+ if raw >= xs[-1]:
118
+ return ys[-1]
119
+ for i in range(1, len(xs)):
120
+ if raw <= xs[i]:
121
+ t = (raw - xs[i - 1]) / max(1e-12, xs[i] - xs[i - 1])
122
+ return ys[i - 1] + t * (ys[i] - ys[i - 1])
123
+ return raw
124
+
125
+ def _status(self, analysis: dict[str, Any], ranked: list[dict[str, Any]]) -> dict[str, Any]:
126
+ if not ranked:
127
+ return {"page_status": STATUS_NO_LIST, "page_probs": {}, "list_prob": 0.0, "top_prob": 0.0}
128
+ # No URL-shape gate: a channel root and an article detail can share
129
+ # the same path pattern, so the decision comes from the DOM only.
130
+ vec = page_vector_v3(analysis, ranked)
131
+ probs = self.page_model.predict_proba(vec)
132
+ classes = [str(c) for c in self.page_model.classes]
133
+ page_probs = {c: round(float(p), 4) for c, p in zip(classes, probs)}
134
+ list_prob = float(page_probs.get("1", page_probs.get(1, 0.0)))
135
+ status = STATUS_LIST if list_prob >= self.threshold else STATUS_NO_LIST
136
+ return {
137
+ "page_status": status,
138
+ "page_probs": page_probs,
139
+ "list_prob": round(list_prob, 4),
140
+ "top_prob": round(float(ranked[0].get("model_score") or 0.0), 4),
141
+ }
142
+
143
+ def _select_container(self, ranked: list[dict[str, Any]]) -> dict[str, Any] | None:
144
+ """Highest model+structure blend among candidates that have entries."""
145
+ candidates = [c for c in ranked if c.get("entries") or c.get("samples")]
146
+ if not candidates:
147
+ return None
148
+ def blended(c: dict[str, Any]) -> float:
149
+ h = min(1.0, max(0.0, float(c.get("score") or 0.0) / 20.0))
150
+ return CONTAINER_MODEL_WEIGHT * float(c.get("model_score") or 0.0) + (1.0 - CONTAINER_MODEL_WEIGHT) * h
151
+ return max(candidates, key=blended)
152
+
153
+ # -- public API ------------------------------------------------------
154
+ def extract_html(
155
+ self,
156
+ raw: str,
157
+ page_url: str,
158
+ click_links: dict[str, dict[str, Any]] | None = None,
159
+ ) -> dict[str, Any]:
160
+ analysis = analyze_html(raw, page_url, click_links=click_links)
161
+ if analysis:
162
+ analysis['page_url'] = page_url
163
+ if not analysis or not analysis.get("candidates"):
164
+ result = self._empty_result(STATUS_NO_LIST, page_url, "未找到结构候选", analysis or {})
165
+ result["list_manifest"] = build_manifest(result, raw, page_url)
166
+ return result
167
+
168
+ ranked = self._rank(analysis)
169
+ meta = self._status(analysis, ranked)
170
+ result = self._result(analysis, ranked, meta, page_url)
171
+ result["list_manifest"] = build_manifest(result, raw, page_url)
172
+ return result
173
+
174
+ def extract_url(
175
+ self,
176
+ url: str,
177
+ mode: str = "auto",
178
+ follow_pages: bool = False,
179
+ max_pages: int = 3,
180
+ verify_links: bool = True,
181
+ ) -> dict[str, Any]:
182
+ result = self._extract_one(url, mode)
183
+ if verify_links:
184
+ verify_click_entries(result, result.get("url") or url)
185
+ if follow_pages:
186
+ result = self._follow_pages(result, mode, max_pages, verify_links)
187
+ return result
188
+
189
+ def _extract_one(self, url: str, mode: str = "auto") -> dict[str, Any]:
190
+ if mode not in {"auto", "static", "browser"}:
191
+ raise ValueError(f"unknown mode: {mode}")
192
+ results = []
193
+ if mode in {"auto", "static"}:
194
+ static = self._static(url)
195
+ if static.html:
196
+ r = self.extract_html(static.html, static.final_url or url)
197
+ r.update(_fetch_meta(static)); results.append(r)
198
+ if mode == "static":
199
+ return results[0] if results else {
200
+ **self._empty_result(STATUS_FETCH_ERROR, url, static.err or "静态抓取为空", {}),
201
+ **_fetch_meta(static),
202
+ }
203
+ browser = self._browser(url)
204
+ if browser.html:
205
+ r = self.extract_html(browser.html, browser.final_url or url)
206
+ r.update(_fetch_meta(browser)); results.append(r)
207
+ elif not results:
208
+ results.append({**self._empty_result(STATUS_FETCH_ERROR, url, browser.err or "浏览器抓取为空", {}), **_fetch_meta(browser)})
209
+ return max(results, key=_evidence)
210
+
211
+ def _follow_pages(self, first: dict[str, Any], mode: str, max_pages: int, verify_links: bool) -> dict[str, Any]:
212
+ next_url = ((first.get("list_manifest") or {}).get("pagination") or {}).get("next_page") or ""
213
+ pages = [first]; seen = {first.get("url") or ""}
214
+ while next_url and len(pages) < max(1, int(max_pages)) and next_url not in seen:
215
+ seen.add(next_url)
216
+ nxt = self._extract_one(next_url, mode)
217
+ if verify_links:
218
+ verify_click_entries(nxt, nxt.get("url") or next_url)
219
+ if not nxt.get("list_manifest"):
220
+ break
221
+ pages.append(nxt)
222
+ next_url = ((nxt.get("list_manifest") or {}).get("pagination") or {}).get("next_page") or ""
223
+ best = max(pages, key=_evidence)
224
+ combined = dict(best)
225
+ entries, seen_entries = [], set()
226
+ for p in pages:
227
+ for e in p.get("entries") or []:
228
+ u = (e.get("url") or "").strip()
229
+ if u and u not in seen_entries:
230
+ seen_entries.add(u); entries.append(e)
231
+ combined["entries"] = entries
232
+ combined["pages"] = [{"url": p.get("url"), "status": p.get("status"), "list_prob": p.get("list_prob"),
233
+ "entry_count": len(p.get("entries") or [])} for p in pages]
234
+ m = build_manifest(combined, raw=None, page_url=best.get("url") or "")
235
+ m["pages"] = combined["pages"]
236
+ m["pagination"] = ((pages[-1].get("list_manifest") or {}).get("pagination") or m.get("pagination") or {})
237
+ m["complete"] = bool((pages[-1].get("list_manifest") or {}).get("complete", False))
238
+ combined["list_manifest"] = m
239
+ return combined
240
+
241
+ def _result(
242
+ self,
243
+ analysis: dict[str, Any],
244
+ ranked: list[dict[str, Any]],
245
+ meta: dict[str, Any],
246
+ page_url: str,
247
+ ) -> dict[str, Any]:
248
+ main = self._select_container(ranked) if meta["page_status"] == STATUS_LIST else None
249
+ entries = _clean_entries((main or {}).get("entries") or (main or {}).get("samples") or [], page_url) if main else []
250
+ if meta["page_status"] == STATUS_LIST and main is None:
251
+ # A positive page with no candidate that carries entries is not a
252
+ # usable list; the page model was trained on pages, not on
253
+ # entry-level completeness. The status reflects the page, while
254
+ # the container is absent.
255
+ status = STATUS_NO_LIST
256
+ reason = "页面模型判为列表,但无可提取条目的结构容器"
257
+ elif meta["page_status"] == STATUS_LIST:
258
+ status = STATUS_LIST
259
+ reason = "页面主内容是列表;容器由候选模型 + 结构分选出"
260
+ else:
261
+ status = STATUS_NO_LIST
262
+ entries = []
263
+ reason = "页面主内容不是列表(文章/导航/页脚/筛选/空栏目等)"
264
+ out = {
265
+ "status": status,
266
+ "page_status": meta["page_status"],
267
+ "page_probs": meta["page_probs"],
268
+ "list_prob": meta["list_prob"],
269
+ "top_prob": meta["top_prob"],
270
+ "threshold": self.threshold,
271
+ "semantic": "U",
272
+ "semantic_probs": {},
273
+ "semantic_top_prob": 0.0,
274
+ "confidence": _confidence(status, float(meta["list_prob"]), float(meta["top_prob"])),
275
+ "reason": reason,
276
+ "review_cause": "",
277
+ "url": page_url,
278
+ "main": _candidate_meta(main) if main else None,
279
+ "entries": entries,
280
+ "candidates": [_candidate_meta(c) for c in ranked[:10]],
281
+ "page": _page_meta(analysis),
282
+ }
283
+ out["production"] = production_decision(out)
284
+ out["input_health"] = input_health(out)
285
+ return out
286
+
287
+ def _empty_result(self, status: str, page_url: str, reason: str, analysis: dict[str, Any]) -> dict[str, Any]:
288
+ out = {
289
+ "status": status, "page_status": STATUS_NO_LIST, "page_probs": {},
290
+ "list_prob": 0.0, "top_prob": 0.0, "threshold": self.threshold,
291
+ "semantic": "U", "semantic_probs": {}, "semantic_top_prob": 0.0,
292
+ "confidence": "none", "reason": reason, "review_cause": "",
293
+ "url": page_url, "main": None, "entries": [], "candidates": [],
294
+ "page": _page_meta(analysis),
295
+ }
296
+ out["production"] = production_decision(out)
297
+ out["input_health"] = input_health(out)
298
+ return out
299
+
300
+
301
+ def _evidence(result: dict[str, Any]) -> tuple[int, float, float]:
302
+ return (STATUS_RANK.get(str(result.get("status")), 0),
303
+ float(result.get("list_prob") or 0.0),
304
+ float((result.get("main") or {}).get("model_score") or 0.0))
305
+
306
+
307
+ def _confidence(status: str, list_prob: float, top_score: float) -> str:
308
+ if status != STATUS_LIST:
309
+ return "none"
310
+ if list_prob >= 0.85 and top_score >= 0.5:
311
+ return "high"
312
+ return "medium"
313
+
314
+
315
+ def _candidate_meta(c: dict[str, Any]) -> dict[str, Any]:
316
+ keys = (
317
+ "tag", "cls", "id", "family", "template_sig", "sig", "loose", "selector", "n",
318
+ "score", "model_score", "date_ratio", "kw_ratio", "year_ratio", "detail_ratio",
319
+ "ext_ratio", "uniq_ratio", "uniq_title_ratio", "title_len_std", "nav_ratio",
320
+ "avg_len", "bl_score", "numeric_ratio", "share", "prior", "link_density",
321
+ "text_density", "depth", "child_ratio", "is_table", "has_pagination", "pos",
322
+ "raw_rank", "link_mode", "link_status", "click_entries", "ctx_landmark",
323
+ "ctx_nav_tok", "ctx_footer_tok", "ctx_widget_tok", "dup_ratio", "section_ratio",
324
+ "near_pagi", "more_link", "img_item_ratio", "short_item_ratio", "parent_cand",
325
+ )
326
+ out = {k: c.get(k) for k in keys if k in c}
327
+ out["samples"] = c.get("samples", [])
328
+ return out
329
+
330
+
331
+ def _page_meta(analysis: dict[str, Any]) -> dict[str, Any]:
332
+ return {k: analysis.get(k) for k in PAGE_META_KEYS}
333
+
334
+
335
+ def _clean_entries(entries: list[dict[str, Any]], page_url: str) -> list[dict[str, Any]]:
336
+ out, seen = [], set()
337
+ for e in entries:
338
+ url = e.get("url") or e.get("href") or ""
339
+ title = clean_title(e.get("title") or "")
340
+ if len(title) < 2:
341
+ continue
342
+ if not url:
343
+ # A JS-only list can expose stable titles/dates with no href in
344
+ # the static DOM. Keep the row, mark the missing link; do not
345
+ # invent a URL.
346
+ if e.get("link_mode") != "text" or title in seen:
347
+ continue
348
+ seen.add(title)
349
+ out.append({
350
+ "title": title, "url": "", "date": e.get("date") or "",
351
+ "year": e.get("year") or "", "kw": bool(e.get("kw") or False),
352
+ "detail": bool(e.get("detail") or False), "external": False,
353
+ "link_mode": "text", "link_status": "no_href",
354
+ })
355
+ continue
356
+ url = canonicalize_url(page_url, url)
357
+ if not url or url in seen:
358
+ continue
359
+ seen.add(url)
360
+ out.append({
361
+ "title": title, "url": url, "date": e.get("date") or "",
362
+ "year": e.get("year") or "", "kw": bool(e.get("kw") or False),
363
+ "detail": bool(e.get("detail") or False), "external": bool(e.get("external") or False),
364
+ "link_mode": e.get("link_mode") or "", "link_status": e.get("link_status") or "",
365
+ })
366
+ return out
367
+
368
+
369
+ def _fetch_meta(f: FetchResult) -> dict[str, Any]:
370
+ return {"fetch_mode": f.mode, "http_status": f.code, "final_url": f.final_url or f.url,
371
+ "browser_error": f.err if f.mode == "browser" else ""}