Spaces:
Sleeping
Sleeping
Download main.py from clarussolution/sibyl-oracle: direct link, hf CLI and curl.
- Browser
- Download file 3.91 kB
-
https://huggingface.co/spaces/clarussolution/sibyl-oracle/resolve/main/main.py
- Command line
-
hf download hf://spaces/clarussolution/sibyl-oracle/main.py
-
curl -L -o main.py https://huggingface.co/spaces/clarussolution/sibyl-oracle/resolve/main/main.py
3.91 kB
| import os | |
| import pandas as pd | |
| from fastapi import FastAPI, Query | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from supabase import create_client, Client | |
| from prophet import Prophet | |
| # Inisialisasi FastAPI | |
| app = FastAPI() | |
| # 🛡️ PELINDUNG CORS (Membunuh "Network Failure" di Browser) | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # ⚠️ PERHATIAN: Ini adalah Kunci Master (Service Role). | |
| # Pastikan Hugging Face Space kamu di-set ke PRIVATE! | |
| SUPABASE_URL = "https://ighzdxdjydqjvidrneol.supabase.co" | |
| SUPABASE_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImlnaHpkeGRqeWRxanZpZHJuZW9sIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc3OTY5NTc0MiwiZXhwIjoyMDk1MjcxNzQyfQ.NkTW7A7HpNv0Fwj_PJ8w3Ldkf_MOjrIiHOnIufv-Wks" | |
| # 🛠️ PINTU SATPAM CRON-JOB (Hanya 1 Rute Root) | |
| def health_check(): | |
| return {"status": "200 OK", "message": "Sibyl Engine is Awake and Running. Psycho-Pass clear."} | |
| def forecast_revenue(biz_id: str = Query(None, description="ID Bisnis Klien")): | |
| # 1. Cek Keamanan Kunci API | |
| if not SUPABASE_URL or not SUPABASE_KEY: | |
| return {"error": "Kunci API Supabase belum dipasang di Server Sibyl."} | |
| # 2. Cek Parameter biz_id (PR-03: Keamanan Multi-Tenant) | |
| if not biz_id: | |
| return {"error": "Akses Ditolak: Identifier bisnis (biz_id) tidak ditemukan."} | |
| try: | |
| # 3. Terhubung ke Database | |
| supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY) | |
| # 4. Tarik data HANYA milik biz_id yang me-request | |
| response = supabase.table("invoices")\ | |
| .select("invoice_date, invoice_amount, tax_amount")\ | |
| .eq("biz_id", biz_id)\ | |
| .in_("invoice_status", ["Paid", "PAID"])\ | |
| .execute() | |
| data = response.data | |
| # 5. Cek ambang batas data | |
| if not data or len(data) < 5: | |
| return {"error": "Data invoice berstatus LUNAS (Paid) masih di bawah batas minimum (5 data)."} | |
| # 6. Konversi ke DataFrame Pandas | |
| df = pd.DataFrame(data) | |
| # Penyesuaian NUMERIC ke float64 (Wajib untuk perhitungan engine Prophet) | |
| df['invoice_amount'] = pd.to_numeric(df['invoice_amount'], errors='coerce').fillna(0) | |
| df['tax_amount'] = pd.to_numeric(df['tax_amount'], errors='coerce').fillna(0) | |
| # Gabungkan Subtotal + PPN = Total Revenue | |
| df['total'] = df['invoice_amount'] + df['tax_amount'] | |
| df = df.rename(columns={"invoice_date": "ds", "total": "y"}) | |
| df['ds'] = pd.to_datetime(df['ds']) | |
| # Gabungkan pendapatan jika ada beberapa transaksi di hari yang sama | |
| df = df.groupby('ds').sum().reset_index() | |
| if len(df) < 3: | |
| return {"error": "Varian tanggal transaksi terlalu sedikit untuk menebak pola masa depan."} | |
| # 7. Nyalakan Mesin Prophet (AI Meta) | |
| m = Prophet(daily_seasonality=True, yearly_seasonality=False, weekly_seasonality=True) | |
| m.fit(df) | |
| # 8. Ramal 30 hari ke depan | |
| future = m.make_future_dataframe(periods=30) | |
| forecast = m.predict(future) | |
| # Potong hasil hanya untuk 30 hari masa depan | |
| forecast_30 = forecast.tail(30)[['ds', 'yhat']] | |
| # 9. Rapikan output JSON | |
| hasil = [] | |
| for index, row in forecast_30.iterrows(): | |
| # Filter angka minus (penjualan tidak mungkin minus) | |
| prediksi = float(row['yhat']) if pd.notna(row['yhat']) and row['yhat'] > 0 else 0.0 | |
| hasil.append({ | |
| "tanggal": row['ds'].strftime('%Y-%m-%d'), | |
| "prediksi_omset": prediksi | |
| }) | |
| return {"forecast": hasil} | |
| except Exception as e: | |
| return {"error": f"Core System Error: {str(e)}"} |