Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / news / scripts / harvest_sources.py
harvest_sources.py324 lines · 13.5 KiBRaw
| 1 | #!/usr/bin/env python3 |
| 2 | """Harvest verified news sources for the built-in catalog. |
| 3 | |
| 4 | Pools (public, no login/paywall scraping): |
| 5 | --opml-dir DIR OPML files (awesome-rss-feeds layout); feed URLs direct. |
| 6 | --wikidata Wikidata newspapers/magazines/news sites with an |
| 7 | official website; the feed is discovered from the |
| 8 | homepage's <link rel=alternate> or common feed paths. |
| 9 | --candidates FILE TSV rows: feed_url<TAB>name<TAB>category<TAB>language. |
| 10 | |
| 11 | Verification (repo bar, news/AGENTS.md): feed fetches 200 and parses as |
| 12 | RSS/Atom/sitemap with >=1 article link, and one sampled article's raw HTML |
| 13 | contains a full body (paragraph text measured, tail present). Everything |
| 14 | else is rejected with a reason; nothing unverified is emitted. |
| 15 | |
| 16 | Dedupe: by normalised domain and by normalised feed URL against the |
| 17 | existing catalog (news/catalog/source_catalog.tsv) and within the run. |
| 18 | Existing catalog has exactly one feed per domain, so a new domain wins. |
| 19 | |
| 20 | Output rows use the catalog TSV field order: |
| 21 | id, name, feedUrl, kind(S/R), language, categories, badge, region |
| 22 | (badge/region stay empty: harvest cannot prove a meter badge or a local |
| 23 | circulation area beyond what the pool metadata states). |
| 24 | |
| 25 | Usage: |
| 26 | python3 news/scripts/harvest_sources.py --selftest |
| 27 | python3 news/scripts/harvest_sources.py --wikidata --opml-dir /tmp/opml \ |
| 28 | --existing news/catalog/source_catalog.tsv \ |
| 29 | --out /tmp/news-harvest/new-rows.tsv \ |
| 30 | --report /tmp/news-harvest/report.json --workers 48 |
| 31 | """ |
| 32 | import argparse, html, json, re, sys, urllib.error, urllib.parse, urllib.request |
| 33 | from concurrent.futures import ThreadPoolExecutor |
| 34 | from pathlib import Path |
| 35 | |
| 36 | UA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 news-harvest/1.0" |
| 37 | MIN_BODY_CHARS, MIN_PARAS = 800, 3 |
| 38 | FEED_PATHS = ["/news-sitemap.xml", "/sitemaps/news.xml", "/feed", "/feed/", |
| 39 | "/rss", "/rss.xml", "/atom.xml", "/feed.xml", "/index.xml"] |
| 40 | COUNTRY_LANG = {"Germany": "de", "France": "fr", "Spain": "es", "Brazil": "pt", |
| 41 | "Italy": "it", "Japan": "ja", "Netherlands": "nl", "Poland": "pl", |
| 42 | "Russia": "ru", "Ukraine": "uk", "Mexico": "es", "Indonesia": "id"} |
| 43 | |
| 44 | |
| 45 | def norm_domain(url: str) -> str: |
| 46 | host = urllib.parse.urlparse(url).netloc.lower().split("@")[-1].split(":")[0] |
| 47 | return host[4:] if host.startswith("www.") else host |
| 48 | |
| 49 | |
| 50 | def norm_feed(url: str) -> str: |
| 51 | p = urllib.parse.urlparse(url) |
| 52 | port = p.port |
| 53 | if (p.scheme.lower(), port) in {("https", 443), ("http", 80)}: |
| 54 | port = None |
| 55 | return (p.scheme.lower(), norm_domain(url), port, p.path.rstrip("/").lower(), |
| 56 | p.query) |
| 57 | |
| 58 | |
| 59 | def slugify(domain: str) -> str: |
| 60 | parts = [p for p in re.split(r"[^a-z0-9]+", domain.lower()) if p] |
| 61 | if len(parts) > 1 and parts[-1] in {"com", "org", "net", "co", "io"}: |
| 62 | parts = parts[:-1] + [parts[-1][:2]] |
| 63 | return "-".join(parts)[:48].strip("-") or "source" |
| 64 | |
| 65 | |
| 66 | def parse_feed(text: str): |
| 67 | """(kind, title, language, article_urls) or None when not a feed.""" |
| 68 | head = text[:200000] |
| 69 | if "<urlset" in head or "<sitemapindex" in head: |
| 70 | locs = re.findall(r"<loc>\s*([^<\s]+)", head) |
| 71 | articles = [u for u in locs if not u.endswith(".xml")] |
| 72 | if not articles and locs: |
| 73 | return ("S", None, None, locs[:1]) # index: child is followed by caller |
| 74 | return ("S", None, None, articles[:5]) if articles else None |
| 75 | if "<rss" in head or "<feed" in head or "<rdf" in head: |
| 76 | title = re.search(r"<channel>.*?<title>(?:<!\[CDATA\[)?(.*?)(?:\]\]>)?</title>", |
| 77 | head, re.S) |
| 78 | lang = re.search(r"<language>\s*([^<]+)", head) |
| 79 | links = re.findall(r"<link>\s*(https?://[^<\s]+)", head) |
| 80 | items = re.findall(r"<item[ >]", head) |
| 81 | entries = re.findall(r"<entry[ >]", head) |
| 82 | if "<feed" in head: # Atom: <link href="..."> |
| 83 | links = re.findall(r'<link[^>]+href="(https?://[^"]+)"', head) |
| 84 | title = re.search(r"<feed[^>]*>.*?<title>(?:<!\[CDATA\[)?(.*?)(?:\]\]>)?</title>", |
| 85 | head, re.S) |
| 86 | if not links or (not items and not entries and "<feed" not in head): |
| 87 | return None |
| 88 | t = html.unescape(title.group(1)).strip() if title else None |
| 89 | lg = lang.group(1).strip().lower() if lang else None |
| 90 | return ("R", t, lg, links[:5]) |
| 91 | return None |
| 92 | |
| 93 | |
| 94 | def article_body_ok(page: str) -> bool: |
| 95 | body = re.sub(r"(?is)<(script|style|noscript)[^>]*>.*?</\1>", " ", page) |
| 96 | paras = [html.unescape(re.sub(r"(?s)<[^>]+>", " ", p)).strip() |
| 97 | for p in re.findall(r"(?is)<p[^>]*>(.*?)</p>", body)] |
| 98 | paras = [re.sub(r"\s+", " ", p) for p in paras if len(p) >= 40] |
| 99 | return len(paras) >= MIN_PARAS and sum(len(p) for p in paras) >= MIN_BODY_CHARS \ |
| 100 | and len(paras[-1]) >= 40 |
| 101 | |
| 102 | |
| 103 | class Fetcher: |
| 104 | def __init__(self, timeout=12): |
| 105 | self.timeout = timeout |
| 106 | |
| 107 | def fetch(self, url, max_bytes=600_000): |
| 108 | req = urllib.request.Request(url, headers={"User-Agent": UA}) |
| 109 | with urllib.request.urlopen(req, timeout=self.timeout) as r: |
| 110 | if r.status != 200: |
| 111 | raise ValueError(f"http-{r.status}") |
| 112 | data = r.read(max_bytes) |
| 113 | return r.geturl(), data.decode("utf-8", "replace") |
| 114 | |
| 115 | |
| 116 | def discover_feed(fetcher, site_url): |
| 117 | """Feed URL found from a homepage, or None.""" |
| 118 | try: |
| 119 | final, page = fetcher.fetch(site_url) |
| 120 | except Exception: |
| 121 | return None |
| 122 | m = re.search(r'<link[^>]+type="application/(?:rss|atom)\+xml"[^>]+href="([^"]+)"', |
| 123 | page) or re.search( |
| 124 | r'<link[^>]+href="([^"]+)"[^>]+type="application/(?:rss|atom)\+xml"', page) |
| 125 | urls = [] |
| 126 | if m: |
| 127 | urls.append(urllib.parse.urljoin(final, html.unescape(m.group(1)))) |
| 128 | base = urllib.parse.urlparse(final) |
| 129 | root = f"{base.scheme}://{base.netloc}" |
| 130 | urls += [root + p for p in FEED_PATHS] |
| 131 | for u in urls: |
| 132 | try: |
| 133 | _, text = fetcher.fetch(u) |
| 134 | except Exception: |
| 135 | continue |
| 136 | if parse_feed(text): |
| 137 | return u |
| 138 | return None |
| 139 | |
| 140 | |
| 141 | def verify(cand, fetcher): |
| 142 | """Catalogue row dict for cand, or a rejection-reason string.""" |
| 143 | feed_url = cand["feed_url"] |
| 144 | try: |
| 145 | _, text = fetcher.fetch(feed_url) |
| 146 | except Exception as e: |
| 147 | return f"feed-fetch:{type(e).__name__}:{e}"[:120] |
| 148 | parsed = parse_feed(text) |
| 149 | if not parsed: |
| 150 | return "feed-parse" |
| 151 | kind, title, lang, articles = parsed |
| 152 | if kind == "S" and articles and articles[0].endswith(".xml"): |
| 153 | try: |
| 154 | _, child = fetcher.fetch(articles[0]) |
| 155 | except Exception as e: |
| 156 | return f"sitemap-child:{type(e).__name__}"[:120] |
| 157 | parsed = parse_feed(child) |
| 158 | if not parsed: |
| 159 | return "sitemap-child-parse" |
| 160 | kind, title, lang, articles = parsed |
| 161 | if not articles: |
| 162 | return "feed-empty" |
| 163 | body_ok = False |
| 164 | for art in articles[:3]: |
| 165 | try: |
| 166 | _, page = fetcher.fetch(art) |
| 167 | except Exception: |
| 168 | continue |
| 169 | if article_body_ok(page): |
| 170 | body_ok = True |
| 171 | break |
| 172 | if not body_ok: |
| 173 | return "article-body" |
| 174 | language = (lang or cand.get("language") or "en").split("-")[0].lower() |
| 175 | if not re.fullmatch(r"[a-z]{2,3}", language): |
| 176 | language = cand.get("language") or "en" |
| 177 | name = re.sub(r"[\t\r\n]+", " ", (title or cand.get("name") or norm_domain(feed_url))).strip() |
| 178 | return {"id": None, "name": name[:120], |
| 179 | "feedUrl": feed_url, "kind": kind, |
| 180 | "language": language, "categories": cand.get("category") or "W"} |
| 181 | |
| 182 | |
| 183 | def load_existing(path): |
| 184 | domains, feeds, ids = set(), set(), set() |
| 185 | for line in Path(path).read_text(encoding="utf-8").splitlines(): |
| 186 | if not line or line.startswith("#"): |
| 187 | continue |
| 188 | for rec in line.split(" ;; "): |
| 189 | f = rec.split("\t") |
| 190 | ids.add(f[0]); domains.add(norm_domain(f[2])); feeds.add(norm_feed(f[2])) |
| 191 | return domains, feeds, ids |
| 192 | |
| 193 | |
| 194 | def candidates_from_opml(opml_dir): |
| 195 | out = [] |
| 196 | for f in sorted(Path(opml_dir).glob("*.opml")): |
| 197 | text = f.read_text(encoding="utf-8", errors="replace") |
| 198 | country = f.stem.replace("opml-", "").replace("_", " ") |
| 199 | for name, url in re.findall(r'text="([^"]+)"[^>]*xmlUrl="([^"]+)"', text): |
| 200 | out.append({"feed_url": html.unescape(url), "name": html.unescape(name), |
| 201 | "category": "U" if country == "United States" else "W", |
| 202 | "language": COUNTRY_LANG.get(country, "en")}) |
| 203 | return out |
| 204 | |
| 205 | |
| 206 | def candidates_from_wikidata(fetcher_text): |
| 207 | q = ("SELECT ?itemLabel ?site ?countryLabel ?langCode WHERE { " |
| 208 | "?item wdt:P856 ?site. " |
| 209 | "{ ?item wdt:P31 wd:Q11032. } UNION { ?item wdt:P31 wd:Q41298. } " |
| 210 | "UNION { ?item wdt:P31 wd:Q17232649. } " |
| 211 | "OPTIONAL { ?item wdt:P17 ?country. } " |
| 212 | "OPTIONAL { ?item wdt:P407/wdt:P218 ?langCode. } " |
| 213 | "SERVICE wikibase:label { bd:serviceParam wikibase:language 'en'. } }") |
| 214 | url = ("https://query.wikidata.org/sparql?query=" + urllib.parse.quote(q) |
| 215 | + "&format=json") |
| 216 | data = json.loads(fetcher_text(url)) |
| 217 | out = [] |
| 218 | for b in data["results"]["bindings"]: |
| 219 | site = b["site"]["value"] |
| 220 | country = b.get("countryLabel", {}).get("value", "") |
| 221 | out.append({"site": site, "name": b.get("itemLabel", {}).get("value", ""), |
| 222 | "category": "U" if country == "United States" else "W", |
| 223 | "language": b.get("langCode", {}).get("value") |
| 224 | or COUNTRY_LANG.get(country, "en")}) |
| 225 | return out |
| 226 | |
| 227 | |
| 228 | def selftest(): |
| 229 | rss = ('<rss><channel><title>Fixture News</title><language>en-US</language>' |
| 230 | '<item><link>https://ex.com/a1</link></item></channel></rss>') |
| 231 | assert parse_feed(rss)[0] == "R" and parse_feed(rss)[3] == ["https://ex.com/a1"] |
| 232 | sm = ('<urlset><url><loc>https://ex.com/story</loc></url></urlset>') |
| 233 | assert parse_feed(sm)[0] == "S" |
| 234 | assert parse_feed("<html>nope</html>") is None |
| 235 | page = "".join(f"<p>{'word ' * 40}.</p>" for _ in range(5)) |
| 236 | assert article_body_ok(page) and not article_body_ok("<p>tiny</p>") |
| 237 | assert slugify("the-guardian.com") == "the-guardian-co" |
| 238 | assert norm_domain("https://www.bbc.com/x") == "bbc.com" |
| 239 | print("selftest ok") |
| 240 | |
| 241 | |
| 242 | def main(): |
| 243 | ap = argparse.ArgumentParser() |
| 244 | ap.add_argument("--selftest", action="store_true") |
| 245 | ap.add_argument("--opml-dir"); ap.add_argument("--wikidata", action="store_true") |
| 246 | ap.add_argument("--candidates"); ap.add_argument("--existing", required=False) |
| 247 | ap.add_argument("--out"); ap.add_argument("--report") |
| 248 | ap.add_argument("--workers", type=int, default=48) |
| 249 | ap.add_argument("--limit", type=int, default=0) |
| 250 | args = ap.parse_args() |
| 251 | if args.selftest: |
| 252 | return selftest() |
| 253 | fetcher = Fetcher() |
| 254 | cands = [] |
| 255 | if args.opml_dir: |
| 256 | cands += candidates_from_opml(args.opml_dir) |
| 257 | if args.wikidata: |
| 258 | cands += candidates_from_wikidata( |
| 259 | lambda u: fetcher.fetch(u, max_bytes=30_000_000)[1]) |
| 260 | if args.candidates: |
| 261 | for line in Path(args.candidates).read_text(encoding="utf-8").splitlines(): |
| 262 | f = line.split("\t") |
| 263 | if len(f) >= 1 and f[0].startswith("http"): |
| 264 | cands.append({"feed_url": f[0], "name": f[1] if len(f) > 1 else "", |
| 265 | "category": f[2] if len(f) > 2 else "W", |
| 266 | "language": f[3] if len(f) > 3 else "en"}) |
| 267 | domains, feeds, ids = load_existing(args.existing) |
| 268 | seen_domains, seen_feeds = set(domains), set(feeds) |
| 269 | todo, rejected = [], {} |
| 270 | for c in cands: |
| 271 | site = c.get("site") or c["feed_url"] |
| 272 | d = norm_domain(site) |
| 273 | if d in seen_domains: |
| 274 | rejected["duplicate-existing-domain"] = rejected.get("duplicate-existing-domain", 0) + 1 |
| 275 | continue |
| 276 | seen_domains.add(d) |
| 277 | if "feed_url" in c and norm_feed(c["feed_url"]) in seen_feeds: |
| 278 | rejected["duplicate-feed"] = rejected.get("duplicate-feed", 0) + 1 |
| 279 | continue |
| 280 | if "feed_url" in c: |
| 281 | seen_feeds.add(norm_feed(c["feed_url"])) |
| 282 | todo.append(c) |
| 283 | if args.limit: |
| 284 | todo = todo[: args.limit] |
| 285 | print(f"candidates={len(cands)} todo={len(todo)} pre-rejected={sum(rejected.values())}", |
| 286 | flush=True) |
| 287 | |
| 288 | def work(c): |
| 289 | cc = dict(c) |
| 290 | if "feed_url" not in cc: |
| 291 | found = discover_feed(fetcher, cc["site"]) |
| 292 | if not found: |
| 293 | return ("discover-none", c) |
| 294 | cc["feed_url"] = found |
| 295 | r = verify(cc, fetcher) |
| 296 | return (r, cc) if isinstance(r, dict) else (r.split(":")[0], cc) |
| 297 | |
| 298 | rows = [] |
| 299 | with ThreadPoolExecutor(max_workers=args.workers) as ex: |
| 300 | for i, (res, c) in enumerate(ex.map(work, todo)): |
| 301 | if isinstance(res, dict): |
| 302 | base = slugify(norm_domain(res["feedUrl"])) |
| 303 | sid, n = base, 2 |
| 304 | while sid in ids: |
| 305 | sid = f"{base}-{n}"; n += 1 |
| 306 | ids.add(sid); res["id"] = sid; rows.append(res) |
| 307 | else: |
| 308 | rejected[res] = rejected.get(res, 0) + 1 |
| 309 | if (i + 1) % 500 == 0: |
| 310 | print(f"{i + 1}/{len(todo)} verified={len(rows)}", flush=True) |
| 311 | if args.out: |
| 312 | with open(args.out, "w", encoding="utf-8") as fh: |
| 313 | for r in rows: |
| 314 | fh.write("\t".join([r["id"], r["name"], r["feedUrl"], r["kind"], |
| 315 | r["language"], r["categories"], "", ""]) + "\n") |
| 316 | report = {"candidates": len(cands), "todo": len(todo), "verified": len(rows), |
| 317 | "rejected": rejected} |
| 318 | if args.report: |
| 319 | Path(args.report).write_text(json.dumps(report, indent=1), encoding="utf-8") |
| 320 | print(json.dumps(report, indent=1)) |
| 321 | |
| 322 | |
| 323 | if __name__ == "__main__": |
| 324 | main() |