-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1189 lines (958 loc) · 39.6 KB
/
server.py
File metadata and controls
1189 lines (958 loc) · 39.6 KB
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import json
import re
import sys
import urllib.parse
from pathlib import Path
from bs4 import BeautifulSoup, Tag
from cloakbrowser import launch_async
from markdownify import markdownify as md
from mcp.server.fastmcp import FastMCP
from playwright.async_api import TimeoutError as PlaywrightTimeoutError
mcp = FastMCP("searchfetch")
# ---------------------------------------------------------------------------
# Browser Manager — single shared browser instance, stealth by default
# ---------------------------------------------------------------------------
class BrowserManager:
def __init__(self):
self.browser = None
self._lock = asyncio.Lock()
async def get_browser(self):
async with self._lock:
if self.browser and self.browser.is_connected:
return self.browser
self.browser = await launch_async(
headless=True,
humanize=True,
args=[
"--disable-blink-features=AutomationControlled",
"--no-sandbox",
"--disable-dev-shm-usage",
],
)
return self.browser
async def close(self):
if self.browser:
await self.browser.close()
self.browser = None
browser_manager = BrowserManager()
# ---------------------------------------------------------------------------
# Utility helpers
# ---------------------------------------------------------------------------
def _get_string_attr(tag: Tag, attr: str) -> str:
val = tag.get(attr)
if isinstance(val, list):
return str(val[0]) if val else ""
return str(val or "")
def _select_first(parent, selector_string: str):
"""Try comma-separated selectors in order; return list of matches from the
first selector that produces results. Searches descendants first, then
walks up the ancestor chain (up to 4 levels) searching each ancestor's
subtree — this allows child selectors to find elements that are siblings
of the parent (e.g. a snippet <div> next to an <h3> result heading).
If *selector_string* is empty or blank, return *[parent]* (the "current
element" semantic). An empty selector *within* a comma list
(e.g. ``"a, "``) also means "current parent" and short-circuits to
*[parent]*."""
if not selector_string or not selector_string.strip():
return [parent]
# Split on top-level commas — soupsieve selectors don't nest commas.
selectors = [s.strip() for s in selector_string.split(",")]
for sel in selectors:
if not sel:
# Empty selector inside comma list → "current parent element"
return [parent]
try:
# 1. Descendants
results = parent.select(sel)
if results:
return results
except Exception:
pass
# 2. Ancestor subtrees (walk up 4 levels; siblings are in parent's
# subtree at level 1)
ancestor = getattr(parent, "parent", None)
for _level in range(4):
if ancestor is None or not hasattr(ancestor, "select"):
break
try:
results = ancestor.select(sel)
if results:
return results
except Exception:
pass
ancestor = getattr(ancestor, "parent", None)
return []
def _select_one_first(parent, selector_string: str):
results = _select_first(parent, selector_string)
return results[0] if results else None
# ---------------------------------------------------------------------------
# Transforms (post-extraction)
# ---------------------------------------------------------------------------
TRANSFORMS = {}
def _tf_strip(value, _origin):
return value.strip() if isinstance(value, str) else value
TRANSFORMS["strip"] = _tf_strip
def _tf_decode_google_url(value, _origin):
"""If value starts with /url?q=, strip prefix and URL-decode."""
if isinstance(value, str) and value.startswith("/url?q="):
try:
raw = value.split("/url?q=")[1].split("&")[0]
return urllib.parse.unquote(raw)
except Exception:
return value
return value
TRANSFORMS["decode_google_url"] = _tf_decode_google_url
def _tf_decode_ddg_url(value, _origin):
"""If value contains /l/?uddg=, extract and URL-decode the uddg parameter."""
if isinstance(value, str) and "/l/?uddg=" in value:
try:
params = dict(
urllib.parse.parse_qsl(urllib.parse.urlsplit(value).query)
)
return urllib.parse.unquote(str(params.get("uddg", value)))
except Exception:
return value
return value
TRANSFORMS["decode_ddg_url"] = _tf_decode_ddg_url
def _tf_json_parse(value, _origin):
"""Parse the extracted text as JSON and pretty-print."""
if isinstance(value, str):
try:
parsed = json.loads(value)
return json.dumps(parsed, indent=2, ensure_ascii=False)
except (json.JSONDecodeError, TypeError):
return value
return value
TRANSFORMS["json_parse"] = _tf_json_parse
def _tf_resolve_href(value, origin):
"""If href is relative (starts with /), prepend page origin."""
if isinstance(value, str) and value.startswith("/") and not value.startswith("//"):
return origin + value
return value
TRANSFORMS["resolve_href"] = _tf_resolve_href
def apply_transform(value, transform, origin=""):
"""Apply a single transform name or chain (list) to *value*."""
if transform is None:
return value
if isinstance(transform, str):
chain = [transform]
else:
chain = transform
for name in chain:
fn = TRANSFORMS.get(name)
if fn:
value = fn(value, origin)
return value
# ---------------------------------------------------------------------------
# Built-in templates (loaded from templates/*.json at startup)
# ---------------------------------------------------------------------------
def _load_builtin_templates():
"""Load built-in template JSON files from disk.
Searches (in order):
1. templates/ adjacent to server.py (development / editable install)
2. templates/ in current working directory (uv run, npm run)
3. templates/ under sys.prefix (data_files wheel install)
Returns a dict of template name -> template data, preserving insertion
order sorted by the "order" field in each template.
"""
search_paths = [
Path(__file__).resolve().parent / "templates",
Path.cwd() / "templates",
Path(sys.prefix) / "templates",
]
templates_dir = None
for sp in search_paths:
if sp.is_dir():
templates_dir = sp
break
if templates_dir is None:
searched = "', '".join(str(p) for p in search_paths[:2])
raise FileNotFoundError(
f"Templates directory not found. Searched: '{searched}'"
)
json_files = sorted(templates_dir.glob("*.json"))
if not json_files:
raise FileNotFoundError(
f"No template JSON files (*.json) found in '{templates_dir}'"
)
raw_templates = []
for filepath in json_files:
try:
data = json.loads(filepath.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise ValueError(
f"Invalid JSON in template file '{filepath}': {exc}"
) from exc
name = data.get("name")
if not name or not isinstance(name, str):
raise ValueError(
f"Template file '{filepath}' is missing a valid 'name' field"
)
raw_templates.append(data)
# Sort by "order" field for deterministic URL-pattern matching
raw_templates.sort(key=lambda t: t.get("order", 999))
# Build ordered dict for O(1) lookup
templates = {}
for t in raw_templates:
templates[t["name"]] = t
return templates
BUILTIN_TEMPLATES = _load_builtin_templates()
# ---------------------------------------------------------------------------
# Template resolution helpers
# ---------------------------------------------------------------------------
def resolve_search_template(engine: str):
"""Map engine name to template name. Also handles inline JSON and custom names."""
if engine == "duckduckgo":
return "duckduckgo-search"
if engine == "google":
return "google-search"
if engine.startswith("{"):
return engine # inline JSON — caller parses it
return engine # custom name
def map_search_params(
query: str, engine: str, region: str | None, safe_search: bool | None
):
"""Map universal websearch params to engine-specific url_params dict."""
params = {"query": query}
if engine == "duckduckgo":
if region is not None:
params["kl"] = region
if safe_search is True:
params["kp"] = "1"
elif safe_search is False:
params["kp"] = "-2"
elif engine == "google":
if region is not None:
parts = region.split("-", 1) if "-" in region else [region, region]
params["hl"] = parts[0]
if len(parts) >= 2:
params["gl"] = parts[1]
else:
params["gl"] = parts[0]
if safe_search is True:
params["safe"] = "active"
return params
def resolve_url_template(template: dict, provided_params: dict) -> str:
"""Fill url_template placeholders using provided_params + url_params defaults.
Returns the resolved URL string or raises ValueError for missing required params.
"""
url_template = template.get("url_template")
if not url_template:
raise ValueError(
f"Template '{template.get('name', 'unknown')}' has no url_template."
)
url_params = template.get("url_params", {})
resolved = url_template
# Find all {placeholder} tokens
placeholders = re.findall(r"\{(\w+)\}", url_template)
for key in placeholders:
param_def = url_params.get(key, {})
value = None
if key in provided_params and provided_params[key] is not None:
value = str(provided_params[key])
elif "default" in param_def:
value = str(param_def["default"])
elif param_def.get("required", False):
raise ValueError(
f"Required URL parameter '{key}' is missing for template "
f"'{template.get('name', 'unknown')}'."
)
else:
continue
if param_def.get("encode") == "url":
value = urllib.parse.quote_plus(value, safe="")
resolved = resolved.replace(f"{{{key}}}", str(value))
return resolved
def resolve_page_template(url: str, template_arg: str):
"""Resolve the template for a webfetch request.
Returns (template_dict | None, template_name: str).
"""
# 1. Inline JSON?
if template_arg.startswith("{"):
try:
tmpl = json.loads(template_arg)
return tmpl, tmpl.get("name", "custom")
except json.JSONDecodeError as exc:
raise ValueError(f"Invalid inline JSON template: {exc}") from exc
# 2. Named built-in?
if template_arg in BUILTIN_TEMPLATES:
return BUILTIN_TEMPLATES[template_arg], template_arg
# 3. "auto" — match by URL pattern
if template_arg == "auto":
for name, tmpl in BUILTIN_TEMPLATES.items():
for pat in tmpl.get("url_patterns", []):
try:
if re.search(pat, url):
return tmpl, name
except re.error:
continue
return None, "auto (fallback)"
# Named template not found
available = sorted(BUILTIN_TEMPLATES.keys())
raise ValueError(
f"Unknown template '{template_arg}'. Available: {', '.join(available)}"
)
# ---------------------------------------------------------------------------
# Source markdown detection (fetch raw .md source instead of HTML)
# ---------------------------------------------------------------------------
def _is_markdown_content(text: str) -> bool:
if not text:
return False
html_tags = len(re.findall(r"<\w+[^>]*>", text))
if html_tags > 3:
return False
patterns = [
r"^#{1,6}\s+\S",
r"\[.+?\]\(.+?\)",
r"```\w*\n",
r"^\s*[-*+]\s+\S",
r"\*\*[^*]+\*\*",
r"^>\s+\S",
]
for pat in patterns:
if re.search(pat, text, re.MULTILINE):
return True
return False
def _strip_source_markdown(content: str) -> str:
content = re.sub(r"^@twoslash-cache:.*$", "", content, flags=re.MULTILINE)
content = re.sub(r"\n{3,}", "\n\n", content)
return content.strip()
def _resolve_source_url(source_template: str, url: str) -> str:
if source_template == "{url}.md":
return f"{url.rstrip('/')}.md"
return source_template.replace("{url}", url)
async def _fetch_source_markdown(
source_url: str, template: dict | None, block_media: bool
):
"""Try fetching a page as raw markdown source text.
Returns the stripped text if it looks like markdown, None otherwise.
"""
browser = await browser_manager.get_browser()
context, page = await _new_fetch_page(browser, template, block_media)
try:
try:
response = await page.goto(
source_url, wait_until="domcontentloaded", timeout=10000
)
except Exception:
return None
http_status = response.status if response else None
if http_status and http_status >= 400:
return None
try:
text = await page.evaluate(
"() => document.body?.innerText || document.body?.textContent || ''"
)
except Exception:
text = await page.content()
if not text or not isinstance(text, str):
return None
text = _strip_source_markdown(text.strip())
if _is_markdown_content(text):
return text
return None
except Exception:
return None
finally:
await context.close()
# ---------------------------------------------------------------------------
# Access-failure detection
# ---------------------------------------------------------------------------
ACCESS_DENIED_TITLE_PATTERNS = [
r"\b(?:captcha|robot|verify|access\s*denied|blocked|forbidden|not\s+available)\b",
r"\b(?:unusual\s+traffic|are\s+you\s+a\s+human)\b",
r"\b(?:429|403|401)\b",
]
ACCESS_DENIED_BODY_TRIGGERS = [
"captcha",
"verify you are human",
"are you a robot",
"unusual traffic",
"access denied",
"sorry, you have been blocked",
"to continue, please type the characters",
]
_ACCESS_DENIED_RE = re.compile(
"|".join(ACCESS_DENIED_TITLE_PATTERNS), re.IGNORECASE
)
def _detect_access_failure(http_status: int | None, soup: BeautifulSoup) -> bool:
"""Conservative check: does the page look like an access-denial / CAPTCHA?"""
if http_status is not None and http_status in (401, 403, 429):
return True
title_tag = soup.find("title")
title_text = title_tag.get_text(strip=True) if title_tag else ""
if title_text and _ACCESS_DENIED_RE.search(title_text):
return True
body = soup.find("body")
if body:
body_text = body.get_text(" ", strip=True)
if len(body_text) < 800:
lowered = body_text.lower()
if any(trigger in lowered for trigger in ACCESS_DENIED_BODY_TRIGGERS):
return True
return False
# ---------------------------------------------------------------------------
# Fetch engine — stealth browser with cookie injection & resource blocking
# ---------------------------------------------------------------------------
FETCH_MAX_ATTEMPTS = 2
HTTP_429_RETRY_DELAY_SECONDS = 2.0
class HttpStatusError(RuntimeError):
def __init__(self, status: int, url: str, retry_after: float | None = None):
super().__init__(f"Access denied: HTTP {status} when fetching {url}")
self.status = status
self.retry_after = retry_after
def _parse_retry_after(value: str | None) -> float:
if not value:
return HTTP_429_RETRY_DELAY_SECONDS
try:
seconds = float(value)
if seconds >= 0:
return min(seconds, 30.0)
except ValueError:
pass
return HTTP_429_RETRY_DELAY_SECONDS
async def _new_fetch_page(browser, template: dict | None, block_media: bool):
context = await browser.new_context()
if template:
for c in template.get("cookies", []):
await context.add_cookies([c])
page = await context.new_page()
if block_media:
if template:
block_types = set(template.get("block_resources", ["image", "media", "font"]))
else:
block_types = {"image", "media", "font"}
async def route_handler(route):
if route.request.resource_type in block_types:
await route.abort()
else:
await route.continue_()
await page.route("**/*", route_handler)
return context, page
async def fetch_html(
url: str, template: dict | None, block_media: bool, retry: bool = True
):
"""Fetch page HTML through cloakbrowser.
Args:
url: Target URL.
template: Optional template dict (for cookies, block_resources).
block_media: Whether to block media; if True, blocks template.block_resources
(or default ["image","media","font"] when no template).
retry: If True, retry once on network errors.
"""
browser = await browser_manager.get_browser()
context, page = await _new_fetch_page(browser, template, block_media)
last_exc = None
attempts = FETCH_MAX_ATTEMPTS if retry else 1
for attempt in range(attempts):
try:
try:
response = await page.goto(
url, wait_until="networkidle", timeout=15000
)
except PlaywrightTimeoutError:
response = None # partial render is OK
http_status = response.status if response else None
if http_status in (401, 403):
raise HttpStatusError(http_status, url)
if http_status == 429:
retry_after = _parse_retry_after(response.headers.get("retry-after"))
raise HttpStatusError(http_status, url, retry_after)
content = await page.content()
soup = BeautifulSoup(content, "html.parser")
if _detect_access_failure(http_status, soup):
raise RuntimeError(
f"Access to {url} was denied (HTTP {http_status or 'N/A'}). "
"The site may require authentication, has blocked this request, "
"or presented a CAPTCHA."
)
await context.close()
return content
except HttpStatusError as exc:
last_exc = exc
if attempt < attempts - 1 and exc.status == 429:
await context.close()
await asyncio.sleep(exc.retry_after or HTTP_429_RETRY_DELAY_SECONDS)
context, page = await _new_fetch_page(browser, template, block_media)
continue
await context.close()
raise
except (RuntimeError, ValueError):
await context.close()
raise
except Exception as exc:
last_exc = exc
# Retry only on network-level errors (parity with index.js:
# retry on net::, ERR_, Navigation failed)
exc_msg = str(exc).lower()
is_network = (
"net::" in exc_msg
or "err_" in exc_msg
or "timeout" in exc_msg
or "connection" in exc_msg
or "econnrefused" in exc_msg
or "econnreset" in exc_msg
or "enotfound" in exc_msg
or "navigation" in exc_msg
)
if attempt < attempts - 1 and is_network:
await asyncio.sleep(0.5)
# Need fresh page/context for retry
await context.close()
context, page = await _new_fetch_page(browser, template, block_media)
continue
await context.close()
raise RuntimeError(f"Failed to fetch {url} after retry: {last_exc}") from exc
# Should not reach here, but guard anyway
await context.close()
raise RuntimeError(f"Failed to fetch {url} after retry: {last_exc}")
# ---------------------------------------------------------------------------
# Extraction engine
# ---------------------------------------------------------------------------
def _extract_element(element: Tag, section: dict, origin: str):
"""Extract content from a single element according to section format/attribute."""
fmt = section.get("format", "text")
attr_name = section.get("attribute")
if fmt == "attribute":
value = _get_string_attr(element, attr_name or "href")
elif fmt == "html":
value = str(element)
elif fmt == "markdown":
raw = element.decode_contents()
value = md(raw, heading_style="ATX")
value = re.sub(r"\n{3,}", "\n\n", value).strip()
else: # "text" (default)
value = element.get_text(" ", strip=True)
transform = section.get("transform")
if transform:
value = apply_transform(value, transform, origin)
return value
def extract_section(parent, section: dict, origin: str = ""):
"""Extract one section from *parent* (soup or Tag element).
Returns a dict describing the extracted content:
{"name": …, "type": "value"|"multiple"|"children"|"search_results", …}
"""
name = section["name"]
selector = section.get("selector", "")
is_multiple = section.get("multiple", False)
max_items = section.get("max_items")
children_defs = section.get("children", [])
required = section.get("required", False)
if children_defs:
# ----- Children mode: parent is just a scoping container -----
if is_multiple:
# Multiple parents, each with children → "search_results" type
parent_matches = _select_first(parent, selector)
if not parent_matches:
if required:
raise ValueError(f"Required section '{name}' not found on page.")
return {"name": name, "type": "search_results", "items": []}
if max_items is not None:
parent_matches = parent_matches[:max_items]
items = []
for p_el in parent_matches:
if not isinstance(p_el, Tag):
continue
item = {}
for child_def in children_defs:
child_name = child_def["name"]
child_selector = child_def.get("selector", "")
child_req = child_def.get("required", False)
child_el = _select_one_first(p_el, child_selector)
if child_el and isinstance(child_el, Tag):
item[child_name] = _extract_element(
child_el, child_def, origin
)
elif child_req:
raise ValueError(
f"Required child section '{child_name}' not found "
f"inside '{name}'."
)
else:
item[child_name] = ""
items.append(item)
return {"name": name, "type": "search_results", "items": items}
else:
# Single parent with children
parent_el = _select_one_first(parent, selector)
if not parent_el:
if required:
raise ValueError(f"Required section '{name}' not found on page.")
return {"name": name, "type": "children", "children": []}
child_results = []
for child_def in children_defs:
child_name = child_def["name"]
child_selector = child_def.get("selector", "")
child_req = child_def.get("required", False)
child_el = _select_one_first(parent_el, child_selector)
if child_el and isinstance(child_el, Tag):
child_results.append(
{
"name": child_name,
"type": "value",
"value": _extract_element(child_el, child_def, origin),
}
)
elif child_req:
raise ValueError(
f"Required child section '{child_name}' not found "
f"inside '{name}'."
)
else:
child_results.append(
{"name": child_name, "type": "value", "value": ""}
)
return {"name": name, "type": "children", "children": child_results}
else:
# ----- Simple mode (no children) -----
if is_multiple:
matches = _select_first(parent, selector)
if not matches:
if required:
raise ValueError(f"Required section '{name}' not found on page.")
return {"name": name, "type": "multiple", "items": []}
if max_items is not None:
matches = matches[:max_items]
values = []
for el in matches:
if isinstance(el, Tag):
values.append(_extract_element(el, section, origin))
elif isinstance(el, str):
values.append(str(el))
return {"name": name, "type": "multiple", "items": values}
else:
el = _select_one_first(parent, selector)
if not el:
if required:
raise ValueError(f"Required section '{name}' not found on page.")
return {"name": name, "type": "value", "value": ""}
if not isinstance(el, Tag):
return {"name": name, "type": "value", "value": str(el)}
return {
"name": name,
"type": "value",
"value": _extract_element(el, section, origin),
}
def extract_template(
soup: BeautifulSoup,
template: dict,
origin: str = "",
max_results_override: int | None = None,
):
"""Run the full extraction pipeline against *soup* using *template*.
Returns list of section result dicts.
"""
# 1. Global cleanup — remove elements listed in template.remove
# Use spec default when template doesn't specify its own remove list.
remove_selectors = template.get("remove", None)
if remove_selectors is None:
remove_selectors = _SPEC_DEFAULT_REMOVE
for sel in remove_selectors:
try:
for tag in soup.select(sel):
if hasattr(tag, "decompose"):
tag.decompose()
except Exception:
pass
# Strip style attributes and data:image src (parity with index.js applyRemove)
for tag in soup.select("[style]"):
if isinstance(tag, Tag):
tag.attrs.pop("style", None)
for tag in soup.find_all(True):
if isinstance(tag, Tag):
src = _get_string_attr(tag, "src")
if src.startswith("data:image"):
tag.attrs.pop("src", None)
sections_data = []
max_items_applied = False
for section in template.get("sections", []):
# max_results override: first section with multiple + children
if (
max_results_override is not None
and not max_items_applied
and section.get("multiple")
and section.get("children")
):
section = dict(section)
section["max_items"] = max_results_override
max_items_applied = True
result = extract_section(soup, section, origin)
sections_data.append(result)
return sections_data
# ---------------------------------------------------------------------------
# Composition (output formatting)
# ---------------------------------------------------------------------------
def _format_children_section(section_data: dict) -> str:
"""Format a single-parent + children section.
Each child is emitted as its own ``## ChildName`` section (parity with
index.js composeSections "children" branch). The parent section name is
not used as a heading — it only scopes extraction.
Special case: if children contain 'Author' + 'Comment' (or 'Body'),
use the threaded comment format.
"""
children = section_data.get("children", [])
name = section_data["name"]
child_names = {c["name"].lower() for c in children}
is_threaded = "author" in child_names and (
"comment" in child_names or "body" in child_names
)
if is_threaded:
# Threaded comment format: ## Comments / **author:** / body / ---
lines = [f"## {name}", ""]
for child in children:
cname = child["name"]
cval = child.get("value", "").strip()
if cname.lower() == "author":
if cval:
lines.append(f"**{cval}:**")
elif cname.lower() in ("comment", "body"):
if cval:
lines.append("")
lines.append(cval)
lines.append("")
lines.append("---")
lines.append("")
# Remove trailing --- separator
while lines and lines[-1] in ("---", ""):
lines.pop()
return "\n".join(lines).rstrip() if len(lines) > 2 else ""
# Standard children: each child is its own ## ChildName section
parts = []
for child in children:
cname = child["name"]
cval = child.get("value", "").strip()
if cval:
parts.append(f"## {cname}\n\n{cval}")
return "\n\n---\n\n".join(parts) if parts else ""
def compose_sections(sections_data: list[dict], _template_name: str = "") -> str:
"""Compose extracted sections into a Markdown string (for webfetch)."""
parts = []
for sec in sections_data:
sec_type = sec.get("type")
name = sec.get("name", "")
if sec_type == "value":
val = sec.get("value", "").strip()
if val:
parts.append(f"## {name}\n\n{val}")
elif sec_type == "multiple":
items = sec.get("items", [])
if items:
lines = [f"## {name}", ""]
for item in items:
lines.append(str(item).strip())
parts.append("\n".join(lines))
elif sec_type == "children":
child_str = _format_children_section(sec)
if child_str:
parts.append(child_str)
elif sec_type == "search_results":
items = sec.get("items", [])
if not items:
continue
lines = [f"## {name}", ""]
for i, item in enumerate(items, start=1):
title = str(item.get("Title", "")).strip()
url = str(item.get("URL", "")).strip()
snippet = str(item.get("Snippet", "")).strip()
lines.append(f"[{i}] {title}")
if url:
lines.append(f" URL: {url}")
if snippet:
lines.append(f" Snippet: {snippet}")
parts.append("\n".join(lines))
if not parts:
return "(No content extracted from this page.)"
return "\n\n---\n\n".join(parts)
def compose_search_results(
sections_data: list[dict], _template_name: str = ""
) -> str:
"""Compose extracted sections into the websearch numbered-output format.
Filters non-http URLs and Google internal links (parity with index.js)."""
for sec in sections_data:
if sec.get("type") == "search_results":
items = sec.get("items", [])
if not items:
return "## Results\n\nNo results found."
section_name = sec.get("name", "Results")
lines = [f"## {section_name}", ""]
for i, item in enumerate(items, start=1):
title = str(item.get("Title", "")).strip()
url = str(item.get("URL", "")).strip()
snippet = str(item.get("Snippet", "")).strip()
# Filter out non-http URLs and Google internal links
clean_url = url
if clean_url and not clean_url.startswith("http"):
clean_url = ""
if clean_url and (
"google.com/search" in clean_url
or "support.google.com" in clean_url
):
clean_url = ""
if not title:
continue
lines.append(f"[{i}] {title}")
if clean_url:
lines.append(f" URL: {clean_url}")
if snippet:
lines.append(f" Snippet: {snippet}")
if len(lines) <= 2: # only header, no items
return "## Results\n\nNo results found."
return "\n".join(lines)
# Fall back to section-based output when no search_results section exists
# (parity with index.js: composeSearchResults falls back to composeSections)
return compose_sections(sections_data, _template_name)
# ---------------------------------------------------------------------------
# Generic fallback (webfetch when no template matches)