58 lines
1.9 KiB
Python
Executable File
58 lines
1.9 KiB
Python
Executable File
"""Fungsi pemrosesan teks murni Python (dipakai sebagai UDF Spark dan bisa diuji tanpa Spark)."""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
|
|
from spark_jobs.lexicon import KATEGORI, PROVINSI, WILAYAH_IGNORE
|
|
|
|
_URL = re.compile(r"https?://\S+|www\.\S+")
|
|
_TAG = re.compile(r"<[^>]+>")
|
|
_NON = re.compile(r"[^a-z0-9\s]")
|
|
_WS = re.compile(r"\s+")
|
|
|
|
|
|
def normalize_text(s: str | None) -> str:
|
|
if not s:
|
|
return ""
|
|
s = _URL.sub(" ", _TAG.sub(" ", s.lower()))
|
|
return _WS.sub(" ", _NON.sub(" ", s)).strip()
|
|
|
|
|
|
def _compile(alias: str) -> re.Pattern:
|
|
return re.compile(r"\b" + re.escape(alias) + r"\b")
|
|
|
|
|
|
# (pola, provinsi) diurutkan dari alias terpanjang agar "kepulauan riau" menang atas "riau".
|
|
_PATTERNS: list[tuple[re.Pattern, str | None]] = sorted(
|
|
[(_compile(a), prov) for prov, aliases in PROVINSI.items() for a in aliases]
|
|
+ [(_compile(a), None) for a in WILAYAH_IGNORE],
|
|
key=lambda x: -len(x[0].pattern),
|
|
)
|
|
|
|
|
|
def extract_wilayah(text_norm: str | None) -> list[str]:
|
|
"""Daftar provinsi yang disebut dalam teks (sudah dinormalisasi)."""
|
|
if not text_norm:
|
|
return []
|
|
found: list[str] = []
|
|
text = text_norm
|
|
for pat, prov in _PATTERNS:
|
|
if pat.search(text):
|
|
if prov and prov not in found:
|
|
found.append(prov)
|
|
text = pat.sub(" ", text) # cegah alias lebih pendek cocok di dalam alias yang lebih panjang
|
|
return found
|
|
|
|
|
|
_KAT_PATTERNS = {k: [_compile(t) for t in terms] for k, terms in KATEGORI.items()}
|
|
|
|
|
|
def classify(judul_norm: str | None, isi_norm: str | None) -> str:
|
|
judul, isi = judul_norm or "", isi_norm or ""
|
|
best, best_score = "Lainnya", 0
|
|
for kat, pats in _KAT_PATTERNS.items(): # urutan = prioritas
|
|
score = sum(3 * len(p.findall(judul)) + len(p.findall(isi)) for p in pats)
|
|
if score > best_score:
|
|
best, best_score = kat, score
|
|
return best
|