#!/usr/bin/env python3 """Harvest verified news sources for the built-in catalog. Pools (public, no login/paywall scraping): --opml-dir DIR OPML files (awesome-rss-feeds layout); feed URLs direct. --wikidata Wikidata newspapers/magazines/news sites with an official website; the feed is discovered from the homepage's or common feed paths. --candidates FILE TSV rows: feed_urlnamecategorylanguage. Verification (repo bar, news/AGENTS.md): feed fetches 200 and parses as RSS/Atom/sitemap with >=1 article link, and one sampled article's raw HTML contains a full body (paragraph text measured, tail present). Everything else is rejected with a reason; nothing unverified is emitted. Dedupe: by normalised domain and by normalised feed URL against the existing catalog (news/catalog/source_catalog.tsv) and within the run. Existing catalog has exactly one feed per domain, so a new domain wins. Output rows use the catalog TSV field order: id, name, feedUrl, kind(S/R), language, categories, badge, region (badge/region stay empty: harvest cannot prove a meter badge or a local circulation area beyond what the pool metadata states). Usage: python3 news/scripts/harvest_sources.py --selftest python3 news/scripts/harvest_sources.py --wikidata --opml-dir /tmp/opml \ --existing news/catalog/source_catalog.tsv \ --out /tmp/news-harvest/new-rows.tsv \ --report /tmp/news-harvest/report.json --workers 48 """ import argparse, html, json, re, sys, urllib.error, urllib.parse, urllib.request from concurrent.futures import ThreadPoolExecutor from pathlib import Path UA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 news-harvest/1.0" MIN_BODY_CHARS, MIN_PARAS = 800, 3 FEED_PATHS = ["/news-sitemap.xml", "/sitemaps/news.xml", "/feed", "/feed/", "/rss", "/rss.xml", "/atom.xml", "/feed.xml", "/index.xml"] COUNTRY_LANG = {"Germany": "de", "France": "fr", "Spain": "es", "Brazil": "pt", "Italy": "it", "Japan": "ja", "Netherlands": "nl", "Poland": "pl", "Russia": "ru", "Ukraine": "uk", "Mexico": "es", "Indonesia": "id"} def norm_domain(url: str) -> str: host = urllib.parse.urlparse(url).netloc.lower().split("@")[-1].split(":")[0] return host[4:] if host.startswith("www.") else host def norm_feed(url: str) -> str: p = urllib.parse.urlparse(url) port = p.port if (p.scheme.lower(), port) in {("https", 443), ("http", 80)}: port = None return (p.scheme.lower(), norm_domain(url), port, p.path.rstrip("/").lower(), p.query) def slugify(domain: str) -> str: parts = [p for p in re.split(r"[^a-z0-9]+", domain.lower()) if p] if len(parts) > 1 and parts[-1] in {"com", "org", "net", "co", "io"}: parts = parts[:-1] + [parts[-1][:2]] return "-".join(parts)[:48].strip("-") or "source" def parse_feed(text: str): """(kind, title, language, article_urls) or None when not a feed.""" head = text[:200000] if "\s*([^<\s]+)", head) articles = [u for u in locs if not u.endswith(".xml")] if not articles and locs: return ("S", None, None, locs[:1]) # index: child is followed by caller return ("S", None, None, articles[:5]) if articles else None if ".*?(?:<!\[CDATA\[)?(.*?)(?:\]\]>)?", head, re.S) lang = re.search(r"\s*([^<]+)", head) links = re.findall(r"\s*(https?://[^<\s]+)", head) items = re.findall(r"]", head) entries = re.findall(r"]", head) if " links = re.findall(r']+href="(https?://[^"]+)"', head) title = re.search(r"]*>.*?(?:<!\[CDATA\[)?(.*?)(?:\]\]>)?", head, re.S) if not links or (not items and not entries and " bool: body = re.sub(r"(?is)<(script|style|noscript)[^>]*>.*?", " ", page) paras = [html.unescape(re.sub(r"(?s)<[^>]+>", " ", p)).strip() for p in re.findall(r"(?is)]*>(.*?)

", body)] paras = [re.sub(r"\s+", " ", p) for p in paras if len(p) >= 40] return len(paras) >= MIN_PARAS and sum(len(p) for p in paras) >= MIN_BODY_CHARS \ and len(paras[-1]) >= 40 class Fetcher: def __init__(self, timeout=12): self.timeout = timeout def fetch(self, url, max_bytes=600_000): req = urllib.request.Request(url, headers={"User-Agent": UA}) with urllib.request.urlopen(req, timeout=self.timeout) as r: if r.status != 200: raise ValueError(f"http-{r.status}") data = r.read(max_bytes) return r.geturl(), data.decode("utf-8", "replace") def discover_feed(fetcher, site_url): """Feed URL found from a homepage, or None.""" try: final, page = fetcher.fetch(site_url) except Exception: return None m = re.search(r']+type="application/(?:rss|atom)\+xml"[^>]+href="([^"]+)"', page) or re.search( r']+href="([^"]+)"[^>]+type="application/(?:rss|atom)\+xml"', page) urls = [] if m: urls.append(urllib.parse.urljoin(final, html.unescape(m.group(1)))) base = urllib.parse.urlparse(final) root = f"{base.scheme}://{base.netloc}" urls += [root + p for p in FEED_PATHS] for u in urls: try: _, text = fetcher.fetch(u) except Exception: continue if parse_feed(text): return u return None def verify(cand, fetcher): """Catalogue row dict for cand, or a rejection-reason string.""" feed_url = cand["feed_url"] try: _, text = fetcher.fetch(feed_url) except Exception as e: return f"feed-fetch:{type(e).__name__}:{e}"[:120] parsed = parse_feed(text) if not parsed: return "feed-parse" kind, title, lang, articles = parsed if kind == "S" and articles and articles[0].endswith(".xml"): try: _, child = fetcher.fetch(articles[0]) except Exception as e: return f"sitemap-child:{type(e).__name__}"[:120] parsed = parse_feed(child) if not parsed: return "sitemap-child-parse" kind, title, lang, articles = parsed if not articles: return "feed-empty" body_ok = False for art in articles[:3]: try: _, page = fetcher.fetch(art) except Exception: continue if article_body_ok(page): body_ok = True break if not body_ok: return "article-body" language = (lang or cand.get("language") or "en").split("-")[0].lower() if not re.fullmatch(r"[a-z]{2,3}", language): language = cand.get("language") or "en" name = re.sub(r"[\t\r\n]+", " ", (title or cand.get("name") or norm_domain(feed_url))).strip() return {"id": None, "name": name[:120], "feedUrl": feed_url, "kind": kind, "language": language, "categories": cand.get("category") or "W"} def load_existing(path): domains, feeds, ids = set(), set(), set() for line in Path(path).read_text(encoding="utf-8").splitlines(): if not line or line.startswith("#"): continue for rec in line.split(" ;; "): f = rec.split("\t") ids.add(f[0]); domains.add(norm_domain(f[2])); feeds.add(norm_feed(f[2])) return domains, feeds, ids def candidates_from_opml(opml_dir): out = [] for f in sorted(Path(opml_dir).glob("*.opml")): text = f.read_text(encoding="utf-8", errors="replace") country = f.stem.replace("opml-", "").replace("_", " ") for name, url in re.findall(r'text="([^"]+)"[^>]*xmlUrl="([^"]+)"', text): out.append({"feed_url": html.unescape(url), "name": html.unescape(name), "category": "U" if country == "United States" else "W", "language": COUNTRY_LANG.get(country, "en")}) return out def candidates_from_wikidata(fetcher_text): q = ("SELECT ?itemLabel ?site ?countryLabel ?langCode WHERE { " "?item wdt:P856 ?site. " "{ ?item wdt:P31 wd:Q11032. } UNION { ?item wdt:P31 wd:Q41298. } " "UNION { ?item wdt:P31 wd:Q17232649. } " "OPTIONAL { ?item wdt:P17 ?country. } " "OPTIONAL { ?item wdt:P407/wdt:P218 ?langCode. } " "SERVICE wikibase:label { bd:serviceParam wikibase:language 'en'. } }") url = ("https://query.wikidata.org/sparql?query=" + urllib.parse.quote(q) + "&format=json") data = json.loads(fetcher_text(url)) out = [] for b in data["results"]["bindings"]: site = b["site"]["value"] country = b.get("countryLabel", {}).get("value", "") out.append({"site": site, "name": b.get("itemLabel", {}).get("value", ""), "category": "U" if country == "United States" else "W", "language": b.get("langCode", {}).get("value") or COUNTRY_LANG.get(country, "en")}) return out def selftest(): rss = ('Fixture Newsen-US' 'https://ex.com/a1') assert parse_feed(rss)[0] == "R" and parse_feed(rss)[3] == ["https://ex.com/a1"] sm = ('https://ex.com/story') assert parse_feed(sm)[0] == "S" assert parse_feed("nope") is None page = "".join(f"

{'word ' * 40}.

" for _ in range(5)) assert article_body_ok(page) and not article_body_ok("

tiny

") assert slugify("the-guardian.com") == "the-guardian-co" assert norm_domain("https://www.bbc.com/x") == "bbc.com" print("selftest ok") def main(): ap = argparse.ArgumentParser() ap.add_argument("--selftest", action="store_true") ap.add_argument("--opml-dir"); ap.add_argument("--wikidata", action="store_true") ap.add_argument("--candidates"); ap.add_argument("--existing", required=False) ap.add_argument("--out"); ap.add_argument("--report") ap.add_argument("--workers", type=int, default=48) ap.add_argument("--limit", type=int, default=0) args = ap.parse_args() if args.selftest: return selftest() fetcher = Fetcher() cands = [] if args.opml_dir: cands += candidates_from_opml(args.opml_dir) if args.wikidata: cands += candidates_from_wikidata( lambda u: fetcher.fetch(u, max_bytes=30_000_000)[1]) if args.candidates: for line in Path(args.candidates).read_text(encoding="utf-8").splitlines(): f = line.split("\t") if len(f) >= 1 and f[0].startswith("http"): cands.append({"feed_url": f[0], "name": f[1] if len(f) > 1 else "", "category": f[2] if len(f) > 2 else "W", "language": f[3] if len(f) > 3 else "en"}) domains, feeds, ids = load_existing(args.existing) seen_domains, seen_feeds = set(domains), set(feeds) todo, rejected = [], {} for c in cands: site = c.get("site") or c["feed_url"] d = norm_domain(site) if d in seen_domains: rejected["duplicate-existing-domain"] = rejected.get("duplicate-existing-domain", 0) + 1 continue seen_domains.add(d) if "feed_url" in c and norm_feed(c["feed_url"]) in seen_feeds: rejected["duplicate-feed"] = rejected.get("duplicate-feed", 0) + 1 continue if "feed_url" in c: seen_feeds.add(norm_feed(c["feed_url"])) todo.append(c) if args.limit: todo = todo[: args.limit] print(f"candidates={len(cands)} todo={len(todo)} pre-rejected={sum(rejected.values())}", flush=True) def work(c): cc = dict(c) if "feed_url" not in cc: found = discover_feed(fetcher, cc["site"]) if not found: return ("discover-none", c) cc["feed_url"] = found r = verify(cc, fetcher) return (r, cc) if isinstance(r, dict) else (r.split(":")[0], cc) rows = [] with ThreadPoolExecutor(max_workers=args.workers) as ex: for i, (res, c) in enumerate(ex.map(work, todo)): if isinstance(res, dict): base = slugify(norm_domain(res["feedUrl"])) sid, n = base, 2 while sid in ids: sid = f"{base}-{n}"; n += 1 ids.add(sid); res["id"] = sid; rows.append(res) else: rejected[res] = rejected.get(res, 0) + 1 if (i + 1) % 500 == 0: print(f"{i + 1}/{len(todo)} verified={len(rows)}", flush=True) if args.out: with open(args.out, "w", encoding="utf-8") as fh: for r in rows: fh.write("\t".join([r["id"], r["name"], r["feedUrl"], r["kind"], r["language"], r["categories"], "", ""]) + "\n") report = {"candidates": len(cands), "todo": len(todo), "verified": len(rows), "rejected": rejected} if args.report: Path(args.report).write_text(json.dumps(report, indent=1), encoding="utf-8") print(json.dumps(report, indent=1)) if __name__ == "__main__": main()