Spaces:
Running on Zero
Running on Zero
Download scripts/scrape_te.py from MustafaHussein/te-assistant: direct link, hf CLI and curl.
- Browser
- Download file 9.8 kB
-
https://huggingface.co/spaces/MustafaHussein/te-assistant/resolve/main/scripts/scrape_te.py
- Command line
-
hf download hf://spaces/MustafaHussein/te-assistant/scripts/scrape_te.py
-
curl -L -o scrape_te.py https://huggingface.co/spaces/MustafaHussein/te-assistant/resolve/main/scripts/scrape_te.py
9.8 kB
| #!/usr/bin/env python | |
| """Polite crawler for te.eg -> data/te_corpus.jsonl | |
| Run this on YOUR machine (the build sandbox cannot reach te.eg): | |
| python scripts/scrape_te.py --max-pages 40 # first: small trial run, inspect the output | |
| python scripts/scrape_te.py --max-pages 600 # then the real crawl | |
| python scripts/scrape_te.py --render --max-pages 600 # if pages come back empty (JS-rendered site) | |
| Pages that were missing or thin in the first crawl (branches, promotion details): open te.eg, click | |
| "فروع وسنترالات" / the promotion's "المزيد" button, copy the page URL, and pass it as an extra seed: | |
| python scripts/scrape_te.py --render --max-pages 200 --max-depth 2 \ | |
| --seeds https://www.te.eg/web/guest/personal/promotions <branch-page-url> --out data/te_extra.jsonl | |
| then append data/te_extra.jsonl to data/te_corpus.jsonl and run scripts/build_index.py. | |
| --render needs: pip install playwright && playwright install chromium | |
| Each output line is one document: | |
| {"url", "title", "lang", "text"} for HTML pages | |
| {"url", "title", "lang", "pages": ["...", ...]} for PDFs (page-aware citations) | |
| """ | |
| import argparse | |
| import collections | |
| import hashlib | |
| import json | |
| import re | |
| import sys | |
| import time | |
| import urllib.robotparser | |
| from pathlib import Path | |
| from urllib.parse import urljoin, urldefrag, urlparse | |
| sys.path.insert(0, str(Path(__file__).resolve().parents[1])) | |
| import requests # noqa: E402 | |
| from bs4 import BeautifulSoup # noqa: E402 | |
| import config # noqa: E402 | |
| from core.corpus import is_excluded, looks_like_xml # noqa: E402 | |
| from core.lang import detect_language # noqa: E402 | |
| UA = "TE-Assistant-POC/0.1 (case-study crawler)" | |
| HEADERS = {"User-Agent": UA, "Accept-Language": "ar,en;q=0.8"} | |
| SKIP_EXT = ( | |
| ".jpg", ".jpeg", ".png", ".gif", ".svg", ".webp", ".ico", ".css", ".js", ".zip", | |
| ".rar", ".mp4", ".mp3", ".woff", ".woff2", ".ttf", ".xls", ".xlsx", ".doc", ".docx", | |
| ".ppt", ".pptx", ".apk", | |
| ) | |
| DROP_TAGS = ["script", "style", "noscript", "svg", "iframe", "form", "nav", "footer", "header", "aside"] | |
| SEEDS = ["https://www.te.eg/", "https://te.eg/"] | |
| class Fetcher: | |
| def __init__(self, render: bool): | |
| self.render = render | |
| self.session = requests.Session() | |
| self.session.headers.update(HEADERS) | |
| self._pw = self._browser = None | |
| if render: | |
| from playwright.sync_api import sync_playwright | |
| self._pw = sync_playwright().start() | |
| self._browser = self._pw.chromium.launch() | |
| def get(self, url: str): | |
| """Return (content_type, bytes_or_text) or None.""" | |
| if self.render and not url.lower().split("?")[0].endswith(".pdf"): | |
| page = self._browser.new_page() | |
| try: | |
| page.goto(url, wait_until="networkidle", timeout=45000) | |
| return "text/html", page.content() | |
| except Exception as e: # noqa: BLE001 | |
| print(f" render failed: {e}") | |
| return None | |
| finally: | |
| page.close() | |
| r = self.session.get(url, timeout=30) | |
| if r.status_code != 200: | |
| return None | |
| ctype = r.headers.get("content-type", "").lower() | |
| if "pdf" in ctype or url.lower().split("?")[0].endswith(".pdf"): | |
| return "application/pdf", r.content | |
| if "html" in ctype: # XML (sitemaps, feeds) is not page content | |
| r.encoding = r.apparent_encoding if (r.encoding or "").lower() == "iso-8859-1" else r.encoding | |
| return "text/html", r.text | |
| return None | |
| def close(self): | |
| if self._browser: | |
| self._browser.close() | |
| self._pw.stop() | |
| def in_scope(url: str) -> bool: | |
| p = urlparse(url) | |
| if p.scheme not in ("http", "https"): | |
| return False | |
| if not (p.netloc == "te.eg" or p.netloc.endswith(".te.eg")): | |
| return False | |
| if is_excluded(url): # sitemaps, press archive, board bios: do not spend requests on them | |
| return False | |
| return not p.path.lower().endswith(SKIP_EXT) | |
| def norm(url: str) -> str: | |
| return urldefrag(url)[0].rstrip("/") if urlparse(url).path not in ("", "/") else urldefrag(url)[0] | |
| def get_robots(host_url: str): | |
| rp = urllib.robotparser.RobotFileParser() | |
| try: | |
| r = requests.get(urljoin(host_url, "/robots.txt"), headers=HEADERS, timeout=15) | |
| rp.parse(r.text.splitlines() if r.status_code == 200 else []) | |
| except Exception: # noqa: BLE001 | |
| print(" (could not read robots.txt, continuing)") | |
| rp.parse([]) | |
| return rp | |
| def sitemap_urls(seed: str) -> list: | |
| out = [] | |
| try: | |
| r = requests.get(urljoin(seed, "/sitemap.xml"), headers=HEADERS, timeout=20) | |
| if r.status_code == 200: | |
| out = re.findall(r"<loc>\s*(.*?)\s*</loc>", r.text) | |
| except Exception: # noqa: BLE001 | |
| pass | |
| return out | |
| def extract_html(html: str, url: str): | |
| soup = BeautifulSoup(html, "lxml") | |
| links = [a["href"] for a in soup.find_all("a", href=True)] | |
| title = (soup.title.get_text(" ", strip=True) if soup.title else "") or url | |
| for t in soup(DROP_TAGS): | |
| t.decompose() | |
| main = soup.find("main") or soup.find(attrs={"role": "main"}) or soup.body or soup | |
| lines = [re.sub(r"\s+", " ", l).strip() for l in main.get_text("\n").splitlines()] | |
| lines = [l for l in lines if len(l) > 2] | |
| dedup = [l for i, l in enumerate(lines) if i == 0 or l != lines[i - 1]] | |
| return title, dedup, links | |
| def extract_pdf(data: bytes): | |
| import pymupdf as fitz | |
| doc = fitz.open(stream=data, filetype="pdf") | |
| pages = [(p.get_text("text") or "").strip() for p in doc] | |
| return [p for p in pages if p] | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--seeds", nargs="*", default=SEEDS) | |
| ap.add_argument("--max-pages", type=int, default=300) | |
| ap.add_argument("--max-depth", type=int, default=4) | |
| ap.add_argument("--delay", type=float, default=1.0, help="seconds between requests") | |
| ap.add_argument("--render", action="store_true", help="use headless Chromium (JS-rendered pages)") | |
| ap.add_argument("--min-chars", type=int, default=80, | |
| help="drop pages shorter than this (promotion detail pages are short, so keep this low)") | |
| ap.add_argument("--out", default=str(config.CORPUS_PATH)) | |
| args = ap.parse_args() | |
| fetcher = Fetcher(args.render) | |
| robots = {} | |
| queue = collections.deque((norm(s), 0) for s in args.seeds) | |
| for s in args.seeds: | |
| for u in sitemap_urls(s)[: args.max_pages]: | |
| if in_scope(u): | |
| queue.append((norm(u), 1)) | |
| seen, raw_docs, hashes = set(), [], set() | |
| while queue and len(seen) < args.max_pages: | |
| url, depth = queue.popleft() | |
| if url in seen or not in_scope(url): | |
| continue | |
| seen.add(url) | |
| host = f"{urlparse(url).scheme}://{urlparse(url).netloc}" | |
| if host not in robots: | |
| robots[host] = get_robots(host) | |
| if not robots[host].can_fetch(UA, url): | |
| print(f"[robots] skip {url}") | |
| continue | |
| print(f"[{len(seen)}/{args.max_pages}] d={depth} {url}") | |
| try: | |
| got = fetcher.get(url) | |
| except Exception as e: # noqa: BLE001 | |
| print(f" error: {e}") | |
| got = None | |
| time.sleep(args.delay) | |
| if not got: | |
| continue | |
| ctype, body = got | |
| if ctype == "application/pdf": | |
| try: | |
| pages = extract_pdf(body) | |
| except Exception as e: # noqa: BLE001 | |
| print(f" pdf error: {e}") | |
| continue | |
| joined = "\n".join(pages) | |
| if len(joined) >= args.min_chars: | |
| raw_docs.append({"url": url, "title": Path(urlparse(url).path).name or url, | |
| "lang": detect_language(joined), "pages": pages}) | |
| continue | |
| if looks_like_xml(body): | |
| continue | |
| title, lines, links = extract_html(body, url) | |
| text = "\n".join(lines) | |
| h = hashlib.md5(text.encode("utf-8")).hexdigest() | |
| if len(text) >= args.min_chars and h not in hashes: | |
| hashes.add(h) | |
| raw_docs.append({"url": url, "title": title, "lang": detect_language(text), "lines": lines}) | |
| if depth < args.max_depth: | |
| for href in links: | |
| nxt = norm(urljoin(url, href)) | |
| if nxt not in seen and in_scope(nxt): | |
| queue.append((nxt, depth + 1)) | |
| fetcher.close() | |
| # Remove boilerplate: lines that repeat on >30% of pages (menus, cookie banners, footers) | |
| html_docs = [d for d in raw_docs if "lines" in d] | |
| if len(html_docs) >= 8: | |
| freq = collections.Counter(l for d in html_docs for l in set(d["lines"])) | |
| limit = max(5, int(0.3 * len(html_docs))) | |
| boiler = {l for l, c in freq.items() if c >= limit} | |
| print(f"removing {len(boiler)} boilerplate lines") | |
| else: | |
| boiler = set() | |
| Path(args.out).parent.mkdir(parents=True, exist_ok=True) | |
| kept = 0 | |
| with open(args.out, "w", encoding="utf-8") as f: | |
| for d in raw_docs: | |
| if "lines" in d: | |
| text = "\n".join(l for l in d["lines"] if l not in boiler) | |
| if len(text) < args.min_chars: | |
| continue | |
| rec = {"url": d["url"], "title": d["title"], "lang": detect_language(text), "text": text} | |
| else: | |
| rec = d | |
| f.write(json.dumps(rec, ensure_ascii=False) + "\n") | |
| kept += 1 | |
| print(f"\nWrote {kept} documents (crawled {len(seen)} URLs) -> {args.out}") | |
| if kept == 0: | |
| print("Nothing kept. Try --render (JS site) and check robots.txt / network access.") | |
| if __name__ == "__main__": | |
| main() | |