Tahap 1: ingestion Google News, GDELT, ANTARA, Detik, CNN + validasi
This commit is contained in:
parent
68b4dcd0f5
commit
31864f7d2e
0
ingestion/__init__.py
Executable file
0
ingestion/__init__.py
Executable file
166
ingestion/common.py
Executable file
166
ingestion/common.py
Executable file
@ -0,0 +1,166 @@
|
||||
"""Fungsi bersama untuk tahap ingestion: skema, normalisasi tanggal, validasi, penulisan raw."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import warnings
|
||||
from collections import Counter
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from email.utils import parsedate_to_datetime
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import requests
|
||||
from bs4 import BeautifulSoup, MarkupResemblesLocatorWarning
|
||||
from requests.adapters import HTTPAdapter
|
||||
from urllib3.util.retry import Retry
|
||||
|
||||
import config
|
||||
|
||||
warnings.filterwarnings("ignore", category=MarkupResemblesLocatorWarning)
|
||||
|
||||
WIB = timezone(timedelta(hours=7))
|
||||
USER_AGENT = "Mozilla/5.0 (compatible; KarhutlaBigDataProject/1.0; student-project)"
|
||||
|
||||
# Skema seragam untuk semua sumber
|
||||
FIELDS = ["id", "judul", "isi", "tanggal_publikasi", "sumber", "sumber_data", "url", "kata_kunci", "wilayah_raw"]
|
||||
|
||||
KNOWN_MEDIA = {
|
||||
"antaranews.com": "ANTARA",
|
||||
"detik.com": "Detik.com",
|
||||
"cnnindonesia.com": "CNN Indonesia",
|
||||
}
|
||||
|
||||
|
||||
def make_session() -> requests.Session:
|
||||
s = requests.Session()
|
||||
retry = Retry(total=3, backoff_factor=1.5, status_forcelist=(429, 500, 502, 503, 504),
|
||||
allowed_methods=("GET",))
|
||||
s.mount("https://", HTTPAdapter(max_retries=retry))
|
||||
s.mount("http://", HTTPAdapter(max_retries=retry))
|
||||
s.headers.update({"User-Agent": USER_AGENT, "Accept-Language": "id,en;q=0.8"})
|
||||
return s
|
||||
|
||||
|
||||
def host_of(url: str) -> str:
|
||||
host = urlparse(url).netloc.lower()
|
||||
return host[4:] if host.startswith("www.") else host
|
||||
|
||||
|
||||
def media_from_url(url: str) -> str:
|
||||
host = host_of(url)
|
||||
for dom, name in KNOWN_MEDIA.items():
|
||||
if host == dom or host.endswith("." + dom):
|
||||
return name
|
||||
return host or "unknown"
|
||||
|
||||
|
||||
def make_id(url: str) -> str:
|
||||
return hashlib.sha1(url.strip().encode("utf-8")).hexdigest()[:16]
|
||||
|
||||
|
||||
def strip_html(text: str | None) -> str:
|
||||
if not text:
|
||||
return ""
|
||||
txt = BeautifulSoup(text, "html.parser").get_text(" ")
|
||||
return re.sub(r"\s+", " ", txt).strip()
|
||||
|
||||
|
||||
def parse_date_any(value: str | None) -> str | None:
|
||||
"""Ubah berbagai format tanggal ke ISO 'YYYY-MM-DDTHH:MM:SS' (zona WIB). None bila gagal."""
|
||||
if not value:
|
||||
return None
|
||||
value = value.strip()
|
||||
dt = None
|
||||
for parser in (
|
||||
lambda v: datetime.strptime(v, "%Y%m%dT%H%M%SZ").replace(tzinfo=timezone.utc), # GDELT
|
||||
lambda v: datetime.fromisoformat(v.replace("Z", "+00:00")), # ISO 8601
|
||||
lambda v: parsedate_to_datetime(v), # RFC 822 (RSS)
|
||||
lambda v: datetime.strptime(v, "%Y/%m/%d %H:%M:%S"), # Detik
|
||||
lambda v: datetime.strptime(v, "%Y/%m/%d %H:%M"),
|
||||
lambda v: datetime.strptime(v, "%d/%m/%Y %H:%M:%S"),
|
||||
lambda v: datetime.strptime(v, "%d/%m/%Y %H:%M"),
|
||||
):
|
||||
try:
|
||||
dt = parser(value)
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
if dt is None:
|
||||
return None
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=WIB)
|
||||
return dt.astimezone(WIB).strftime("%Y-%m-%dT%H:%M:%S")
|
||||
|
||||
|
||||
def build_record(*, judul, url, tanggal, sumber, sumber_data, kata_kunci="", isi="", wilayah_raw="") -> dict:
|
||||
return {
|
||||
"id": make_id(url) if url else "",
|
||||
"judul": (judul or "").strip(),
|
||||
"isi": (isi or "").strip(),
|
||||
"tanggal_publikasi": tanggal,
|
||||
"sumber": sumber,
|
||||
"sumber_data": sumber_data,
|
||||
"url": (url or "").strip(),
|
||||
"kata_kunci": kata_kunci,
|
||||
"wilayah_raw": wilayah_raw,
|
||||
}
|
||||
|
||||
|
||||
def validate_record(rec: dict) -> tuple[bool, str]:
|
||||
"""Validasi atribut utama (Bab 4.1): judul, tanggal publikasi, sumber, tautan."""
|
||||
if not rec.get("judul"):
|
||||
return False, "judul_kosong"
|
||||
if not rec.get("tanggal_publikasi"):
|
||||
return False, "tanggal_kosong_atau_tidak_terbaca"
|
||||
if not rec.get("sumber"):
|
||||
return False, "sumber_kosong"
|
||||
if not str(rec.get("url", "")).startswith("http"):
|
||||
return False, "url_tidak_valid"
|
||||
return True, ""
|
||||
|
||||
|
||||
def month_windows(start: date, end: date, days: int):
|
||||
"""Pecah rentang [start, end] menjadi jendela `days` hari: (a, b) dengan b eksklusif."""
|
||||
cur = start
|
||||
while cur <= end:
|
||||
nxt = min(cur + timedelta(days=days), end + timedelta(days=1))
|
||||
yield cur, nxt
|
||||
cur = nxt
|
||||
|
||||
|
||||
def write_records(records, channel: str, run_id: str) -> dict:
|
||||
"""Validasi lalu tulis ke raw/<channel>/<YYYY-MM>/<channel>_<run_id>.jsonl.
|
||||
Record yang gagal validasi disimpan di reports/rejected_*.jsonl."""
|
||||
stats = Counter()
|
||||
reasons = Counter()
|
||||
handles: dict[str, object] = {}
|
||||
rejected_path = config.REPORT_DIR / f"rejected_{channel}_{run_id}.jsonl"
|
||||
rejected_fh = None
|
||||
try:
|
||||
for rec in records:
|
||||
stats["total"] += 1
|
||||
ok, reason = validate_record(rec)
|
||||
if ok:
|
||||
month = rec["tanggal_publikasi"][:7]
|
||||
if month not in handles:
|
||||
d = config.RAW_LOCAL_DIR / channel / month
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
handles[month] = open(d / f"{channel}_{run_id}.jsonl", "a", encoding="utf-8")
|
||||
handles[month].write(json.dumps(rec, ensure_ascii=False) + "\n")
|
||||
stats["valid"] += 1
|
||||
else:
|
||||
if rejected_fh is None:
|
||||
config.REPORT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
rejected_fh = open(rejected_path, "a", encoding="utf-8")
|
||||
rejected_fh.write(json.dumps({**rec, "_reason": reason}, ensure_ascii=False) + "\n")
|
||||
stats["rejected"] += 1
|
||||
reasons[reason] += 1
|
||||
finally:
|
||||
for fh in handles.values():
|
||||
fh.close()
|
||||
if rejected_fh:
|
||||
rejected_fh.close()
|
||||
return {"channel": channel, "total": stats["total"], "valid": stats["valid"],
|
||||
"rejected": stats["rejected"], "reject_reasons": dict(reasons)}
|
||||
64
ingestion/gdelt.py
Executable file
64
ingestion/gdelt.py
Executable file
@ -0,0 +1,64 @@
|
||||
"""Pengumpulan berita dari GDELT DOC 2.0 API (mode ArtList).
|
||||
Batas: maks 250 artikel per request, dan ~1 request / 5 detik, sehingga data dipecah per jendela waktu."""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from datetime import date, timedelta
|
||||
|
||||
from ingestion.common import build_record, media_from_url, month_windows, parse_date_any
|
||||
|
||||
CHANNEL = "gdelt"
|
||||
API = "https://api.gdeltproject.org/api/v2/doc/doc"
|
||||
MAX_CONSECUTIVE_FAILURES = 4 # berhenti lebih awal bila GDELT terus gagal merespons
|
||||
|
||||
|
||||
def _request(session, params, retries: int = 2, timeout: int = 40):
|
||||
"""Kembalikan (data, error). error berisi penyebab singkat bila gagal."""
|
||||
err = ""
|
||||
for attempt in range(retries):
|
||||
try:
|
||||
r = session.get(API, params=params, timeout=timeout)
|
||||
if r.status_code != 200:
|
||||
err = f"HTTP {r.status_code}: {r.text[:150].strip()}"
|
||||
else:
|
||||
try:
|
||||
return r.json(), ""
|
||||
except ValueError:
|
||||
# GDELT mengirim teks biasa (bukan JSON) saat kena rate limit / query tidak valid
|
||||
err = f"respons bukan JSON: {r.text[:150].strip()}"
|
||||
except Exception as exc:
|
||||
err = f"{type(exc).__name__}: {str(exc)[:150]}"
|
||||
time.sleep(8 * (attempt + 1))
|
||||
return None, err
|
||||
|
||||
|
||||
def collect(keywords, start: date, end: date, session, window_days: int = 7, sleep: float = 5.5, limit: int | None = None):
|
||||
n = 0
|
||||
failures = 0
|
||||
for a, b in month_windows(start, end, window_days):
|
||||
last_day = b - timedelta(days=1)
|
||||
for kw in keywords:
|
||||
params = {
|
||||
"query": f'"{kw}" sourcelang:indonesian',
|
||||
"mode": "artlist", "format": "json", "maxrecords": 250, "sort": "datedesc",
|
||||
"startdatetime": a.strftime("%Y%m%d") + "000000",
|
||||
"enddatetime": last_day.strftime("%Y%m%d") + "235959",
|
||||
}
|
||||
data, err = _request(session, params)
|
||||
time.sleep(sleep)
|
||||
if data is None:
|
||||
failures += 1
|
||||
print(f"[gdelt] gagal {a}..{b} '{kw}' -> {err}", flush=True)
|
||||
if failures >= MAX_CONSECUTIVE_FAILURES:
|
||||
raise RuntimeError(f"GDELT gagal {failures}x berturut-turut. Penyebab terakhir: {err}")
|
||||
continue
|
||||
failures = 0
|
||||
for art in data.get("articles", []):
|
||||
url = art.get("url", "")
|
||||
yield build_record(
|
||||
judul=art.get("title", ""), url=url, tanggal=parse_date_any(art.get("seendate")),
|
||||
sumber=media_from_url(url), sumber_data=CHANNEL, kata_kunci=kw,
|
||||
)
|
||||
n += 1
|
||||
if limit and n >= limit:
|
||||
return
|
||||
57
ingestion/google_news.py
Executable file
57
ingestion/google_news.py
Executable file
@ -0,0 +1,57 @@
|
||||
"""Pengumpulan berita dari Google News RSS (feedparser).
|
||||
Satu request per (kata kunci, jendela waktu) karena RSS membatasi jumlah item per request."""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from datetime import date
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import feedparser
|
||||
|
||||
from ingestion.common import (KNOWN_MEDIA, build_record, host_of, media_from_url,
|
||||
month_windows, parse_date_any, strip_html)
|
||||
|
||||
CHANNEL = "google_news"
|
||||
BASE = "https://news.google.com/rss/search"
|
||||
|
||||
|
||||
def _media_name(entry) -> str:
|
||||
src = entry.get("source") or {}
|
||||
href, title = src.get("href", ""), src.get("title", "")
|
||||
if href and any(host_of(href).endswith(d) for d in KNOWN_MEDIA):
|
||||
return media_from_url(href)
|
||||
return title or (media_from_url(href) if href else "Google News")
|
||||
|
||||
|
||||
def collect(keywords, start: date, end: date, session, window_days: int = 7, sleep: float = 1.5, limit: int | None = None):
|
||||
n = 0
|
||||
for a, b in month_windows(start, end, window_days):
|
||||
for kw in keywords:
|
||||
q = f"{kw} after:{a.isoformat()} before:{b.isoformat()}"
|
||||
url = BASE + "?" + urlencode({"q": q, "hl": "id", "gl": "ID", "ceid": "ID:id"})
|
||||
try:
|
||||
resp = session.get(url, timeout=30)
|
||||
resp.raise_for_status()
|
||||
except Exception as exc: # jaringan/rate limit: lanjut ke jendela berikutnya
|
||||
print(f"[google_news] gagal {a}..{b} '{kw}': {exc}")
|
||||
time.sleep(sleep * 2)
|
||||
continue
|
||||
feed = feedparser.parse(resp.content)
|
||||
for e in feed.entries:
|
||||
media = _media_name(e)
|
||||
title = (e.get("title") or "").strip()
|
||||
raw_src = ((e.get("source") or {}).get("title") or "").strip()
|
||||
for suffix in {raw_src, media}: # judul Google berformat "Judul - Nama Media"
|
||||
if suffix and title.endswith(" - " + suffix):
|
||||
title = title[: -len(suffix) - 3].strip()
|
||||
break
|
||||
summary = strip_html(e.get("summary"))
|
||||
isi = "" if (not summary or summary.startswith(title[:40])) else summary
|
||||
yield build_record(
|
||||
judul=title, url=e.get("link", ""), tanggal=parse_date_any(e.get("published")),
|
||||
sumber=media, sumber_data=CHANNEL, kata_kunci=kw, isi=isi,
|
||||
)
|
||||
n += 1
|
||||
if limit and n >= limit:
|
||||
return
|
||||
time.sleep(sleep)
|
||||
194
ingestion/portals.py
Executable file
194
ingestion/portals.py
Executable file
@ -0,0 +1,194 @@
|
||||
"""Scraper portal berita: ANTARA, Detik.com, CNN Indonesia.
|
||||
|
||||
CATATAN: struktur HTML & URL pencarian portal bisa berubah kapan saja. Modul ini tidak bergantung pada CSS
|
||||
selector yang rapuh: tautan artikel dicari dengan pola URL (absolut maupun relatif), metadata diambil dari
|
||||
<meta>/JSON-LD, dan isi artikel dicoba lewat beberapa selector umum. Gunakan scripts/debug_portal.py untuk
|
||||
memeriksa tiap portal, dan patuhi robots.txt serta syarat penggunaan situs."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import time
|
||||
from collections import Counter
|
||||
from datetime import date, datetime
|
||||
from urllib.parse import quote_plus, urljoin
|
||||
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
from ingestion.common import build_record, parse_date_any
|
||||
|
||||
PORTALS = {
|
||||
"antara": {
|
||||
"name": "ANTARA",
|
||||
"search": "https://www.antaranews.com/search?q={q}&page={page}",
|
||||
"link_re": re.compile(r"https?://(?:www\.)?antaranews\.com/berita/\d+/[^\s\"'#?]+"),
|
||||
},
|
||||
"detik": {
|
||||
"name": "Detik.com",
|
||||
"search": "https://www.detik.com/search/searchall?query={q}&page={page}&result_type=latest",
|
||||
"link_re": re.compile(r"https?://[a-z0-9.\-]*detik\.com/[^\s\"'#?]*?/d-\d+/[^\s\"'#?]+"),
|
||||
},
|
||||
"cnn": {
|
||||
"name": "CNN Indonesia",
|
||||
# Halaman pencarian CNN tidak berisi tautan artikel (dirender JavaScript); halaman tag berisi.
|
||||
"search": "https://www.cnnindonesia.com/tag/{q}?page={page}",
|
||||
"query_style": "slug",
|
||||
"link_re": re.compile(r"https?://(?:www\.)?cnnindonesia\.com/[a-z0-9\-]+/\d{14}-\d+-\d+/[^\s\"'#?]+"),
|
||||
},
|
||||
}
|
||||
|
||||
# Hasil pencarian portal sering memuat berita tak terkait (sidebar, terpopuler). Tautan yang slug-nya tidak
|
||||
# memuat salah satu petunjuk ini dilewati agar tidak membuka ratusan halaman sia-sia.
|
||||
SLUG_SUBSTR = ["karhutla", "karlahut", "kebakaran", "bakar", "hutan", "lahan", "gambut", "kabut", "padam",
|
||||
"hotspot", "ispu", "titik-panas", "titik-api", "water-bombing", "modifikasi-cuaca"]
|
||||
SLUG_TOKENS = {"api", "asap"} # kata pendek: harus berdiri sendiri ('api', bukan 'rapi')
|
||||
|
||||
_DATE_META = [
|
||||
("property", r"^article:published_time$"), ("name", r"^(content_)?publishdate$"),
|
||||
("name", r"^content_publisheddate$"), ("itemprop", r"^datePublished$"),
|
||||
("name", r"^pubdate$"), ("property", r"^og:updated_time$"),
|
||||
]
|
||||
|
||||
_BODY_SELECTORS = ["[itemprop=articleBody]", "div.post-content", "div.detail__body-text", "div.detail-text",
|
||||
"div.detail_text", "div.article-content", "div.entry-content", "article"]
|
||||
_JUNK_SELECTORS = ["script", "style", "aside", "figure", "iframe", "noscript", ".parallaxindetail",
|
||||
".staticdetail_container", ".detail__body-tag", ".baca-juga", ".related",
|
||||
"[class*=advert]", "[class*=baca]", "[class*=terkait]"]
|
||||
_JUNK_PREFIX = ("baca juga", "baca:", "advertisement", "scroll to continue", "simak juga", "lihat juga")
|
||||
|
||||
|
||||
def extract_links(html: str, base_url: str, link_re: re.Pattern) -> list[str]:
|
||||
"""Tautan artikel dari halaman: dari atribut href (absolut/relatif) dan URL absolut di teks mentah."""
|
||||
cands = list(link_re.findall(html))
|
||||
for h in re.findall(r'href=["\']([^"\']+)["\']', html):
|
||||
cands.append(urljoin(base_url, h.split("#")[0]))
|
||||
out = []
|
||||
for u in cands:
|
||||
m = link_re.match(u.split("?")[0])
|
||||
if m:
|
||||
out.append(m.group(0))
|
||||
return list(dict.fromkeys(out))
|
||||
|
||||
|
||||
def slug_relevant(url: str) -> bool:
|
||||
low = url.lower()
|
||||
return any(h in low for h in SLUG_SUBSTR) or bool(SLUG_TOKENS & set(re.split(r"[^a-z0-9]+", low)))
|
||||
|
||||
|
||||
def query_for(portal: dict, keyword: str) -> str:
|
||||
"""Bentuk kata kunci di URL: 'karhutla+api' (pencarian) atau 'kebakaran-hutan' (halaman tag)."""
|
||||
if portal.get("query_style") == "slug":
|
||||
return re.sub(r"[^a-z0-9]+", "-", keyword.lower()).strip("-")
|
||||
return quote_plus(keyword)
|
||||
|
||||
|
||||
def discover_links(portal: dict, keyword: str, max_pages: int, session, sleep: float):
|
||||
seen: set[str] = set()
|
||||
for page in range(1, max_pages + 1):
|
||||
url = portal["search"].format(q=query_for(portal, keyword), page=page)
|
||||
try:
|
||||
r = session.get(url, timeout=30)
|
||||
r.raise_for_status()
|
||||
except Exception as exc:
|
||||
print(f"[{portal['name']}] gagal halaman pencarian {page} '{keyword}': {exc}", flush=True)
|
||||
break
|
||||
found = [u for u in extract_links(r.text, url, portal["link_re"]) if u not in seen]
|
||||
if not found:
|
||||
if page == 1:
|
||||
print(f"[{portal['name']}] halaman pencarian 1 '{keyword}' (HTTP {r.status_code}, {len(r.text)} karakter) "
|
||||
f"tidak berisi tautan artikel yang cocok. Jalankan scripts/debug_portal.py.", flush=True)
|
||||
break
|
||||
for u in found:
|
||||
seen.add(u)
|
||||
yield u
|
||||
time.sleep(sleep)
|
||||
|
||||
|
||||
def _extract_body(soup: BeautifulSoup) -> str:
|
||||
for sel in _BODY_SELECTORS:
|
||||
node = soup.select_one(sel)
|
||||
if not node:
|
||||
continue
|
||||
for junk in node.select(",".join(_JUNK_SELECTORS)):
|
||||
junk.decompose()
|
||||
lines = [re.sub(r"\s+", " ", ln).strip() for ln in node.get_text("\n").split("\n")]
|
||||
lines = [ln for ln in lines if len(ln) >= 40 and not ln.lower().startswith(_JUNK_PREFIX)]
|
||||
text = " ".join(lines)
|
||||
if len(text) >= 200:
|
||||
return text[:20000]
|
||||
paras = [p.get_text(" ", strip=True) for p in soup.find_all("p")]
|
||||
paras = [p for p in paras if len(p) >= 40 and not p.lower().startswith(_JUNK_PREFIX)]
|
||||
return " ".join(paras)[:20000]
|
||||
|
||||
|
||||
def fetch_article(url: str, session, timeout: int = 30) -> dict:
|
||||
"""Ambil judul, tanggal, dan isi dari satu halaman artikel. Bila gagal, kolom 'error' terisi."""
|
||||
try:
|
||||
r = session.get(url, timeout=timeout)
|
||||
r.raise_for_status()
|
||||
except Exception as exc:
|
||||
status = getattr(getattr(exc, "response", None), "status_code", None)
|
||||
return {"judul": "", "isi": "", "tanggal": None, "url": url, "raw_date": None, "date_source": None,
|
||||
"html": "", "error": f"HTTP {status}" if status else type(exc).__name__}
|
||||
soup = BeautifulSoup(r.text, "html.parser")
|
||||
|
||||
og = soup.find("meta", attrs={"property": "og:title"})
|
||||
title = (og.get("content") if og and og.get("content") else (soup.h1.get_text(" ", strip=True) if soup.h1 else "")).strip()
|
||||
|
||||
raw_date, date_source = None, None
|
||||
for attr, pattern in _DATE_META:
|
||||
tag = soup.find("meta", attrs={attr: re.compile(pattern, re.I)})
|
||||
if tag and tag.get("content"):
|
||||
raw_date, date_source = tag["content"], f"meta[{attr}~{pattern}]"
|
||||
break
|
||||
if not raw_date:
|
||||
m = re.search(r'"datePublished"\s*:\s*"([^"]+)"', r.text)
|
||||
raw_date, date_source = (m.group(1), "json-ld datePublished") if m else (None, None)
|
||||
if not raw_date:
|
||||
t = soup.find("time", attrs={"datetime": True})
|
||||
raw_date, date_source = (t["datetime"], "time[datetime]") if t else (None, None)
|
||||
|
||||
body = _extract_body(soup)
|
||||
return {"judul": title, "isi": body, "tanggal": parse_date_any(raw_date), "url": url,
|
||||
"raw_date": raw_date, "date_source": date_source, "html": r.text, "error": None}
|
||||
|
||||
|
||||
def collect(portal_key: str, keywords, start: date, end: date, session,
|
||||
max_pages: int = 5, sleep: float = 1.5, limit: int | None = None, slug_filter: bool = True):
|
||||
portal = PORTALS[portal_key]
|
||||
seen_urls: set[str] = set()
|
||||
n = 0
|
||||
diag: Counter = Counter()
|
||||
try:
|
||||
for kw in keywords:
|
||||
for url in discover_links(portal, kw, max_pages, session, sleep):
|
||||
if url in seen_urls:
|
||||
continue
|
||||
seen_urls.add(url)
|
||||
diag["tautan_ditemukan"] += 1
|
||||
if slug_filter and not slug_relevant(url):
|
||||
diag["dilewati_slug_tak_relevan"] += 1
|
||||
continue
|
||||
art = fetch_article(url, session)
|
||||
time.sleep(sleep)
|
||||
if art.get("error"):
|
||||
diag[f"gagal_buka ({art['error']})"] += 1
|
||||
continue
|
||||
if not art["tanggal"]:
|
||||
diag["tanggal_tidak_terbaca"] += 1
|
||||
if diag["tanggal_tidak_terbaca"] <= 2:
|
||||
print(f"[{portal['name']}] tanggal tidak terbaca: {url} (raw={art['raw_date']!r})", flush=True)
|
||||
continue
|
||||
d = datetime.fromisoformat(art["tanggal"]).date()
|
||||
if d < start or d > end:
|
||||
diag["di_luar_rentang_tanggal"] += 1
|
||||
continue
|
||||
if not art["isi"]:
|
||||
diag["isi_kosong (tetap disimpan)"] += 1
|
||||
diag["diterima"] += 1
|
||||
yield build_record(judul=art["judul"], url=url, tanggal=art["tanggal"], sumber=portal["name"],
|
||||
sumber_data=portal_key, kata_kunci=kw, isi=art["isi"])
|
||||
n += 1
|
||||
if limit and n >= limit:
|
||||
return
|
||||
finally:
|
||||
print(f"[{portal['name']}] ringkasan: {dict(diag) or 'tidak ada tautan artikel ditemukan'}", flush=True)
|
||||
78
ingestion/run_ingestion.py
Executable file
78
ingestion/run_ingestion.py
Executable file
@ -0,0 +1,78 @@
|
||||
"""Orkestrasi ingestion. Contoh:
|
||||
python -m ingestion.run_ingestion --sources google_news,gdelt --start 2024-01-01 --end 2026-11-04
|
||||
python -m ingestion.run_ingestion --sources antara,detik,cnn --limit 5 # uji cepat
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import time
|
||||
from datetime import date, datetime
|
||||
|
||||
import config
|
||||
from ingestion import gdelt, google_news, portals
|
||||
from ingestion.common import make_session, write_records
|
||||
|
||||
|
||||
def fetch_body_for(records, session, sleep: float = 1.0):
|
||||
"""Lengkapi kolom `isi` (data GDELT hanya berisi judul) dengan membuka halaman artikelnya."""
|
||||
for rec in records:
|
||||
art = portals.fetch_article(rec["url"], session)
|
||||
if art and art.get("isi"):
|
||||
rec["isi"] = art["isi"]
|
||||
time.sleep(sleep)
|
||||
yield rec
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Pengumpulan data berita karhutla")
|
||||
ap.add_argument("--sources", default="google_news,gdelt,antara,detik,cnn")
|
||||
ap.add_argument("--start", default=config.DATE_START)
|
||||
ap.add_argument("--end", default=config.DATE_END)
|
||||
ap.add_argument("--keywords", default="|".join(config.KEYWORDS), help="dipisah tanda |")
|
||||
ap.add_argument("--window-days", type=int, default=7)
|
||||
ap.add_argument("--max-pages", type=int, default=5, help="halaman pencarian per kata kunci (portal)")
|
||||
ap.add_argument("--limit", type=int, default=None, help="batasi jumlah artikel per sumber (untuk uji)")
|
||||
ap.add_argument("--fetch-body", action="store_true", help="ambil isi artikel untuk data GDELT")
|
||||
ap.add_argument("--no-slug-filter", action="store_true", help="portal: buka semua tautan hasil pencarian (lebih lambat)")
|
||||
args = ap.parse_args()
|
||||
|
||||
start, end = date.fromisoformat(args.start), date.fromisoformat(args.end)
|
||||
keywords = [k.strip() for k in args.keywords.split("|") if k.strip()]
|
||||
run_id = datetime.now().strftime("%Y%m%d%H%M%S")
|
||||
session = make_session()
|
||||
|
||||
generators = {
|
||||
"google_news": lambda: google_news.collect(keywords, start, end, session, args.window_days, limit=args.limit),
|
||||
"gdelt": lambda: gdelt.collect(keywords, start, end, session, args.window_days, limit=args.limit),
|
||||
**{k: (lambda k=k: portals.collect(k, keywords, start, end, session, args.max_pages, limit=args.limit,
|
||||
slug_filter=not args.no_slug_filter))
|
||||
for k in portals.PORTALS},
|
||||
}
|
||||
|
||||
report = []
|
||||
for ch in [s.strip() for s in args.sources.split(",") if s.strip()]:
|
||||
if ch not in generators:
|
||||
print(f"sumber tidak dikenal: {ch}")
|
||||
continue
|
||||
print(f"== {ch} ==")
|
||||
t0 = time.perf_counter()
|
||||
try:
|
||||
gen = generators[ch]()
|
||||
if ch == "gdelt" and args.fetch_body:
|
||||
gen = fetch_body_for(gen, session)
|
||||
stats = write_records(gen, ch, run_id)
|
||||
except Exception as exc: # satu sumber gagal tidak boleh menghentikan sumber lain (mitigasi risiko)
|
||||
stats = {"channel": ch, "error": str(exc)}
|
||||
stats["seconds"] = round(time.perf_counter() - t0, 2)
|
||||
print(stats)
|
||||
report.append(stats)
|
||||
|
||||
config.REPORT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
out = config.REPORT_DIR / f"ingestion_report_{run_id}.json"
|
||||
out.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
print(f"laporan: {out}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
91
scripts/debug_portal.py
Normal file
91
scripts/debug_portal.py
Normal file
@ -0,0 +1,91 @@
|
||||
"""Diagnostik scraper portal: lihat apa yang sebenarnya dikembalikan situs, dan simpan HTML-nya.
|
||||
docker compose exec pipeline python scripts/debug_portal.py antara detik cnn
|
||||
Hasil HTML: data/reports/debug_<portal>_search.html dan debug_<portal>_article.html"""
|
||||
import re
|
||||
import sys
|
||||
|
||||
import config
|
||||
from ingestion import portals
|
||||
from ingestion.common import make_session
|
||||
|
||||
# URL alternatif yang ikut diuji bila halaman pencarian utama tidak menghasilkan tautan artikel
|
||||
ALTERNATIVES = {
|
||||
"cnn": ["https://www.cnnindonesia.com/tag/karhutla", "https://www.cnnindonesia.com/tag/kebakaran-hutan",
|
||||
"https://www.cnnindonesia.com/search?query=karhutla"],
|
||||
"detik": ["https://www.detik.com/tag/karhutla"],
|
||||
"antara": ["https://www.antaranews.com/tag/karhutla"],
|
||||
}
|
||||
ASSET = re.compile(r"\.(css|js|png|jpe?g|gif|svg|ico|webp|woff2?|xml|json)(\?|$)", re.I)
|
||||
|
||||
|
||||
def looks_like_article(href: str) -> bool:
|
||||
path = href.split("?")[0].split("#")[0]
|
||||
path = re.sub(r"^https?://[^/]+", "", path)
|
||||
return not ASSET.search(href) and path.count("/") >= 2 and bool(re.search(r"\d{5,}", path))
|
||||
|
||||
|
||||
def probe(url: str, portal: dict, session, save_as: str | None = None):
|
||||
try:
|
||||
r = session.get(url, timeout=30)
|
||||
except Exception as exc:
|
||||
print(f" GAGAL request {url}: {type(exc).__name__}: {exc}")
|
||||
return None, []
|
||||
if save_as:
|
||||
(config.REPORT_DIR / save_as).write_text(r.text, encoding="utf-8")
|
||||
links = portals.extract_links(r.text, url, portal["link_re"])
|
||||
print(f" {url}\n HTTP {r.status_code} | {len(r.text)} karakter | tautan artikel cocok pola: {len(links)}")
|
||||
return r, links
|
||||
|
||||
|
||||
def debug(key: str, session, keyword: str = "karhutla"):
|
||||
portal = portals.PORTALS[key]
|
||||
url = portal["search"].format(q=portals.query_for(portal, keyword), page=1)
|
||||
print(f"\n=== {portal['name']} ===")
|
||||
config.REPORT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
r, links = probe(url, portal, session, save_as=f"debug_{key}_search.html")
|
||||
if r is None:
|
||||
return
|
||||
for u in links[:5]:
|
||||
print(" ", u)
|
||||
relevan = [u for u in links if portals.slug_relevant(u)]
|
||||
print(f" dari {len(links)} tautan, {len(relevan)} lolos filter slug (yang akan dibuka)")
|
||||
|
||||
if not links:
|
||||
hrefs = list(dict.fromkeys(re.findall(r'href=["\']([^"\']+)["\']', r.text)))
|
||||
cand = [h for h in hrefs if looks_like_article(h)]
|
||||
print(f" href yang tampak seperti artikel ({len(cand)} dari {len(hrefs)} href), 15 contoh:")
|
||||
for h in cand[:15]:
|
||||
print(" ", h[:150])
|
||||
print(" Mencoba URL alternatif:")
|
||||
for alt in ALTERNATIVES.get(key, []):
|
||||
r2, l2 = probe(alt, portal, session, save_as=f"debug_{key}_alt{ALTERNATIVES[key].index(alt)}.html")
|
||||
for u in l2[:3]:
|
||||
print(" ", u)
|
||||
return
|
||||
|
||||
# cek pagination: halaman 2 dan 3 harus memuat tautan BARU
|
||||
seen = set(links)
|
||||
for pg in (2, 3):
|
||||
u = portal["search"].format(q=portals.query_for(portal, keyword), page=pg)
|
||||
try:
|
||||
rp = session.get(u, timeout=30)
|
||||
new = [x for x in portals.extract_links(rp.text, u, portal["link_re"]) if x not in seen]
|
||||
seen.update(new)
|
||||
print(f" halaman {pg}: HTTP {rp.status_code}, tautan baru: {len(new)}")
|
||||
except Exception as exc:
|
||||
print(f" halaman {pg}: gagal ({type(exc).__name__})")
|
||||
|
||||
art = portals.fetch_article(relevan[0] if relevan else links[0], session)
|
||||
(config.REPORT_DIR / f"debug_{key}_article.html").write_text(art.get("html", ""), encoding="utf-8")
|
||||
print(f"\n Artikel contoh: {art['url']}")
|
||||
print(f" error : {art.get('error')}")
|
||||
print(f" judul : {art['judul'][:100]!r}")
|
||||
print(f" tanggal raw: {art['raw_date']!r} (sumber: {art['date_source']}) -> terbaca: {art['tanggal']}")
|
||||
print(f" panjang isi: {len(art['isi'])} karakter | awal isi: {art['isi'][:120]!r}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
keys = sys.argv[1:] or list(portals.PORTALS)
|
||||
s = make_session()
|
||||
for k in keys:
|
||||
debug(k, s)
|
||||
0
tests/__init__.py
Executable file
0
tests/__init__.py
Executable file
185
tests/test_ingestion.py
Executable file
185
tests/test_ingestion.py
Executable file
@ -0,0 +1,185 @@
|
||||
"""Uji parser ingestion dengan respons palsu (tanpa internet)."""
|
||||
import json
|
||||
from datetime import date
|
||||
|
||||
import config
|
||||
from ingestion import gdelt, google_news, portals
|
||||
from ingestion.common import build_record, media_from_url, parse_date_any, validate_record, write_records
|
||||
|
||||
RSS = """<?xml version="1.0"?><rss version="2.0"><channel>
|
||||
<item><title>Karhutla Riau meluas - ANTARA News</title><link>https://news.google.com/rss/articles/abc?oc=5</link>
|
||||
<pubDate>Mon, 02 Sep 2024 08:30:00 GMT</pubDate><description><a>Karhutla Riau meluas</a></description>
|
||||
<source url="https://www.antaranews.com">ANTARA News</source></item></channel></rss>"""
|
||||
|
||||
HTML = """<html><head><meta property="og:title" content="Kabut Asap Selimuti Pekanbaru">
|
||||
<meta property="article:published_time" content="2024-09-15T10:00:00+07:00"></head><body><article>
|
||||
<p>Kabut asap tebal menyelimuti Kota Pekanbaru sejak pagi akibat karhutla di sekitar wilayah Riau.</p>
|
||||
<p>Baca juga: berita lain</p></article></body></html>"""
|
||||
|
||||
|
||||
class FakeResp:
|
||||
def __init__(self, content=b"", text="", js=None):
|
||||
self.content, self.text, self._js = content, text, js
|
||||
|
||||
status_code = 200
|
||||
|
||||
def raise_for_status(self): pass
|
||||
def json(self):
|
||||
if self._js is None:
|
||||
raise ValueError("bukan json")
|
||||
return self._js
|
||||
|
||||
|
||||
class FakeSession:
|
||||
def __init__(self, resp): self.resp = resp
|
||||
def get(self, *a, **k): return self.resp
|
||||
|
||||
|
||||
def test_parse_date():
|
||||
assert parse_date_any("20240902T083000Z") == "2024-09-02T15:30:00"
|
||||
assert parse_date_any("Mon, 02 Sep 2024 08:30:00 GMT") == "2024-09-02T15:30:00"
|
||||
assert parse_date_any("bukan tanggal") is None
|
||||
|
||||
|
||||
def test_media_from_url():
|
||||
assert media_from_url("https://www.detik.com/x") == "Detik.com"
|
||||
assert media_from_url("https://news.detik.com/x") == "Detik.com"
|
||||
assert media_from_url("https://kompas.com/x") == "kompas.com"
|
||||
|
||||
|
||||
def test_validate():
|
||||
ok = build_record(judul="a", url="https://x.com/1", tanggal="2024-01-01T00:00:00", sumber="X", sumber_data="t")
|
||||
assert validate_record(ok)[0]
|
||||
assert validate_record({**ok, "tanggal_publikasi": None}) == (False, "tanggal_kosong_atau_tidak_terbaca")
|
||||
|
||||
|
||||
def test_google_news_parse(monkeypatch):
|
||||
monkeypatch.setattr("time.sleep", lambda s: None)
|
||||
recs = list(google_news.collect(["karhutla"], date(2024, 9, 1), date(2024, 9, 3), FakeSession(FakeResp(content=RSS.encode())), 7))
|
||||
assert recs[0]["judul"] == "Karhutla Riau meluas"
|
||||
assert recs[0]["sumber"] == "ANTARA"
|
||||
assert recs[0]["tanggal_publikasi"] == "2024-09-02T15:30:00"
|
||||
|
||||
|
||||
def test_gdelt_parse(monkeypatch):
|
||||
monkeypatch.setattr("time.sleep", lambda s: None)
|
||||
js = {"articles": [{"url": "https://www.cnnindonesia.com/nasional/1", "title": "Karhutla Jambi", "seendate": "20240902T083000Z"}]}
|
||||
recs = list(gdelt.collect(["karhutla"], date(2024, 9, 1), date(2024, 9, 3), FakeSession(FakeResp(js=js)), 7))
|
||||
assert recs[0]["sumber"] == "CNN Indonesia" and recs[0]["tanggal_publikasi"] == "2024-09-02T15:30:00"
|
||||
|
||||
|
||||
def test_fetch_article():
|
||||
art = portals.fetch_article("https://x/1", FakeSession(FakeResp(text=HTML)))
|
||||
assert art["judul"] == "Kabut Asap Selimuti Pekanbaru"
|
||||
assert art["tanggal"] == "2024-09-15T10:00:00"
|
||||
assert "Pekanbaru" in art["isi"] and "Baca juga" not in art["isi"]
|
||||
|
||||
|
||||
def test_write_records_memisah_reject(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(config, "RAW_LOCAL_DIR", tmp_path / "raw")
|
||||
monkeypatch.setattr(config, "REPORT_DIR", tmp_path / "rep")
|
||||
good = build_record(judul="a", url="https://x.com/1", tanggal="2024-03-05T10:00:00", sumber="X", sumber_data="t")
|
||||
bad = build_record(judul="b", url="https://x.com/2", tanggal=None, sumber="X", sumber_data="t")
|
||||
st = write_records([good, bad], "t", "run1")
|
||||
assert st["valid"] == 1 and st["rejected"] == 1
|
||||
f = tmp_path / "raw" / "t" / "2024-03" / "t_run1.jsonl"
|
||||
assert json.loads(f.read_text().splitlines()[0])["judul"] == "a"
|
||||
|
||||
|
||||
def test_gdelt_berhenti_bila_terus_gagal(monkeypatch):
|
||||
import pytest
|
||||
monkeypatch.setattr("time.sleep", lambda s: None)
|
||||
|
||||
class Bad(FakeResp):
|
||||
status_code = 429
|
||||
text = "Please limit requests to one every 5 seconds"
|
||||
|
||||
with pytest.raises(RuntimeError, match="berturut-turut"):
|
||||
list(gdelt.collect(["karhutla"], date(2026, 10, 1), date(2026, 11, 4), FakeSession(Bad()), 7))
|
||||
|
||||
|
||||
class RoutedSession:
|
||||
"""Situs palsu: halaman pencarian, artikel normal, artikel tanpa tanggal, dan artikel 403."""
|
||||
PAGES = {
|
||||
"search": '<a href="https://www.antaranews.com/berita/111/karhutla-ok">a</a><a href="https://www.antaranews.com/berita/222/karhutla-nodate">b</a>'
|
||||
'<a href="https://www.antaranews.com/berita/333/karhutla-blocked">c</a>',
|
||||
"ok": HTML,
|
||||
"nodate": "<html><head><meta property='og:title' content='Tanpa tanggal'></head><body><p>x</p></body></html>",
|
||||
}
|
||||
|
||||
def get(self, url, **k):
|
||||
class R:
|
||||
status_code = 200
|
||||
headers = {"content-type": "text/html"}
|
||||
r = R()
|
||||
r.url = url
|
||||
if "search" in url:
|
||||
r.text = self.PAGES["search"] if "page=1" in url else ""
|
||||
elif url.endswith("/karhutla-ok"):
|
||||
r.text = self.PAGES["ok"]
|
||||
elif url.endswith("/karhutla-nodate"):
|
||||
r.text = self.PAGES["nodate"]
|
||||
else:
|
||||
import requests
|
||||
resp = requests.Response()
|
||||
resp.status_code = 403
|
||||
raise requests.HTTPError("403", response=resp)
|
||||
r.raise_for_status = lambda: None
|
||||
return r
|
||||
|
||||
|
||||
def test_portal_collect_menghitung_alasan_gugur(monkeypatch, capsys):
|
||||
monkeypatch.setattr("time.sleep", lambda s: None)
|
||||
monkeypatch.setitem(portals.PORTALS["antara"], "search", "https://www.antaranews.com/search?q={q}&page={page}")
|
||||
recs = list(portals.collect("antara", ["karhutla"], date(2024, 1, 1), date(2026, 11, 4), RoutedSession(), max_pages=2))
|
||||
out = capsys.readouterr().out
|
||||
assert len(recs) == 1 and recs[0]["sumber"] == "ANTARA"
|
||||
assert "tanggal_tidak_terbaca" in out and "HTTP 403" in out and "diterima" in out
|
||||
|
||||
|
||||
def test_debug_portal_berjalan(monkeypatch, tmp_path, capsys):
|
||||
import config
|
||||
from scripts import debug_portal
|
||||
monkeypatch.setattr(config, "REPORT_DIR", tmp_path)
|
||||
monkeypatch.setitem(portals.PORTALS["antara"], "search", "https://www.antaranews.com/search?q={q}&page={page}")
|
||||
debug_portal.debug("antara", RoutedSession())
|
||||
out = capsys.readouterr().out
|
||||
assert "tautan artikel cocok pola: 3" in out and "3 lolos filter slug" in out
|
||||
assert (tmp_path / "debug_antara_search.html").exists()
|
||||
|
||||
|
||||
def test_tanggal_format_detik():
|
||||
assert parse_date_any("2026/11/15 12:00:12") == "2026-11-15T12:00:12"
|
||||
assert parse_date_any("15/11/2026 12:00") == "2026-11-15T12:00:00"
|
||||
|
||||
|
||||
def test_extract_links_relatif_dan_absolut():
|
||||
html = '<a href="/nasional/20261114093000-20-1234567/karhutla-riau">x</a><a href="https://www.cnnindonesia.com/nasional/20261113-1-2/abc">y</a>'
|
||||
links = portals.extract_links(html, "https://www.cnnindonesia.com/search/?query=karhutla", portals.PORTALS["cnn"]["link_re"])
|
||||
assert links == ["https://www.cnnindonesia.com/nasional/20261114093000-20-1234567/karhutla-riau"]
|
||||
|
||||
|
||||
def test_slug_filter():
|
||||
assert portals.slug_relevant("https://news.detik.com/berita/d-1/bertemu-menlu-bereskan-karhutla")
|
||||
assert not portals.slug_relevant("https://news.detik.com/berita/d-2/tak-semua-konten-bisa-diblokir-komdigi")
|
||||
|
||||
|
||||
def test_isi_artikel_antara_dengan_br():
|
||||
kalimat = "Kebakaran lahan gambut di Kabupaten Sintang meluas akibat cuaca kering dan angin kencang di wilayah itu."
|
||||
html = f"""<html><head><meta property="og:title" content="Judul"></head><body>
|
||||
<div class="post-content clearfix">{kalimat}<br><br>{kalimat} Tim gabungan terus melakukan pemadaman.<br>Baca juga: lainnya yang tidak perlu ikut tersimpan<br>
|
||||
<script>var x=1;</script></div></body></html>"""
|
||||
art = portals.fetch_article("https://x/1", FakeSession(FakeResp(text=html)))
|
||||
assert "Sintang" in art["isi"] and "Baca juga" not in art["isi"] and "var x" not in art["isi"]
|
||||
|
||||
|
||||
def test_slug_api_hanya_kata_utuh():
|
||||
assert portals.slug_relevant("https://x.com/nasional/1/video-api-masih-membara")
|
||||
assert not portals.slug_relevant("https://x.com/nasional/1/rapi-dan-bersih-kota-ini")
|
||||
|
||||
|
||||
def test_query_cnn_pakai_slug_tag():
|
||||
cnn = portals.PORTALS["cnn"]
|
||||
assert portals.query_for(cnn, "kebakaran hutan dan lahan") == "kebakaran-hutan-dan-lahan"
|
||||
assert portals.query_for(portals.PORTALS["antara"], "kabut asap") == "kabut+asap"
|
||||
assert cnn["search"].format(q="karhutla", page=2) == "https://www.cnnindonesia.com/tag/karhutla?page=2"
|
||||
Loading…
x
Reference in New Issue
Block a user