167 lines
5.9 KiB
Python
Executable File
167 lines
5.9 KiB
Python
Executable File
"""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)}
|