]*>(.*?)
", 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 = ('{'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()