Observasi (Himawari-9, GK2A), baseline (NASA POWER + baseline termal), dan rule engine (MAUT + neighbour support) berjalan sebagai Cloud Run job. Agen ADK tinggal di service asapify-agent dan hanya dipanggil untuk kelompok AWAS; ia mengambil VIIRS saat itu juga (on-demand). Service asapify-api melayani web operator dan pelanggan; setelah operator menerbitkan, pesan masuk ke inbox dan DM Telegram pelanggan provinsi itu lewat worker asapify-notify. Kode di halaman ini 💡 titik awal; bagian ⚠️ dicek di Sprint 0.
Gambar sambungannya ada di Rencana 03 (skematik B). Tabel ini untuk dipegang saat menulis kode.
| Komponen | Pemicu | Membaca | Menulis | Memanggil |
|---|---|---|---|---|
asapify-build (job) | manual, sekali | BIG KHG, data/ref/provinces.geojson, WorldCover (EE) | peat/pixels.parquet, neighbors8, neighbors_r5, power_cells | Earth Engine |
asapify-ingest-himawari (job) | Scheduler */10 20-23,0-4 | NOAA noaa-himawari9, peat/ | himawari/…/HHMM.parquet, raw/himawari/manifest/, runs | — |
asapify-ingest-gk2a (job) | Scheduler */10 20-23,0-4 | NOAA noaa-gk2a-pds, peat/ | gk2a/…/HHMM.parquet, raw/gk2a/manifest/, runs | — |
asapify-environment (job) | Scheduler 0 12 * * * | NASA POWER, himawari/, gk2a/, score/ (piksel beku) | environment/power/, environment/thermal/, environment/bias/, raw/power/ | — |
asapify-evaluate (job) | Scheduler 5-59/10 20-23,0-4 | himawari/, gk2a/, environment/, peat/, score/ 3 malam | score/…/HHMM.parquet, Firestore clusters, runs | asapify-agent: POST /verify (hanya AWAS), POST /cluster-closed |
asapify-agent (service, privat) | POST dari evaluate atau api | clusters, score/, NASA FIRMS, NASA GIBS, NOAA Himawari | crops/, raw/firms/, verifications, alerts.status (tutup), audit_log | Gemini, Telegram (grup operator) |
asapify-api (service) | request web operator dan pelanggan; webhook Telegram | score/ (grid), clusters, verifications, notification_recipients | alerts, audit_log, notification_inbox, notification_jobs | Cloud Tasks (antrean kirim), asapify-agent (verifikasi ulang) |
asapify-notify (service, privat) | Cloud Tasks (satu task per job), Scheduler sweep tiap menit | notification_jobs, notification_inbox, notification_recipients | status job, notification_inbox (fan-out lanjutan) | Telegram (DM pelanggan), FCM (push simulasi) |
/api/v1, lewat Firebase Hosting (satu origin dengan web). Agen: /verify di URL Cloud Run privat.[lon, lat]. Peta web memakai format ringkas: indeks piksel statis sekali (/operator/pixels), lalu satu huruf status per sel (S, N, W, A). Untuk 10 ribu sel ≈ 23 KB mentah / 11 KB gzip, dibanding GeoJSON ≈ 1,9 MB / 83 KB. GeoJSON titik tetap tersedia (format=geojson, default) untuk alat lain.slot = waktu scan 10 menit UTC.p{row}_{col} di grid 0,02° Sumatra + Kalimantan (1.225 × 620, asal 94,9° BT / 6,2° LU, baris 0 di utara); kelompok C-{MMDD}-{nnn}; verifikasi {cluster_id}_{slot:%Y%m%dT%H%M}SAFE, NO_OBSERVATION, WATCH, AWAS (huruf besar, persis)role = "operator"/notifications/*; tidak membuka peta atau keputusansa-jobs atau sa-api ke asapify-agent (Cloud Run IAM run.invoker)--as-of atau env AS_OF; endpoint: as_of; header respons X-Asapify-As-Of{"error": {"code": "...", "message": "..."}}. code stabil; web menulis pesannya sendiri dari code dalam bahasa operator (EN/ID). message (Bahasa Indonesia) hanya tampil bila code belum dikenal web.finding + finding_en, summary_id + summary_en) supaya layar tidak mencampur bahasa. Teks pesan peringatan (inbox dan DM Telegram) tetap Bahasa Indonesia.| Metode | Path | Auth | Fungsi |
|---|---|---|---|
asapify-api · umum (setelah /api/v1) | |||
| GET | /health, /meta | publik | cek hidup; slot terakhir per satelit, malam/siang, status replay, rentang malam arsip yang bisa dibuka (nights.first–nights.last) |
| asapify-api · operator | |||
| GET | /operator/pixels | operator | indeks piksel gambut statis: version, asal grid, langkah 0,02°, baris, kolom, dan kode provinsi per sel. Urutannya menjadi indeks sel di semua respons ringkas. Diunduh sekali; kirim ETag + Cache-Control |
| GET | /operator/grid?as_of=, &format=compact | operator | status semua piksel gambut untuk slot malam terakhir ≤ as_of. Default GeoJSON titik (status, utility, n_sat, cluster_id, province). format=compact (dipakai web): string status satu huruf per sel, utility base64 Uint8 (round(U × 250), 255 = null), dan kelompok aktif → indeks sel |
| GET | /operator/grid/night?night= | operator | 54 string status (format ringkas) untuk satu malam, 20.00–04.50 WIB, plus kelompok yang AWAS di salah satu slot malam itu → indeks sel. Satu permintaan untuk pemutar slot dan malam arsip. Slot setelah as_of atau tanpa data = null |
| GET | /operator/nights?month= | operator | satu baris per malam arsip dalam bulan itu: night, has_data, awas_clusters. Mengisi kalender malam (tanggal pudar = tanpa data, titik = ada kelompok AWAS) |
| GET | /operator/basemaps?as_of= | operator | pilihan peta dasar raster dari BE, mis. citra VIIRS true colour NASA GIBS tanggal as_of (template tile, ukuran tile, zoom maksimum, atribusi, label ID/EN). Array kosong = hanya peta jalan dan polos |
| GET | /operator/clusters?state=active, ?night= | operator | daftar kelompok AWAS + hasil verifikasi terakhir + keputusan. Dengan night=YYYY-MM-DD (malam arsip): kelompok yang AWAS di salah satu slot malam itu, aktif maupun ditutup (first_awas_at ≤ akhir malam dan last_awas_at ≥ awal malam); state diabaikan |
| GET | /operator/clusters/{id} | operator | deret utility 3 malam, atribut MAUT slot pemicu beserta angka terukurnya (attribute_details), grid tetangga, verifikasi + jejak tool, signed URL citra dengan bbox crop, dan suhu kecerahan per sel di balik citra termal (images[].thermal) |
| POST | /operator/clusters/{id}/verify | operator | minta verifikasi ulang; diteruskan ke agen (hormati 6 jam kecuali force=true) |
| POST | /operator/clusters/{id}/decision | operator | publish (teks pesan; keputusan, audit dan alert tersimpan dulu, lalu inbox dan antrean ditulis per pelanggan provinsi itu, 50 per batch; jumlah pelanggan tidak pernah menggagalkan keputusan) / reject (alasan wajib) |
| GET | /operator/alerts?status= | operator | peringatan terbit + ringkasan antrean |
| POST | /operator/alerts/{id}/close | operator | tutup lebih awal oleh operator: inbox berlabel SELESAI, job yang belum terkirim batal (otomatis lewat agent /cluster-closed saat kelompok ditutup) |
| GET | /operator/alerts/{id}/deliveries | operator | status kirim per kanal per pelanggan (pending, sending, accepted, failed, unknown, blocked, cancelled, simulated) + waktu konfirmasi penerima. accepted = diterima penyedia, belum berarti dibaca ✅ |
| asapify-api · pelanggan (akun Google dengan email terverifikasi, tanpa role) | |||
| GET | /notifications/settings | pengguna | preferensi (provinsi, kanal, persetujuan, simulasi), Telegram tertaut / perangkat push terdaftar, daftar kanal beserta status aktif, mode dry_run / live ✅ |
| PUT | /notifications/preferences | pengguna | body {provinces, channels, consent, exercises}; consent = true wajib minimal satu provinsi; berhenti berlangganan = consent = false ✅ |
| POST | /notifications/device, DELETE | pengguna | daftar / lepas satu token push (FCM, termasuk Web Push) per akun ✅ |
| POST | /notifications/telegram-link | pengguna | deep link t.me/<bot>?start=<kode> sekali pakai, berlaku 10 menit; hanya hash kode yang disimpan ✅ |
| GET | /notifications/inbox | pengguna | 50 pesan terakhir milik akun: teks, provinsi, purpose (emergency / exercise), published_at, expires_at, acknowledged_at ✅ |
| POST | /notifications/inbox/{id}/ack | pengguna | konfirmasi diterima; idempoten; ID milik akun lain → 404. Membuka tautan saja tidak dihitung konfirmasi ✅ |
| POST | /notifications/telegram-webhook | secret Telegram | dipanggil Telegram, bukan browser. Header X-Telegram-Bot-Api-Secret-Token; hanya menerima /start <kode> dari chat privat untuk menautkan akun; tidak membalas ✅ |
| bucket publik · file statis untuk lapisan peta (bukan endpoint) | |||
| FILE | layers/peat_pixels.geojson | publik | batas gambut yang diproses (KHG ∩ 15 provinsi − area terbangun), disederhanakan; ditulis asapify-build |
| FILE | layers/provinces.geojson | publik | 15 provinsi Sumatra + Kalimantan (kode BPS, nama), disederhanakan ±90 KB (±30 KB gzip); dipakai garis provinsi dan sorotan provinsi terpilih. geoBoundaries IDN ADM1, ODbL |
| asapify-agent · internal (URL Cloud Run privat) | |||
| POST | /verify | OIDC sa-jobs / sa-api | body {"cluster_id", "trigger_slot", "force": false}; jalankan agen, simpan verifications, kirim ke grup operator. Respons 202 + verification_id |
| POST | /cluster-closed | OIDC sa-jobs | body {"cluster_id"}; kode deterministik (tanpa Gemini): bila ada alert terbit untuk kelompok itu, set alerts.status = closed, beri label SELESAI di inbox, batalkan job yang belum terkirim |
| asapify-notify · internal (URL Cloud Run privat, image yang sama dengan asapify-api) | |||
| POST | /_internal/notifications/dispatch | OIDC sa-task | body {"job_id"} dari Cloud Tasks: klaim satu job, cek ulang persetujuan, konfirmasi dan masa berlaku, kirim, simpan status. Timeout = unknown, tidak dikirim ulang otomatis ✅ |
| POST | /_internal/notifications/sweep | OIDC sa-task | Cloud Scheduler tiap menit: lanjutkan fan-out yang terputus (alerts.fanout = pending), antrekan ulang job pending, tandai sending > 5 menit sebagai unknown ✅ |
Skema lengkap tiap respons (field, tipe, wajib, contoh JSON) ada di tab Kontrak API aplikasi web (/kontrak-api, publik, EN/ID). Contoh di sana diambil dari data mock yang sama dengan yang tampil di layar.
Data fiktif.
{
"id": "C-0924-002",
"state": "active",
"province": "62",
"rep_pixel": "p420_950",
"centroid": [113.92, -2.21],
"pixels": ["p420_950", "p420_951", "p421_950", "p419_951"],
"trigger_slot": "2023-09-24T15:10:00Z",
"utility_score": 0.73,
"neighbour_support": 0.375,
"attributes": {"u_H": 1.0, "u_G": 1.0, "u_LST": 0.5,
"u_SAT": 0.0, "u_T": 0.67},
"attribute_details": {
"u_H": {"value": 18.6, "unit": "K", "scale": [6, 14],
"parts": [{"key": "b07", "value": 318.2, "unit": "K", "abs": true},
{"key": "bg_dt", "value": 4.1, "unit": "K"}]},
"u_T": {"value": 2, "unit": "malam", "scale": [0, 3], "parts": []}
},
"n_sat": 2,
"series": [{"slot": "2023-09-23T15:00:00Z", "U": 0.38, "status": "WATCH"},
{"slot": "2023-09-24T15:10:00Z", "U": 0.73, "status": "AWAS"}],
"neighbours": [{"dir": "n", "state": "anomaly", "u0": 0.62}, …],
"verification": {
"result": "strong_evidence",
"viirs_within_2km_48h": 1,
"tool_calls": 5,
"at": "2023-09-24T15:14:00Z",
"images": [{"source": "himawari_image", "url": "https://…",
"bbox": [113.72, -2.41, 114.12, -2.01],
"thermal": {"cols": 20, "rows": 20, "bands": […]}}, …]
},
"decision": null
}
{ "pixels_version": "2023-09-v1",
"slot": "2023-09-24T15:10:00Z",
"n_sat": 2,
"status": "SSSWSNNSAAS…", # satu huruf per sel, urutan /operator/pixels
"utility": "Mjw8RlB…", # base64 Uint8: round(U × 250), 255 = null
"clusters": {"C-0924-002": [1204, 1205, 1287, 1288]} }
{
"action": "publish",
"caption_id": "AWAS · Kalimantan Tengah …",
"reason": null
}
{ "action": "publish", "by": "operator@contoh.id",
"at": "2023-09-24T15:30:00Z", "reason": null,
"alert_id": "A-0924-001", "telegram": null,
"notifications": {"state": "outbox_saved",
"recipients": 2, "jobs": 4},
"queue": {"state": "accepted", "count": 4} }
{ "error": { "code": "ALREADY_DECIDED",
"message": "Kelompok ini sudah diterbitkan oleh operator lain." } }
| Path | Isi |
|---|---|
peat/pixels.parquet | pixel_id, row, col, lat, lon, peat_frac, built_frac, kode_khg, province (11–19, 21, 61–65), cell_id |
peat/neighbors8.parquet, neighbors_r5.parquet, power_cells.parquet | pixel_id, neighbor_ids[]; cell_id, lat, lon, n_pixels |
himawari/YYYY/MM/DD/HHMM.parquet | pixel_id, mir (B07), win (B14), cloud |
gk2a/YYYY/MM/DD/HHMM.parquet | pixel_id, mir (SW038), win (IR105), cloud |
environment/power/YYYYMMDD.parquet | cell_id, hour_utc, ts_base, t2m_base, n_days |
environment/thermal/{sat}/YYYYMMDD.parquet | pixel_id, hour_utc, median, mad, n_obs, frozen |
environment/bias/YYYYMMDD.parquet | pixel_id, hour_utc, b_lst |
score/YYYY/MM/DD/HHMM.parquet | pixel_id, timestamp, himawari_score, gk2a_score, z_rel_h, z_rel_g, lst, sat, d_lst, d_sat, u_lst, u_sat, u_t, utility_score, neighbour_support, n_sat, status, cluster_id |
crops/{pixel_id}/{timestamp}_{source}.png | citra VIIRS dan Himawari untuk agen dan UI; PNG termal memakai skala warna tetap kanal panas 270–340 K (sama dengan legenda web) |
crops/{pixel_id}/{timestamp}_thermal.json | suhu kecerahan per sel 0,02° di balik crop termal: bbox, 20 × 20 sel, kanal B07/B14 (Himawari) dan SW038/IR105 (GK2A), kelvin 1 desimal, null = berawan. Disajikan sebagai images[].thermal ⚠️ |
raw/{source}/… | manifest file sumber per slot (JSON), cache POWER per sel, cache FIRMS per kotak |
layers/*.geojson (bucket publik) | peat_pixels.geojson dan provinces.geojson untuk lapisan peta web; dibaca browser langsung (CORS) |
| Koleksi | Isi |
|---|---|
clusters | pixels, rep_pixel, centroid, province, utility_max, neighbour_support, first_awas_at, last_awas_at, last_verified_at, state (active/closed) |
verifications | output agen schema-locked, jejak tool, model, validator_ok |
alerts | cluster_id, caption, published_by/at, status (active/closed), purpose (emergency/exercise), expires_at, fanout (pending/done), notifications {state, recipients, jobs} |
notification_recipients | per pelanggan (ID = hash UID): provinsi, kanal, consent, exercises, Telegram chat_id dan token push (tidak pernah dikirim ke browser) |
notification_inbox | satu dokumen per alert × pelanggan: teks, provinsi, purpose, expires_at (1 jam), acknowledged_at |
notification_jobs | outbox per kanal: status, error, attempts, not_before, provider_id; ID deterministik, hanya di-create |
notification_devices, notification_telegram_chats | pemilik token push / chat Telegram, agar satu perangkat atau chat tidak tertaut ke dua akun |
runs | log tiap eksekusi job: slot, n_sat, jumlah per status, latensi, file hilang |
audit_log | setiap aksi operator, panggilan agen, dan pesan bot |
Semua job, backtest, dan UI memakai konstanta yang sama dari jobs/lib/region.py.
from pyresample import create_area_def # lon_min, lat_min, lon_max, lat_max (WGS84) MONITOR_BBOX = (94.9, -6.2, 119.4, 6.2) # Sumatra + Kalimantan (asal grid 94,9 BT / 6,2 LU) BACKTEST_BBOX = (113.5, -2.6, 114.3, -1.9) # sub-area Kalteng (utama) BACKTEST_BBOX_SUMSEL = (105.2, -3.7, 106.0, -3.0) # OKI, Sumsel (direncanakan) GRID_DEG = 0.02 # 1.225 kolom × 620 baris NIGHT_UTC = range(13, 21) # 20.00–04.00 WIB (Sumatra juga WIB) PROVINCES = { # kode BPS "11": "Aceh", "12": "Sumatera Utara", "13": "Sumatera Barat", "14": "Riau", "15": "Jambi", "16": "Sumatera Selatan", "17": "Bengkulu", "18": "Lampung", "19": "Kepulauan Bangka Belitung", "21": "Kepulauan Riau", "61": "Kalimantan Barat", "62": "Kalimantan Tengah", "63": "Kalimantan Selatan", "64": "Kalimantan Timur", "65": "Kalimantan Utara", } AREA = create_area_def("sumkal_002", "EPSG:4326", area_extent=MONITOR_BBOX, resolution=GRID_DEG) def pixel_id(row: int, col: int) -> str: return f"p{row}_{col}" # baris 0 = utara
MONITOR_BBOX ikut mencakup Semenanjung Malaysia, Singapura, Sarawak, Sabah, Brunei, ujung barat Jawa, dan sebagian pantai Sulawesi Barat.province per piksel juga menentukan pelanggan yang menerima peringatan (pelanggan memilih provinsi).import geopandas as gpd, numpy as np, requests
from rasterio import features, transform
from jobs.lib.region import MONITOR_BBOX, GRID_DEG, AREA, pixel_id
KHG = ("https://kspservices.big.go.id/satupeta/rest/services/PUBLIK/"
"SUMBER_DAYA_ALAM_DAN_LINGKUNGAN/MapServer/37/query")
def fetch_khg(bbox):
feats, off = [], 0
while True: # maks 1.000 fitur/request
r = requests.get(KHG, timeout=120, params={
"where": "1=1", "outFields": "kode_khg", "f": "geojson",
"geometry": ",".join(map(str, bbox)),
"geometryType": "esriGeometryEnvelope", "inSR": 4326,
"outSR": 4326, "resultOffset": off, "resultRecordCount": 1000})
page = r.json()["features"]; feats += page
if len(page) < 1000: return gpd.GeoDataFrame.from_features(feats, crs=4326)
off += 1000
def fraction(gdf, sub=10): # fraksi luas per sel 0,02°
h, w = AREA.shape
t = transform.from_bounds(*MONITOR_BBOX, w * sub, h * sub)
fine = features.rasterize(gdf.geometry, (h * sub, w * sub), transform=t)
return fine.reshape(h, sub, w, sub).mean(axis=(1, 3))
khg = fetch_khg(MONITOR_BBOX).make_valid()
prov = gpd.read_file("data/ref/provinces.geojson") # 15 provinsi, Runbook S0-8
peat_frac = fraction(khg.clip(prov))
built_frac = np.load("data/ref/built_frac_002.npy")
keep = (peat_frac >= 0.5) & (built_frac < 0.2)
rows, cols = np.nonzero(keep)
lon, lat = AREA.get_lonlats()
df = gpd.GeoDataFrame({
"pixel_id": [pixel_id(r, c) for r, c in zip(rows, cols)],
"row": rows, "col": cols,
"lat": lat[rows, cols], "lon": lon[rows, cols],
"peat_frac": peat_frac[rows, cols], "built_frac": built_frac[rows, cols],
}, geometry=gpd.points_from_xy(lon[rows, cols], lat[rows, cols]), crs=4326)
df = (df.sjoin(prov[["code", "geometry"]]).drop(columns="index_right")
.rename(columns={"code": "province"}))
df = df.sjoin(khg[["kode_khg", "geometry"]], how="left")
df.drop(columns=["geometry", "index_right"]).to_parquet(
f"gs://{DATA_BUCKET}/peat/pixels.parquet")
import ee, numpy as np, requests, io
from jobs.lib.region import MONITOR_BBOX, GRID_DEG
ee.Initialize(project=PROJECT_ID)
T = [GRID_DEG, 0, MONITOR_BBOX[0], 0, -GRID_DEG, MONITOR_BBOX[3]]
built = (ee.ImageCollection("ESA/WorldCover/v200").first().eq(50)
.reduceResolution(ee.Reducer.mean(), maxPixels=65535)
.reproject(crs="EPSG:4326", crsTransform=T))
url = built.getDownloadURL({"region": ee.Geometry.Rectangle(list(MONITOR_BBOX)),
"crs": "EPSG:4326", "format": "NPY", "crsTransform": T})
arr = np.load(io.BytesIO(requests.get(url).content))
np.save("data/ref/built_frac_002.npy", arr["Map"].astype("float32"))
peat = pd.read_parquet(f"gs://{DATA_BUCKET}/peat/pixels.parquet")
idx = {(r, c): p for p, r, c in zip(peat.pixel_id, peat.row, peat.col)}
def around(r, c, k): # k=1 → 8 arah; k=5 → radius 5 sel
return [idx[(r+i, c+j)] for i in range(-k, k+1) for j in range(-k, k+1)
if (i or j) and (r+i, c+j) in idx and (k == 1 or i*i + j*j <= k*k)]
for k, name in ((1, "neighbors8"), (5, "neighbors_r5")):
pd.DataFrame({"pixel_id": peat.pixel_id,
"neighbor_ids": [around(r, c, k) for r, c in zip(peat.row, peat.col)]}
).to_parquet(f"gs://{DATA_BUCKET}/peat/{name}.parquet")
# sel NASA POWER (GEOS-IT 0,5° × 0,625°)
peat["cell_lat"] = (peat.lat / 0.5).round() * 0.5
peat["cell_lon"] = (peat.lon / 0.625).round() * 0.625
peat["cell_id"] = [f"c{a:+.1f}_{o:.3f}" for a, o in zip(peat.cell_lat, peat.cell_lon)]
cells = (peat.groupby("cell_id")
.agg(lat=("cell_lat", "first"), lon=("cell_lon", "first"),
n_pixels=("pixel_id", "size")).reset_index())
Kedua ingest menulis kolom yang sama (pixel_id, mir, win, cloud), jadi rule engine tidak perlu tahu satelit mana yang dibaca. Hanya slot malam (13.00–20.50 UTC) yang diproses.
import os, s3fs
from satpy import Scene
from jobs.lib.region import AREA
fs = s3fs.S3FileSystem(anon=True)
SEGMENTS = ("S0510", "S0610") # ⚠️ dicek di S0-7
def list_scan(slot): # slot: datetime UTC, kelipatan 10 menit
d = f"noaa-himawari9/AHI-L1b-FLDK/{slot:%Y/%m/%d/%H%M}"
return [f for f in fs.ls(d)
if any(f"_{b}_" in f for b in ("B07", "B14"))
and any(s in f for s in SEGMENTS)] # 4 file
def read_scan(files, tmp):
local = []
for f in files:
p = os.path.join(tmp, os.path.basename(f)); fs.get(f, p); local.append(p)
scn = Scene(reader="ahi_hsd", filenames=local) # .DAT.bz2 ⚠️
scn.load(["B07", "B14"], calibration="brightness_temperature")
g = scn.resample(AREA, resampler="nearest", radius_of_influence=5000)
return g["B07"].values, g["B14"].values # mir, win (445 × 545, K)
import os, s3fs
from satpy import Scene
from jobs.lib.region import AREA
fs = s3fs.S3FileSystem(anon=True)
CHANNELS = ("sw038", "ir105")
def list_scan(slot): # arsip mulai 16 Feb 2023
d = f"noaa-gk2a-pds/AMI/L1B/FD/{slot:%Y%m/%d/%H}"
return [f"{d}/gk2a_ami_le1b_{ch}_fd020ge_{slot:%Y%m%d%H%M}.nc"
for ch in CHANNELS] # 2 file × ~30 MB
def read_scan(files, tmp):
local = []
for f in files:
p = os.path.join(tmp, os.path.basename(f)); fs.get(f, p); local.append(p)
scn = Scene(reader="ami_l1b", filenames=local)
scn.load(["SW038", "IR105"], calibration="brightness_temperature")
g = scn.resample(AREA, resampler="nearest", radius_of_influence=5000)
for p in local: os.remove(p) # jangan simpan full disk
return g["SW038"].values, g["IR105"].values
CLOUD_K = 270.0 # kanal jendela < 270 K = awan def to_features(mir, win, peat): r, c = peat.row.values, peat.col.values df = pd.DataFrame({"pixel_id": peat.pixel_id.values, "mir": mir[r, c], "win": win[r, c]}) df["cloud"] = (df.win < CLOUD_K) | df.win.isna() return df # → {sat}/YYYY/MM/DD/HHMM.parquet
NASA POWER hourly terlambat ~1,5 hari dan kasar (0,5° × 0,625°), jadi dipakai sebagai median 30 hari per jam, bukan nilai malam ini. Tidak ada endpoint wilayah untuk data jam-an: satu request per sel.
URL = "https://power.larc.nasa.gov/api/temporal/hourly/point"
def fetch_cell(lat, lon, start, end):
r = httpx.get(URL, timeout=120, params={
"parameters": "TS,T2M", "community": "RE",
"latitude": lat, "longitude": lon,
"start": f"{start:%Y%m%d}", "end": f"{end:%Y%m%d}",
"format": "JSON", "time-standard": "UTC"})
p = r.json()["properties"]["parameter"]
df = pd.DataFrame({"ts": p["TS"], "t2m": p["T2M"]}).replace(-999.0, np.nan)
df.index = pd.to_datetime(df.index, format="%Y%m%d%H", utc=True)
return df + 273.15 # °C → K
def power_baseline(raw, as_of, days=30): # raw: cell_id, time, ts, t2m
w = raw[(raw.time > as_of - pd.Timedelta(days=days)) & (raw.time <= as_of)]
w = w[w.time.dt.hour.isin(range(13, 21))]
g = w.assign(hour_utc=w.time.dt.hour).groupby(["cell_id", "hour_utc"])
return pd.DataFrame({"ts_base": g.ts.median(), "t2m_base": g.t2m.median(),
"n_days": g.ts.count()}).reset_index()
def thermal_baseline(feats, as_of, nights=30, frozen_ids=(), prev=None):
# feats: pixel_id, slot, mir, cloud dari satu satelit, 30 malam ≤ as_of
f = feats[~feats.cloud].assign(hour_utc=feats.slot.dt.hour)
g = f.groupby(["pixel_id", "hour_utc"]).mir
base = pd.DataFrame({"median": g.median(),
"mad": g.apply(lambda x: (x - x.median()).abs().median()),
"n_obs": g.size()}).reset_index()
base["frozen"] = base.pixel_id.isin(frozen_ids)
if prev is not None: # piksel WATCH/AWAS pakai baris lama
base = pd.concat([base[~base.frozen],
prev[prev.pixel_id.isin(frozen_ids)].assign(frozen=True)])
return base
def lst_bias(win_max, power, cells):
# b_LST = median 30 malam dari (win_max − ts_base) per piksel per jam
d = (win_max.merge(cells, on="pixel_id")
.merge(power, on=["cell_id", "hour_utc"]))
d["x"] = d.win_max - d.ts_base
return d.groupby(["pixel_id", "hour_utc"]).x.median().rename("b_lst")
Angka persis Rencana 05. Ubah hanya di W, RAMP, dan T, lalu catat di WORKLOG bagian 7.
import numpy as np
W = {"H": .25, "G": .25, "LST": .10, "SAT": .05, "T": .15, "N": .20}
RAMP = {"H": (2.0, 4.0), "G": (2.0, 4.0), "LST": (1.0, 4.0), "SAT": (0.0, 3.0)}
def ramp(x, a, b):
return np.clip((x - a) / (b - a), 0.0, 1.0) # NaN tetap NaN
def attributes(zrel_h, zrel_g, d_lst, d_sat, k_nights):
return {"H": ramp(zrel_h, *RAMP["H"]), "G": ramp(zrel_g, *RAMP["G"]),
"LST": ramp(d_lst, *RAMP["LST"]), "SAT": ramp(d_sat, *RAMP["SAT"]),
"T": np.minimum(k_nights / 3.0, 1.0)}
def weighted(u, keys): # bobot dinormalisasi atas atribut ada
num = sum(np.where(np.isnan(u[k]), 0, u[k]) * W[k] for k in keys)
den = sum(np.where(np.isnan(u[k]), 0, W[k]) for k in keys)
return np.where(den > 0, num / np.where(den > 0, den, 1), np.nan)
def u0(u):
return weighted(u, ["H", "G", "LST", "SAT", "T"])
def utility(u, u_n):
return weighted({**u, "N": u_n}, ["H", "G", "LST", "SAT", "T", "N"])
def support(u0: pd.Series, nbr8: pd.DataFrame) -> pd.Series:
# u0: index pixel_id; nbr8: pixel_id, neighbor_ids[]
def one(ids):
v = u0.reindex(ids).dropna() # hanya tetangga teramati
return float((v >= 0.5).mean()) if len(v) else 0.0
return pd.Series(nbr8.neighbor_ids.map(one).values, index=nbr8.pixel_id)
T = {"awas_u": 0.65, "awas_n": 0.25, "watch_u": 0.30}
def classify(U, u_n, agree, n_sat):
return np.select(
[n_sat == 0,
(U >= T["awas_u"]) & (u_n >= T["awas_n"]) & agree,
U >= T["watch_u"]],
["NO_OBSERVATION", "AWAS", "WATCH"], default="SAFE")
# agree = u_H ≥ 0,5 dan u_G ≥ 0,5, masing-masing ≥ 1 slot dalam 60 menit
jobs/evaluate.py: baca fitur slot → anomaly.zscore per satelit → ΔLST, ΔSAT → maut.attributes → u0 → neighbours.support → utility → status.classify → tulis score/ → cluster.label → POST /verify untuk kelompok baru.✅ Built-in loop ADK, dipanggil per kelompok AWAS. Output lewat save_verification yang memvalidasi skema; tidak ada field status atau level.
from google.adk.agents import Agent
INSTRUCTION = """
You verify AWAS thermal anomalies on Indonesian peatland.
The rule engine has already identified the coordinate as AWAS.
Your task is verification, not detection.
1. Read the candidate context (get_pixel_context).
2. Retrieve the latest VIIRS detections around the coordinate
(get_latest_viirs).
3. Retrieve the latest VIIRS true-colour image (fetch_viirs_image)
and a Himawari image of the same area (fetch_himawari_image).
4. Look for visible smoke or other visual evidence consistent
with smouldering or fire activity near the marker.
5. result = strong_evidence if smoke is visible within 5 km, or
get_latest_viirs reports within_2km > 0. Otherwise inconclusive.
Absence of visible smoke is never a negative.
6. Never change the rule-engine status. Every number in your
summary must come from a tool result.
7. Finish with save_verification.
"""
verifier = Agent(
name="asapify_verifier",
model=os.environ["GEMINI_MODEL"],
instruction=INSTRUCTION,
tools=[get_pixel_context, get_latest_viirs, fetch_viirs_image,
fetch_himawari_image, save_verification],
)
class Evidence(BaseModel):
source: Literal["rule_engine", "viirs_firms",
"viirs_image", "himawari_image"]
finding: str = Field(max_length=200) # Bahasa Indonesia
finding_en: str = Field(max_length=200) # temuan yang sama untuk UI bahasa Inggris
observed_at: str | None = None
age_h: float | None = None
class Verification(BaseModel):
model_config = ConfigDict(extra="forbid")
cluster_id: str
pixel_id: str
result: Literal["strong_evidence", "inconclusive"]
smoke_visible: bool | None
viirs_within_2km_48h: int = Field(ge=0)
evidence: list[Evidence] = Field(min_length=1)
summary_id: str = Field(max_length=500)
summary_en: str = Field(max_length=500)
# tidak ada field status atau level
MAX_TOOL_CALLS = 8
def save_verification(result: dict) -> dict:
"""Validasi skema + aturan:
- viirs_within_2km_48h harus sama dengan hasil get_latest_viirs
- viirs_within_2km_48h > 0 → result wajib strong_evidence
- setiap angka di summary_* ada di hasil tool
Kembalikan {"ok": true} atau {"ok": false, "errors": [...]}"""
FIRMS = "https://firms.modaps.eosdis.nasa.gov/api/area/csv/{k}/{src}/{w},{s},{e},{n}/{days}"
SATS = ("VIIRS_SNPP", "VIIRS_NOAA20", "VIIRS_NOAA21")
def get_latest_viirs(lat: float, lon: float, as_of: str,
radius_km: float = 10, hours: int = 48) -> dict:
t = parse_utc(as_of); d = radius_km / 111
recent = (now_utc() - t).days <= 7 # NRT; selain itu arsip SP
rows = []
for sat in SATS:
src = f"{sat}_NRT" if recent else f"{sat}_SP"
url = FIRMS.format(k=MAP_KEY, src=src, w=lon-d, s=lat-d, e=lon+d, n=lat+d, days=2)
if not recent:
url += f"/{t - timedelta(days=1):%Y-%m-%d}" # ⚠️ arti tanggal: S0-6
try: rows.append(read_csv(cached_get(url)).assign(src=src))
except SourceUnavailable: continue # mis. NOAA21 SP belum ada
df = pd.concat(rows)
df["time_utc"] = to_utc(df.acq_date, df.acq_time)
df = df[(df.time_utc > t - timedelta(hours=hours)) & (df.time_utc <= t)]
df["distance_km"] = haversine(lat, lon, df.latitude, df.longitude)
df = df[df.distance_km <= radius_km].sort_values("distance_km")
return {"detections": df[["src", "time_utc", "daynight", "confidence",
"frp", "distance_km"]].to_dict("records"),
"within_2km": int((df.distance_km <= 2).sum())}
GIBS = "https://gibs.earthdata.nasa.gov/wms/epsg4326/best/wms.cgi"
LAYERS = [f"{s}_CorrectedReflectance_TrueColor"
for s in ("VIIRS_NOAA21", "VIIRS_NOAA20", "VIIRS_SNPP")]
def fetch_viirs_image(lat: float, lon: float, as_of: str,
half_deg: float = 0.2) -> dict:
t = parse_utc(as_of)
for back in range(0, 4): # tanggal WIB as_of, mundur ≤ 3 hari
day = (t + timedelta(hours=7)).date() - timedelta(days=back)
for layer in LAYERS:
r = httpx.get(GIBS, timeout=60, params={
"SERVICE": "WMS", "REQUEST": "GetMap", "VERSION": "1.3.0",
"LAYERS": layer, "CRS": "EPSG:4326",
"BBOX": f"{lat-half_deg},{lon-half_deg},{lat+half_deg},{lon+half_deg}",
"WIDTH": 512, "HEIGHT": 512, "FORMAT": "image/jpeg",
"TIME": f"{day:%Y-%m-%d}"})
img = Image.open(io.BytesIO(r.content))
if np.asarray(img).std() < 3: continue # kosong / tanpa data
png = draw_marker(img, radius_km=5) # titik + lingkaran 5 km
path = save_crop(png, pixel_id, t, "viirs")
return {"path": path, "signed_url": sign(path, hours=1),
"layer": layer, "date": str(day),
"age_h": hours_since(day, local_time="13:30", tz="+07:00", now=t)}
return {"none": True, "reason": "tidak ada citra 3 hari terakhir"}
HTTP langsung ke Bot API (httpx), tanpa framework bot. asapify-agent mengirim ringkasan verifikasi ke grup operator. Peringatan yang diterbitkan tidak lagi dikirim ke grup provinsi: asapify-api menulis inbox per pelanggan yang memilih provinsi itu, lalu worker asapify-notify mengirim DM Telegram teks (keputusan tim 9 Okt, kode di ktp-asapify-be).
TG = f"https://api.telegram.org/bot{TOKEN}"
r = client.post(f"{TG}/sendMessage", json={
"chat_id": profile["telegram_chat_id"],
"text": text_message(inbox), # teks polos, HTML dibuang
"link_preview_options": {"is_disabled": True},
"reply_markup": {"inline_keyboard": [[{
"text": "Buka & konfirmasi diterima",
"url": f"{ORIGIN}/notifikasi?open={inbox['id']}"}]]}})
# ok + message_id → accepted (bukan "dibaca")
# 4xx → failed
# timeout / 5xx → unknown, tidak dikirim ulang otomatis
# 1. web: POST /notifications/telegram-link # → t.me/<bot>?start=<kode> (10 menit, sekali pakai) # 2. pelanggan menekan Start di bot # 3. Telegram → POST /notifications/telegram-webhook # header secret token; hanya chat privat # 4. API menyimpan chat_id di profil pelanggan curl -s "https://api.telegram.org/bot$TOKEN/setWebhook" \ -d url="https://<HOSTING>/api/v1/notifications/telegram-webhook" \ -d secret_token="$WEBHOOK_SECRET" \ -d allowed_updates='["message"]'
sendPhoto dengan chat_id yang dicatat sekali.AS_OF dibulatkan ke bawah ke kelipatan 10 menit; proses slot itu + slot malam yang belum ada dalam 60 menit terakhir. Di luar 13.00–20.50 UTC: selesai tanpa aksi.list_scan(slot); bila file belum lengkap, catat di runs (pending) dan selesai. Siklus berikutnya mencoba lagi.read_scan → grid 0,02° → to_features (hanya piksel gambut).{sat}/YYYY/MM/DD/HHMM.parquet (idempoten: tulis ulang) dan manifest file sumber di raw/{sat}/manifest/.LastModified file) di runs.n_sat = 1). Lewati slot yang sudah ada di runs.environment/.score/.cluster.label), perbarui clusters, tutup kelompok tanpa AWAS 3 malam valid lalu POST $AGENT_URL/cluster-closed agar alert yang pernah diterbitkan ditandai SELESAI.POST $AGENT_URL/verify dengan token OIDC.peat/power_cells.parquet: minta hari yang belum ada di raw/power/{cell_id}.parquet (jeda 0,2 detik antar request).power_baseline → environment/power/YYYYMMDD.parquet.thermal_baseline per satelit dari 30 malam himawari/ dan gk2a/; piksel WATCH/AWAS dibekukan.lst_bias → environment/bias/YYYYMMDD.parquet.build_built_frac (Earth Engine WorldCover).build_peat_mask (KHG BIG + provinsi + built_frac).build_neighbors (8 arah, radius 5) dan build_power_cells.Backfill backtest memakai image dan kode ingest yang sama: python -m jobs.backfill --sat … --start … --end … --step 10|20 --night-only, dijalankan sebagai Cloud Run job 8 task.
asapify/ ├─ WORKLOG.md, Dockerfile, .gcloudignore, requirements.lock ├─ infra/ env.sh, set_role.py, lifecycle.json ├─ shared/ telegram.py, auth.py, storage.py # dipakai agent dan api ├─ agent/ # Cloud Run service asapify-agent │ ├─ main.py (POST /verify), agent.py, schema.py, validator.py, run.py, evaluate.py │ ├─ tools/ context.py, viirs.py, viirs_image.py, himawari_image.py │ └─ tests/ test_viirs.py, test_viirs_image.py, test_validator.py ├─ api/ # Cloud Run service asapify-api │ ├─ main.py │ └─ routers/ public.py, operator.py ├─ jobs/ # Cloud Run jobs, satu image │ ├─ ingest.py (--sat himawari|gk2a), evaluate.py, environment.py # terjadwal │ ├─ build_all.py, build_built_frac.py, build_peat_mask.py, │ │ build_neighbors.py, build_power_cells.py # sekali │ ├─ backfill.py, replay.py, calibrate.py # backtest │ ├─ lib/ region.py, himawari.py, gk2a.py, features.py, power.py, baseline.py, │ │ anomaly.py, maut.py, neighbours.py, status.py, cluster.py │ └─ tests/ test_features.py, test_himawari.py, test_gk2a.py, test_power.py, │ test_baseline.py, test_maut.py, test_status.py, test_cluster.py ├─ notebooks/ backtest.ipynb # lead time: VIIRS pertama − AWAS pertama ├─ scripts/ e2e.sh ├─ data/ref/ # KHG, provinsi, built_frac (tanpa rahasia) ├─ data/local/ # mentah, tidak di-commit ├─ docs/ # bukti selesai: png, csv, log └─ (web di repo ktp-asapify-fe: React 19 + Vite + MapLibre 6)
Rancangan monorepo. Yang sudah dibangun ada di repo tim ktp-asapify-be: asapify_api/ (API operator + Notification Engine), gcp/ (skrip deploy), tools/ (publish snapshot, set operator); pipeline dan agen masih eksperimen.
| Kejadian | Perilaku |
|---|---|
| Scan satu satelit belum tersedia | Ingest selesai tanpa aksi; evaluate menunggu sampai 40 menit, lalu jalan dengan satu satelit (n_sat = 1, AWAS tidak mungkin). |
| Kedua satelit hilang atau rusak | Semua piksel NO_OBSERVATION untuk slot itu; tercatat di runs. |
| NASA POWER gagal / terlambat | Environment memakai baseline POWER terakhir yang ada (maks 3 hari); lebih lama → u_LST dan u_SAT dikeluarkan (NaN) dan bobot dinormalisasi. |
| FIRMS atau GIBS gagal | Tool mengembalikan galat; agen melanjutkan dengan bukti yang ada dan hasilnya inconclusive dengan catatan sumber yang gagal. |
| Gemini gagal atau batas tool tercapai | Verifikasi disimpan inconclusive dengan validator_failed / tool_limit; operator bisa minta verifikasi ulang. |
| Dua operator memutuskan bersamaan | Transaksi Firestore; yang kedua mendapat 409 ALREADY_DECIDED, web menampilkan keputusan yang sudah tersimpan. |
| Malam arsip tanpa data | /operator/nights mengirim has_data = false (tanggal pudar di kalender); /operator/grid/night mengirim semua slot null dan web menampilkan semua piksel tidak teramati dengan banner. |
| Kirim gagal atau tidak pasti (429, jaringan, worker mati) | Keputusan dan inbox tetap tersimpan. 4xx = failed; timeout atau worker mati setelah klaim = unknown, tidak dikirim ulang otomatis. Operator melihat status per kanal di /deliveries. |