Repository navigation
Expand file tree
/
Copy pathsource_discovery.py
More file actions
213 lines (194 loc) · 8.13 KB
/
Copy pathsource_discovery.py
File metadata and controls
213 lines (194 loc) · 8.13 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
"""Goal-aware source discovery helpers for generalized dataset requests."""
from __future__ import annotations
from dataclasses import dataclass
import re
from urllib.parse import quote_plus
from goal_intent import GoalDecomposition, decompose_goal
from source_adapters import adapter_urls_for_goal
from source_memory import SourceMemory
KNOWN_STALE_URL_FRAGMENTS = (
"statbunker.com",
"nanoreview.net/en/laptop-list",
)
@dataclass(frozen=True, slots=True)
class DiscoveryCandidate:
"""A source candidate enriched with family-level context."""
url: str
expected_source_type: str
family: str
rationale: str
class SourceDiscoveryEngine:
"""Generate higher-quality seed URLs and search prompts for broad goals."""
def __init__(self, source_memory: SourceMemory | None = None) -> None:
self.source_memory = source_memory or SourceMemory()
def discover(
self,
goal: str,
*,
forbidden_domains: set[str] | None = None,
limit: int = 12,
) -> list[DiscoveryCandidate]:
decomposition = decompose_goal(goal)
forbidden_domains = {domain.lower() for domain in (forbidden_domains or set()) if domain}
candidates: list[DiscoveryCandidate] = []
candidates.extend(self._memory_candidates(goal))
candidates.extend(self._adapter_candidates(goal))
candidates.extend(self._pattern_candidates(decomposition))
deduped: list[DiscoveryCandidate] = []
seen: set[str] = set()
for candidate in candidates:
normalized = candidate.url.strip()
if not normalized or normalized in seen:
continue
if any(fragment in normalized.lower() for fragment in KNOWN_STALE_URL_FRAGMENTS):
continue
if any(domain in normalized.lower() for domain in forbidden_domains):
continue
seen.add(normalized)
deduped.append(candidate)
if len(deduped) >= limit:
break
return deduped
def search_queries(self, goal: str, *, limit: int = 8) -> list[str]:
decomposition = decompose_goal(goal)
entity_phrase = decomposition.row_granularity.replace("_", " ")
target_phrase = (decomposition.target_hint or "target").replace("_", " ")
feature_phrases = [feature.replace("_", " ") for feature in decomposition.feature_hints[:2]]
domain_phrase = decomposition.domain_intent.replace("-", " ")
temporal_phrase = {
"historical": "historical",
"current": "current",
"recent": "latest",
}.get(decomposition.temporal_scope, "")
query_templates = [
f"{goal} public table",
f"{domain_phrase} {entity_phrase} {target_phrase} stats table".strip(),
f"{domain_phrase} {entity_phrase} list {temporal_phrase}".strip(),
f"{entity_phrase} {target_phrase} directory".strip(),
f"{goal} wikipedia list",
]
if feature_phrases:
query_templates.append(
f"{domain_phrase} {entity_phrase} {' '.join(feature_phrases)} dataset".strip()
)
queries: list[str] = []
for query in query_templates:
cleaned = re.sub(r"\s+", " ", query).strip()
if cleaned and cleaned not in queries:
queries.append(cleaned)
if len(queries) >= limit:
break
return queries
def _memory_candidates(self, goal: str) -> list[DiscoveryCandidate]:
return [
DiscoveryCandidate(
url=url,
expected_source_type="html_table",
family="memory",
rationale="reused_successful_source",
)
for url in self.source_memory.similar_urls(goal)
]
def _adapter_candidates(self, goal: str) -> list[DiscoveryCandidate]:
candidates: list[DiscoveryCandidate] = []
for url in adapter_urls_for_goal(goal):
source_type = "react_state" if any(token in url for token in ("nba.com/stats", "transfermarkt")) else "html_table"
candidates.append(
DiscoveryCandidate(
url=url,
expected_source_type=source_type,
family="adapter",
rationale="domain_specific_adapter",
)
)
return candidates
def _pattern_candidates(self, decomposition: GoalDecomposition) -> list[DiscoveryCandidate]:
query = quote_plus(decomposition.raw_goal)
list_query = quote_plus(f"{decomposition.raw_goal} list")
candidates = [
DiscoveryCandidate(
url=f"https://en.wikipedia.org/w/index.php?search={list_query}",
expected_source_type="html_table",
family="reference_list",
rationale="wikipedia_list_fallback",
),
DiscoveryCandidate(
url=f"https://www.wikidata.org/w/index.php?search={query}",
expected_source_type="html_table",
family="reference_list",
rationale="wikidata_entity_search",
),
]
if decomposition.domain_intent == "public-data" or decomposition.entity_intent == "state":
candidates.extend(
[
DiscoveryCandidate(
url="https://www.census.gov/data/tables/time-series/demo/popest/2020s-state-total.html",
expected_source_type="html_table",
family="official_dataset",
rationale="official_public_table",
),
DiscoveryCandidate(
url="https://www.bea.gov/data/gdp/gdp-state",
expected_source_type="html_table",
family="official_dataset",
rationale="official_public_table",
),
]
)
if decomposition.domain_intent in {"startup", "bank"} or decomposition.entity_intent == "company":
candidates.extend(
[
DiscoveryCandidate(
url="https://www.forbes.com/lists/",
expected_source_type="browser_heavy",
family="publisher_list",
rationale="publisher_rankings",
),
]
)
if decomposition.domain_intent == "nba":
candidates.extend(
[
DiscoveryCandidate(
url="https://www.basketball-reference.com/leagues/NBA_2025_per_game.html",
expected_source_type="html_table",
family="aggregator",
rationale="sports_aggregator",
),
]
)
elif decomposition.domain_intent == "ncaa-basketball":
candidates.extend(
[
DiscoveryCandidate(
url="https://www.sports-reference.com/cbb/seasons/",
expected_source_type="html_table",
family="aggregator",
rationale="sports_aggregator",
),
]
)
elif decomposition.domain_intent == "soccer":
candidates.extend(
[
DiscoveryCandidate(
url="https://www.transfermarkt.com/",
expected_source_type="browser_heavy",
family="aggregator",
rationale="sports_aggregator",
),
]
)
if decomposition.domain_intent == "laptop":
candidates.extend(
[
DiscoveryCandidate(
url="https://www.notebookcheck.net/",
expected_source_type="html_table",
family="aggregator",
rationale="hardware_rankings",
),
]
)
return candidates