ALAMDIENG commited on
Commit
6f173bf
·
1 Parent(s): da8d205

update feature : fine tuning ulang , update data dan testing ke akuratan prediksi hingga mencapai 94.5%

Browse files
Files changed (3) hide show
  1. Doc.md +6 -0
  2. FRONTEND_API_DOC.md +381 -0
  3. README.md +6 -0
Doc.md CHANGED
@@ -6,6 +6,12 @@
6
 
7
  ---
8
 
 
 
 
 
 
 
9
  ## 📑 Table of Contents
10
  1. [Project Overview](#1-project-overview)
11
  2. [System Architecture](#2-system-architecture)
 
6
 
7
  ---
8
 
9
+ > [!IMPORTANT]
10
+ > **📖 FRONT-END INTEGRATION GUIDE**:
11
+ > Untuk panduan teknis khusus tim Front-End (termasuk tipe TypeScript, Axios snippets, pemetaan Peta & progress bar), silakan merujuk langsung ke dokumen [FRONTEND_API_DOC.md](file:///c:/khusus%20project%20IT/Fine%20tuning%20ulang%20AI%20jakarta/waste-prediction-api/FRONTEND_API_DOC.md).
12
+
13
+ ---
14
+
15
  ## 📑 Table of Contents
16
  1. [Project Overview](#1-project-overview)
17
  2. [System Architecture](#2-system-architecture)
FRONTEND_API_DOC.md ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🗑️ Panduan Integrasi API Waste Intelligence — Khusus Front-End (FE)
2
+ > **Sistem Prediksi Manajemen Sampah DKI Jakarta 2026**
3
+ > **Target API Base URL (Lokal)**: `http://localhost:8001`
4
+ > **Target API Base URL (Production)**: `https://huggingface.co/spaces/ALAMDIENG/waste-prediction-api`
5
+
6
+ Dokumen ini disusun untuk memudahkan tim Front-End (FE) dalam mengintegrasikan endpoint backend dengan Dashboard UI, komponen Peta (Leaflet.js/Mapbox), Grafik (Recharts/ApexCharts/Chart.js), dan Sistem Alerts.
7
+
8
+ ---
9
+
10
+ ## 📑 Daftar Isi
11
+ 1. [Konstanta & Data Spasial (Map & Coordinates)](#1-konstanta--data-spasial-map--coordinates)
12
+ 2. [Definisi Tipe Data (TypeScript Interfaces)](#2-definisi-tipe-data-typescript-interfaces)
13
+ 3. [Referensi Endpoint API](#3-referensi-endpoint-api)
14
+ - [GET `/status` (Health Check)](#get-status-health-check)
15
+ - [POST `/api/v1/predict` (Forecasting & Analisis)](#post-apiv1predict-forecasting--analisis)
16
+ - [POST `/api/v1/predict/csv` (Export Data)](#post-apiv1predictcsv-export-data)
17
+ - [GET `/api/v1/alerts` (Daftar Peringatan Hari Ini & H+2)](#get-apiv1alerts-daftar-peringatan-hari-ini--h2)
18
+ 4. [Contoh Implementasi Code (Axios / Fetch)](#4-contoh-implementasi-code-axios--fetch)
19
+ 5. [Panduan Mapping ke UI Dashboard](#5-panduan-mapping-ke-ui-dashboard)
20
+ 6. [Penanganan Error & Validasi](#6-penanganan-error--validasi)
21
+
22
+ ---
23
+
24
+ ## 1. Konstanta & Data Spasial (Map & Coordinates)
25
+
26
+ Untuk memudahkan penggambaran Marker dan Garis Rute (Logistics Route) ke TPST Bantargebang di peta Leaflet.js, gunakan konstanta koordinat berikut di sisi klien.
27
+
28
+ ```javascript
29
+ // Koordinat Utama Lokasi Pengamatan
30
+ export const LOCATION_COORDINATES = {
31
+ "GBK": { latitude: -6.2183, longitude: 106.8022, radiusLabel: "2.0 km" },
32
+ "JIS": { latitude: -6.1244, longitude: 106.8622, radiusLabel: "1.5 km" },
33
+ "Pasar Senen": { latitude: -6.1744, longitude: 106.8444, radiusLabel: "1.2 km" },
34
+ "Gang Sempit Tambora": { latitude: -6.1500, longitude: 106.8000, radiusLabel: "0.8 km" }
35
+ };
36
+
37
+ // Koordinat Pembuangan Akhir (Tempat Pembuangan Sampah Terpadu Bantargebang)
38
+ export const BANTARGEBANG_COORDS = { latitude: -6.3477, longitude: 106.9939 };
39
+
40
+ // Jarak & Waktu Tempuh Estimasi untuk UI Rute Logistik
41
+ export const LOGISTICS_ROUTING_PROFILES = {
42
+ "JIS": { distance: "41.2 km", travelTime: "1.5 Jam" },
43
+ "GBK": { distance: "38.5 km", travelTime: "1.8 Jam" },
44
+ "Pasar Senen": { distance: "34.8 km", travelTime: "1.4 Jam" },
45
+ "Gang Sempit Tambora": { distance: "43.5 km", travelTime: "2.1 Jam" }
46
+ };
47
+ ```
48
+
49
+ > [!TIP]
50
+ > Gambar garis rute (logistik) dari koordinat lokasi terpilih langsung menuju `BANTARGEBANG_COORDS` menggunakan fitur `L.polyline` dengan style *dashed cyan glow* (`#00F0FF`) untuk memberikan kesan modern/cyberpunk.
51
+
52
+ ---
53
+
54
+ ## 2. Definisi Tipe Data (TypeScript Interfaces)
55
+
56
+ Jika Anda menggunakan TypeScript pada frontend (seperti React, Vue, atau Next.js), salin tipe data berikut:
57
+
58
+ ```typescript
59
+ export type ModelType = 'chronos' | 'gradient_boosting';
60
+ export type Granularity = 'daily' | 'hourly';
61
+ export type RiskStatus = 'SAFE' | 'WARNING' | 'CRITICAL';
62
+ export type HourlyRiskIndicator = 'LOW' | 'MEDIUM' | 'HIGH';
63
+
64
+ export interface PredictionRequest {
65
+ forecast_days: number; // 1 - 30 hari
66
+ rainfall_mm: number; // Curah hujan manual (0 = Otomatis mengambil data live cuaca)
67
+ event_scale: number; // Skala keramaian buatan (0 = tidak ada, 5 = masif)
68
+ location: 'JIS' | 'GBK' | 'Pasar Senen' | 'Gang Sempit Tambora';
69
+ start_date?: string; // Opsional, format YYYY-MM-DD
70
+ granularity?: Granularity; // Default: 'daily'
71
+ model_type?: ModelType; // Default: 'chronos'
72
+ }
73
+
74
+ export interface ConfidenceRange {
75
+ lower: number;
76
+ upper: number;
77
+ }
78
+
79
+ export interface HourlyBreakdown {
80
+ hour: string; // Format "00:00", "01:00", dsb.
81
+ estimated_volume_ton: number;
82
+ risk_indicator: HourlyRiskIndicator;
83
+ confidence_range: ConfidenceRange;
84
+ }
85
+
86
+ export interface PredictionResult {
87
+ date: string; // YYYY-MM-DD
88
+ location: string;
89
+ total_volume_ton: number;
90
+ organic_waste_ton: number;
91
+ plastic_waste_ton: number;
92
+ recommended_trucks: number; // Truk kapasitas 5 ton
93
+ risk_status: RiskStatus;
94
+ event_info: string | null; // Nama event terdekat (jika ada)
95
+ hourly_breakdown: HourlyBreakdown[] | null; // Terisi jika granularity = 'hourly'
96
+ }
97
+
98
+ export interface LogisticsPlan {
99
+ trucks_needed: number;
100
+ manpower: number; // 3 x jumlah armada truk
101
+ estimated_duration_hours: number;
102
+ efficiency_rate: string; // Contoh: "85% (Optimal)"
103
+ }
104
+
105
+ export interface PredictionData {
106
+ prediction_results: PredictionResult[];
107
+ logistics_plan: LogisticsPlan;
108
+ }
109
+
110
+ export interface APIPredictionResponse {
111
+ status: 'success' | 'error';
112
+ message: string;
113
+ confidence_score: number; // Skala 0.0 - 1.0 (misal: 0.93)
114
+ data: PredictionData;
115
+ }
116
+
117
+ export interface AlertItem {
118
+ date: string;
119
+ location: string;
120
+ status: 'WARNING' | 'CRITICAL';
121
+ estimated_volume_ton: number;
122
+ message: string;
123
+ }
124
+
125
+ export interface APIAlertResponse {
126
+ status: 'success';
127
+ alert_count: number;
128
+ alerts: AlertItem[];
129
+ last_updated: string; // ISO Timestamp
130
+ }
131
+ ```
132
+
133
+ ---
134
+
135
+ ## 3. Referensi Endpoint API
136
+
137
+ ### GET `/status` (Health Check)
138
+ Endpoint ini digunakan untuk memverifikasi apakah server menyala dan model AI sudah ter-load dengan benar di memori.
139
+
140
+ - **URL**: `/status`
141
+ - **Method**: `GET`
142
+ - **Response Contoh (200 OK)**:
143
+ ```json
144
+ {
145
+ "status": "Online",
146
+ "model_chronos": "Chronos-T5 Tiny",
147
+ "model_gbr": "Gradient Boosting Regressor",
148
+ "calibrated": true
149
+ }
150
+ ```
151
+
152
+ ---
153
+
154
+ ### POST `/api/v1/predict` (Forecasting & Analisis)
155
+ Endpoint utama untuk memanggil prediksi time-series model AI. AI akan menghitung dampak cuaca basah, event keramaian, status risiko per hari, rincian logistik, hingga dekomposisi sampah organik/plastik.
156
+
157
+ - **URL**: `/api/v1/predict`
158
+ - **Method**: `POST`
159
+ - **Headers**:
160
+ - `Content-Type: application/json`
161
+ - **Request Body Contoh**:
162
+ ```json
163
+ {
164
+ "forecast_days": 7,
165
+ "rainfall_mm": 0,
166
+ "event_scale": 0,
167
+ "location": "JIS",
168
+ "granularity": "hourly",
169
+ "model_type": "gradient_boosting"
170
+ }
171
+ ```
172
+
173
+ - **Response Contoh (200 OK)**:
174
+ ```json
175
+ {
176
+ "status": "success",
177
+ "message": "Normal conditions.",
178
+ "confidence_score": 0.9325,
179
+ "data": {
180
+ "prediction_results": [
181
+ {
182
+ "date": "2026-07-08",
183
+ "location": "JIS",
184
+ "total_volume_ton": 122.45,
185
+ "organic_waste_ton": 61.07,
186
+ "plastic_waste_ton": 28.1,
187
+ "recommended_trucks": 25,
188
+ "risk_status": "SAFE",
189
+ "event_info": null,
190
+ "hourly_breakdown": [
191
+ {
192
+ "hour": "00:00",
193
+ "estimated_volume_ton": 2.45,
194
+ "risk_indicator": "LOW",
195
+ "confidence_range": {
196
+ "lower": 2.08,
197
+ "upper": 2.82
198
+ }
199
+ }
200
+ // ... total 24 jam data
201
+ ]
202
+ }
203
+ ],
204
+ "logistics_plan": {
205
+ "trucks_needed": 25,
206
+ "manpower": 75,
207
+ "estimated_duration_hours": 24.5,
208
+ "efficiency_rate": "85% (Optimal)"
209
+ }
210
+ }
211
+ }
212
+ ```
213
+
214
+ ---
215
+
216
+ ### POST `/api/v1/predict/csv` (Export Data)
217
+ Endpoint ini mengembalikan data prediksi yang sama dengan di atas, tetapi langsung dikonversi menjadi file `.csv` yang siap diunduh di peramban pengguna.
218
+
219
+ - **URL**: `/api/v1/predict/csv`
220
+ - **Method**: `POST`
221
+ - **Headers**:
222
+ - `Content-Type: application/json`
223
+ - **Response**: Mengembalikan raw bytes file stream (`text/csv`). Header response menyertakan `Content-Disposition: attachment; filename="waste_forecast_[lokasi]_[hari]d.csv"`.
224
+
225
+ ---
226
+
227
+ ### GET `/api/v1/alerts` (Daftar Peringatan Hari Ini & H+2)
228
+ Mengambil daftar titik lokasi yang mengalami lonjakan volume (di atas batas ambang aman) dalam 3 hari ke depan secara dinamis.
229
+
230
+ - **URL**: `/api/v1/alerts`
231
+ - **Method**: `GET`
232
+ - **Query Params**:
233
+ - `location` (Opsional) : Untuk memfilter alert hanya untuk lokasi tertentu saja (misal: `JIS` / `GBK`).
234
+ - **Response Contoh (200 OK)**:
235
+ ```json
236
+ {
237
+ "status": "success",
238
+ "alert_count": 1,
239
+ "alerts": [
240
+ {
241
+ "date": "2026-07-09",
242
+ "location": "JIS",
243
+ "status": "WARNING",
244
+ "estimated_volume_ton": 168.5,
245
+ "message": "Alert: WARNING volume expected at JIS"
246
+ }
247
+ ],
248
+ "last_updated": "2026-07-08T10:15:30.123456"
249
+ }
250
+ ```
251
+
252
+ ---
253
+
254
+ ## 4. Contoh Implementasi Code (Axios / Fetch)
255
+
256
+ ### Mengirim Request Prediksi & Update State (JavaScript / React)
257
+ ```javascript
258
+ import axios from 'axios';
259
+
260
+ const API_BASE_URL = 'http://localhost:8001'; // Sesuaikan environment
261
+
262
+ export async function fetchWastePrediction(payload) {
263
+ try {
264
+ const response = await axios.post(`${API_BASE_URL}/api/v1/predict`, payload);
265
+ return response.data;
266
+ } catch (error) {
267
+ console.error("Error predicting waste volume:", error.response?.data || error.message);
268
+ throw error;
269
+ }
270
+ }
271
+ ```
272
+
273
+ ### Mengunduh CSV File (JavaScript)
274
+ ```javascript
275
+ export async function downloadPredictionCSV(payload) {
276
+ try {
277
+ const response = await axios.post(`${API_BASE_URL}/api/v1/predict/csv`, payload, {
278
+ responseType: 'blob' // Wajib diisi agar file blob dibaca dengan benar
279
+ });
280
+
281
+ // Trigger download manual via browser
282
+ const blob = new Blob([response.data], { type: 'text/csv' });
283
+ const url = window.URL.createObjectURL(blob);
284
+ const link = document.createElement('a');
285
+ link.href = url;
286
+
287
+ // Nama file dinamis
288
+ const fileName = `waste_forecast_${payload.location.replace(/\s+/g, '_')}_${payload.forecast_days}d.csv`;
289
+ link.setAttribute('download', fileName);
290
+
291
+ document.body.appendChild(link);
292
+ link.click();
293
+
294
+ // Bersihkan link element setelah click
295
+ link.remove();
296
+ window.URL.revokeObjectURL(url);
297
+ } catch (error) {
298
+ console.error("Gagal mengunduh CSV:", error);
299
+ alert("Ekspor CSV Gagal!");
300
+ }
301
+ }
302
+ ```
303
+
304
+ ---
305
+
306
+ ## 5. Panduan Mapping ke UI Dashboard
307
+
308
+ ### A. Total Volume & Kebutuhan Armada
309
+ 1. **Total Volume Forecast**: Lakukan perulangan (`reduce`) untuk menjumlahkan `total_volume_ton` dari semua entri di `data.prediction_results`. Tampilkan nilai desimal 2 angka (`.toFixed(2)`).
310
+ 2. **Kebutuhan Fleet (Truk)**: Tampilkan `data.logistics_plan.trucks_needed`. Truk dihitung secara kumulatif dengan kapasitas angkut maksimal 5 Ton per armada.
311
+ 3. **Tenaga Kerja (Manpower)**: Ditampilkan dari `data.logistics_plan.manpower`. Angka ini adalah alokasi aman kru operasional (3 orang per truk).
312
+
313
+ ### B. Komposisi Sampah (Organic & Plastic)
314
+ Hitung persentase dinamis untuk di-render pada UI *Progress Bar*:
315
+ ```javascript
316
+ // Hitung jumlah tonase terlebih dahulu
317
+ const totalOrganic = results.reduce((acc, c) => acc + c.organic_waste_ton, 0);
318
+ const totalPlastic = results.reduce((acc, c) => acc + c.plastic_waste_ton, 0);
319
+ const totalVol = results.reduce((acc, c) => acc + c.total_volume_ton, 0);
320
+
321
+ // Hitung persentase relatif
322
+ const organicPct = totalVol > 0 ? (totalOrganic / totalVol) * 100 : 0;
323
+ const plasticPct = totalVol > 0 ? (totalPlastic / totalVol) * 100 : 0;
324
+
325
+ // Render ke UI
326
+ // Ganti properti width progress bar inline style / css variable
327
+ document.getElementById('bar-organic').style.width = `${organicPct}%`;
328
+ document.getElementById('bar-plastic').style.width = `${plasticPct}%`;
329
+ ```
330
+
331
+ ### C. Penentuan Status Risiko (Risk Status)
332
+ Backend mengembalikan status per hari: `'SAFE'`, `'WARNING'`, atau `'CRITICAL'`.
333
+ Untuk menentukan status risiko keseluruhan periode yang dipilih:
334
+ - Ambil status **tertinggi** yang muncul di sepanjang list hari prediksi.
335
+ - Aturan Prioritas Status: `CRITICAL` > `WARNING` > `SAFE`.
336
+ - Berikan penyesuaian style warna badge:
337
+ - `SAFE`: Hijau terang (`#00E676`)
338
+ - `WARNING`: Kuning neon (`#FFD600`)
339
+ - `CRITICAL`: Merah menyala (`#FF1744`)
340
+
341
+ ### D. Weather Integration (Live BMKG)
342
+ Saat user memilih lokasi baru:
343
+ 1. Hubungi BMKG/Open-Meteo API di sisi FE menggunakan koordinat lokasi (lihat [Bagian 1](#1-konstanta--data-spasial-map--coordinates)).
344
+ 2. Dapatkan nilai curah hujan hari ini (`precipitation_sum` / `precipitation`).
345
+ 3. Tampilkan status peringatan hujan di UI:
346
+ - Curah Hujan `> 30 mm` ➡️ Tampilkan badge **HEAVY RAIN 🟡**
347
+ - Curah Hujan `> 50 mm` ➡️ Tampilkan badge **FLOOD DANGER 🔴**
348
+ - Di bawah itu ➡️ Tampilkan **Normal conditions**
349
+
350
+ ---
351
+
352
+ ## 6. Penanganan Error & Validasi
353
+
354
+ Backend menggunakan Pydantic v2 untuk memvalidasi request body secara ketat.
355
+
356
+ ### HTTP 422 Unprocessable Entity
357
+ Terjadi jika payload yang dikirimkan memiliki tipe data yang salah atau data di luar rentang validasi.
358
+ *Contoh error respon*:
359
+ ```json
360
+ {
361
+ "detail": [
362
+ {
363
+ "type": "less_than_equal",
364
+ "loc": ["body", "forecast_days"],
365
+ "msg": "Input should be less than or equal to 30",
366
+ "input": 45
367
+ }
368
+ ]
369
+ }
370
+ ```
371
+ **Tips FE**: Batasi input `forecast_days` menggunakan komponen slider HTML `min="1" max="30"` untuk menghindari error ini.
372
+
373
+ ### HTTP 503 Service Unavailable
374
+ Terjadi jika startup server belum selesai me-load model Amazon Chronos atau file CSV belum siap di sisi backend.
375
+ **Tips FE**: Sediakan visual loader atau spinner yang menarik di dashboard untuk mencegah interaksi klik ganda saat status server menunjukkan pemuatan ulang aset AI.
376
+
377
+ ---
378
+
379
+ > 💡 **Kontak Developer Backend**:
380
+ > **Faril Putra Pratama** (SMK Taruna Bangsa)
381
+ > Hubungi via repository GitHub di: [@FARILtau72](https://github.com/FARILtau72) jika Anda membutuhkan endpoint tambahan atau perubahan format respon!
README.md CHANGED
@@ -21,6 +21,12 @@ Eco-Twin AI adalah sistem cerdas berbasis *Machine Learning* yang dirancang untu
21
 
22
  ---
23
 
 
 
 
 
 
 
24
  ## 🚀 Fitur Unggulan (Hackathon Killer Features)
25
 
26
  1. **Integrasi Kalender Event Otomatis**: Sistem secara otomatis membaca file `event_jakarta_2025.txt` saat server dinyalakan. Jika ada *request* prediksi yang menyentuh tanggal konser besar (misal: Maroon 5 di JIS), AI akan mendeteksi dan secara akurat menambahkan estimasi volume sampah tanpa input manual tambahan.
 
21
 
22
  ---
23
 
24
+ > [!IMPORTANT]
25
+ > **📖 DOKUMENTASI INTEGRASI FRONT-END**:
26
+ > Kami telah menyediakan panduan integrasi lengkap khusus tim Front-End (FE) di file [FRONTEND_API_DOC.md](file:///c:/khusus%20project%20IT/Fine%20tuning%20ulang%20AI%20jakarta/waste-prediction-api/FRONTEND_API_DOC.md). File tersebut berisi konstanta koordinat peta, tipe data TypeScript, contoh request Axios/Fetch, serta cara memetakan respons ke UI Dashboard.
27
+
28
+ ---
29
+
30
  ## 🚀 Fitur Unggulan (Hackathon Killer Features)
31
 
32
  1. **Integrasi Kalender Event Otomatis**: Sistem secara otomatis membaca file `event_jakarta_2025.txt` saat server dinyalakan. Jika ada *request* prediksi yang menyentuh tanggal konser besar (misal: Maroon 5 di JIS), AI akan mendeteksi dan secara akurat menambahkan estimasi volume sampah tanpa input manual tambahan.