Spaces:
Sleeping
Sleeping
Download scripts/laya_simulate_shadow.py from yabeskn/briga-agent-worker: direct link, hf CLI and curl.
- Browser
- Download file 27 kB
-
https://huggingface.co/spaces/yabeskn/briga-agent-worker/resolve/main/scripts/laya_simulate_shadow.py
- Command line
-
hf download hf://spaces/yabeskn/briga-agent-worker/scripts/laya_simulate_shadow.py
-
curl -L -o laya_simulate_shadow.py https://huggingface.co/spaces/yabeskn/briga-agent-worker/resolve/main/scripts/laya_simulate_shadow.py
27 kB
| """ | |
| Laya Shadow Simulator Tool (laya_simulate_shadow.py) | |
| Generates diverse, realistic job posting scenarios (Green, Non-Green, Edge-cases, Scam) | |
| in Indonesian and English, evaluates them using Laya System 1 vs Gemini/Rule-Engine, | |
| records the results to the Supabase `laya_shadow_decisions` table, and runs | |
| calibration analysis (laya_calibrate.py). | |
| Usage: | |
| python scripts/laya_simulate_shadow.py --count 100 | |
| python scripts/laya_simulate_shadow.py --count 50 --domain worker_scraper | |
| python scripts/laya_simulate_shadow.py --count 100 --dry-run | |
| python scripts/laya_simulate_shadow.py --count 20 --live-gemini | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import asyncio | |
| import hashlib | |
| import json | |
| import os | |
| import random | |
| import sys | |
| import time | |
| from typing import Any, Dict, List, Optional, Tuple | |
| import httpx | |
| # Ensure paths | |
| SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| AGENT_ROOT = os.path.dirname(SCRIPT_DIR) | |
| if AGENT_ROOT not in sys.path: | |
| sys.path.insert(0, AGENT_ROOT) | |
| from services.laya.engine import LayaEngine | |
| from services.laya.shadow_mode import ( | |
| compare_green_gate, | |
| compare_sector_choice, | |
| compare_scam_gate, | |
| compare_authenticity, | |
| digest_input, | |
| ) | |
| try: | |
| from services.analyzer import GREEN_SECTORS | |
| except ImportError: | |
| GREEN_SECTORS = [ | |
| "Energi Terbarukan", | |
| "Circular Economy & Pengolahan Limbah", | |
| "Konservasi & Agroforestri", | |
| "Manajemen Karbon & Iklim", | |
| "HSE & Manajemen Lingkungan", | |
| "Green Building & Efisiensi Energi", | |
| ] | |
| # ============================================================================ | |
| # Scenario Templates & Dataset Combinator | |
| # ============================================================================ | |
| GREEN_JOB_TEMPLATES = [ | |
| { | |
| "title": "Solar PV Project Engineer", | |
| "company": "PT Surya Energi Nusantara", | |
| "sector": "Energi Terbarukan", | |
| "desc": "Bertanggung jawab atas desain teknik, instalasi modul surya fotovoltaik (Rooftop & Ground-Mounted), studi kelayakan radiasi surya, dan komisioning sistem PLTS terdistribusi.", | |
| "is_green": True, | |
| "is_scam": False, | |
| "auth_score": 92.0 | |
| }, | |
| { | |
| "title": "ESG & Carbon Accounting Specialist", | |
| "company": "Nusantara Sustainability Advisory", | |
| "sector": "Manajemen Karbon & Iklim", | |
| "desc": "Menghitung emisi Gas Rumah Kaca (GRK) Scope 1, 2, dan 3 berbasis GHG Protocol. Menyusun laporan keberlanjutan GRI Standard dan dokumen verifikasi kredit karbon NDC.", | |
| "is_green": True, | |
| "is_scam": False, | |
| "auth_score": 88.0 | |
| }, | |
| { | |
| "title": "Waste Management & Circular Economy Officer", | |
| "company": "PT Daur Karbon Indonesia", | |
| "sector": "Circular Economy & Pengolahan Limbah", | |
| "desc": "Mengelola fasilitas daur ulang limbah plastik industri, merancang skema circular economy, koordinasi bank sampah mitra, dan optimasi rantai pasok material recovered.", | |
| "is_green": True, | |
| "is_scam": False, | |
| "auth_score": 85.0 | |
| }, | |
| { | |
| "title": "Energy Efficiency & Conservation Auditor", | |
| "company": "GreenAudit Solutions", | |
| "sector": "Green Building & Efisiensi Energi", | |
| "desc": "Melakukan audit konsumsi energi gedung komersial dan pabrik industri. Merekomendasikan retrofit HVAC, pemanfaatan waste heat recovery, dan sertifikasi ISO 50001.", | |
| "is_green": True, | |
| "is_scam": False, | |
| "auth_score": 87.0 | |
| }, | |
| { | |
| "title": "Biodiversity Conservation & Agroforestry Specialist", | |
| "company": "Yayasan Restorasi Hutan Tropis", | |
| "sector": "Konservasi & Agroforestri", | |
| "desc": "Memimpin pemantauan keanekaragaman hayati, restorasi lahan gambut terdegradasi, penanaman mangrove pesisir, dan program mitigasi deforestasi masyarakat agroforestri.", | |
| "is_green": True, | |
| "is_scam": False, | |
| "auth_score": 90.0 | |
| }, | |
| { | |
| "title": "Water Treatment & Wastewater Engineer", | |
| "company": "PT Tirta Lestari Bersih", | |
| "sector": "Circular Economy & Pengolahan Limbah", | |
| "desc": "Operasional Instalasi Pengolahan Air Limbah (IPAL), monitoring baku mutu effluent, pemurnian air limbah industri tekstil, dan teknologi zero liquid discharge.", | |
| "is_green": True, | |
| "is_scam": False, | |
| "auth_score": 83.0 | |
| }, | |
| { | |
| "title": "Wind Farm Operations Technician", | |
| "company": "Bayu Megah EBT", | |
| "sector": "Energi Terbarukan", | |
| "desc": "Pemeliharaan preventif turbin angin kapasitas 3MW, inspeksi bilah rotor, generator listrik, monitoring SCADA ladang angin pembangkit listrik bayu EBT.", | |
| "is_green": True, | |
| "is_scam": False, | |
| "auth_score": 91.0 | |
| }, | |
| { | |
| "title": "Environmental Impact Assessment (AMDAL) Consultant", | |
| "company": "PT Mitra Lingkungan Hidup", | |
| "sector": "HSE & Manajemen Lingkungan", | |
| "desc": "Penyusunan dokumen AMDAL, RKL-RPL, izin lingkungan terintegrasi, dan pemantauan kepatuhan regulasi baku mutu lingkungan KLHK untuk industri hijau.", | |
| "is_green": True, | |
| "is_scam": False, | |
| "auth_score": 86.0 | |
| }, | |
| ] | |
| NON_GREEN_TEMPLATES = [ | |
| { | |
| "title": "Senior Frontend React Developer", | |
| "company": "Fintech Prima Tech", | |
| "sector": "Lainnya", | |
| "desc": "Membangun antarmuka web aplikasi perbankan digital menggunakan React.js, TypeScript, Next.js, dan Tailwind CSS. Kolaborasi dengan tim backend API.", | |
| "is_green": False, | |
| "is_scam": False, | |
| "auth_score": 15.0 | |
| }, | |
| { | |
| "title": "Store Supervisor & Cashier Lead", | |
| "company": "Minimarket Berkah Jaya", | |
| "sector": "Lainnya", | |
| "desc": "Mengawasi transaksi kasir harian, stock opname barang minimarket, melayani komplain pelanggan, dan mengelola shift kerja staf toko retail.", | |
| "is_green": False, | |
| "is_scam": False, | |
| "auth_score": 10.0 | |
| }, | |
| { | |
| "title": "Staff Akuntansi & Pajak", | |
| "company": "Kantor Akuntan Mitra Sejahtera", | |
| "sector": "Lainnya", | |
| "desc": "Pencatatan jurnal buku besar, rekonsiliasi bank, penyusunan laporan laba rugi bulanan, dan pelaporan SPT Masa PPh 21 / PPh 23 serta PPN.", | |
| "is_green": False, | |
| "is_scam": False, | |
| "auth_score": 12.0 | |
| }, | |
| { | |
| "title": "Telemarketing & Sales Executive", | |
| "company": "Solusi Asuransi Jiwa", | |
| "sector": "Lainnya", | |
| "desc": "Menghubungi calon nasabah melalui telepon untuk menawarkan produk asuransi kesehatan keluarga, mencapai target polis bulanan, dan follow-up prospek.", | |
| "is_green": False, | |
| "is_scam": False, | |
| "auth_score": 8.0 | |
| }, | |
| { | |
| "title": "Security Guard Operasional Gedung", | |
| "company": "PT Garda Pengamanan Mandiri", | |
| "sector": "Lainnya", | |
| "desc": "Melakukan patroli keamanan area perkantoran, pengecekan kartu akses masuk pengunjung, memantau kamera CCTV, dan menjaga ketertiban area parkir.", | |
| "is_green": False, | |
| "is_scam": False, | |
| "auth_score": 5.0 | |
| }, | |
| { | |
| "title": "Supir Logistik Truk Ekspedisi", | |
| "company": "Kirim Cepat Logistik", | |
| "sector": "Lainnya", | |
| "desc": "Mengantar barang logistik antarkota jalur darat Jawa-Bali dengan armada truk diesel box, merawat kondisi kendaraan, dan memastikan pengiriman tepat waktu.", | |
| "is_green": False, | |
| "is_scam": False, | |
| "auth_score": 14.0 | |
| }, | |
| ] | |
| EDGE_CASE_TEMPLATES = [ | |
| { | |
| "title": "HSE & Environmental Compliance Officer (Mining)", | |
| "company": "PT Tambang Mineral Sejahtera", | |
| "sector": "HSE & Manajemen Lingkungan", | |
| "desc": "Pengawasan keselamatan kerja K3 dan pengelolaan kepatuhan lingkungan hidup di site pertambangan nikel, uji kualitas air kolam pengendap sedimen, dan reklamasi pascatambang.", | |
| "is_green": True, # Has explicit environmental compliance | |
| "is_scam": False, | |
| "auth_score": 65.0 | |
| }, | |
| { | |
| "title": "Supply Chain Sustainability Analyst", | |
| "company": "Global Beverage Manufacture", | |
| "sector": "Circular Economy & Pengolahan Limbah", | |
| "desc": "Audit kepatuhan pemasok terhadap kemasan ramah lingkungan, optimasi rute armada distribusi untuk efisiensi bahan bakar, dan inisiatif circular packaging.", | |
| "is_green": True, | |
| "is_scam": False, | |
| "auth_score": 72.0 | |
| }, | |
| { | |
| "title": "Green Building Facility Manager", | |
| "company": "Modern Tower Management", | |
| "sector": "Green Building & Efisiensi Energi", | |
| "desc": "Pengelolaan operasional gedung bertingkat dengan sertifikasi Greenship / LEED, pemantauan konsumsi daya chiller hemat energi, dan pengolahan greywater.", | |
| "is_green": True, | |
| "is_scam": False, | |
| "auth_score": 78.0 | |
| }, | |
| { | |
| "title": "Corporate Legal Counsel - Perizinan Kehutanan & Perkebunan", | |
| "company": "Kemitraan Sawit Makmur", | |
| "sector": "Lainnya", | |
| "desc": "Mengurus perizinan pelepasan kawasan hutan, sengketa lahan, sertifikasi ISPO/RSPO, dan kepatuhan hukum regulasi kehutanan nasional.", | |
| "is_green": False, # Primarily legal/palm oil operations | |
| "is_scam": False, | |
| "auth_score": 45.0 | |
| }, | |
| ] | |
| SCAM_TEMPLATES = [ | |
| { | |
| "title": "Staff Entry Data Online - Gaji Harian 500rb", | |
| "company": "PT Bintang Karir Online", | |
| "sector": "Lainnya", | |
| "desc": "Lowongan kerja sampingan ketik data online dari rumah via smartphone. Syarat: usia 18-45 tahun. Hubungi WhatsApp admin di 0812xxxx. Wajib deposit aktivasi akun 150rb.", | |
| "is_green": False, | |
| "is_scam": True, | |
| "auth_score": 5.0 | |
| }, | |
| { | |
| "title": "Recruitment Khusus BUMN Bioenergi & Pertamina (Travel Agent Kerjasama)", | |
| "company": "Panitia Seleksi Rekrutmen Nasional", | |
| "sector": "Energi Terbarukan", | |
| "desc": "Panggilan tes wawancara BUMN Energi Terbarukan di Surabaya. Akomodasi dan tiket penerbangan WAJIB dipesan melalui agen travel resmi mitra panitia dan akan di-reimburse saat kedatangan.", | |
| "is_green": False, | |
| "is_scam": True, | |
| "auth_score": 10.0 | |
| }, | |
| { | |
| "title": "Freelance Review Produk E-Commerce Berkelanjutan", | |
| "company": "EcoShop Global Media", | |
| "sector": "Lainnya", | |
| "desc": "Tugas hanya like dan review produk ramah lingkungan di marketplace. Komisi langsung cair 20% tiap misi. Wajib top-up saldo deposit misi awal sebesar 500.000.", | |
| "is_green": False, | |
| "is_scam": True, | |
| "auth_score": 15.0 | |
| } | |
| ] | |
| LOCATIONS = [ | |
| "Jakarta Selatan, DKI Jakarta", | |
| "Surabaya, Jawa Timur", | |
| "Bandung, Jawa Barat", | |
| "Balikpapan, Kalimantan Timur", | |
| "Medan, Sumatera Utara", | |
| "Denpasar, Bali", | |
| "Makassar, Sulawesi Selatan", | |
| "Batam, Kepulauan Riau", | |
| "Remote / WFH", | |
| ] | |
| def generate_scenarios(count: int = 100) -> List[Dict[str, Any]]: | |
| """ | |
| Generate balanced scenarios from training dataset or template pool. | |
| """ | |
| training_csv = os.path.join(AGENT_ROOT, "data", "training", "brigawan_job_training_full.csv") | |
| if os.path.exists(training_csv): | |
| import csv | |
| with open(training_csv, "r", encoding="utf-8") as f: | |
| reader = csv.DictReader(f) | |
| rows = list(reader) | |
| if rows: | |
| sampled = random.sample(rows, min(count, len(rows))) if count <= len(rows) else random.choices(rows, k=count) | |
| results = [] | |
| for r in sampled: | |
| results.append({ | |
| "id": r["id"], | |
| "title": r["title"], | |
| "company": r["company"], | |
| "location": r["location"], | |
| "description": r["description"], | |
| "ground_truth": { | |
| "is_green": r["is_green"].strip().lower() in ("true", "1"), | |
| "sector": r["sector"], | |
| "is_scam": r["is_scam"].strip().lower() in ("true", "1"), | |
| "auth_score": float(r["authenticity_score"]), | |
| } | |
| }) | |
| return results | |
| scenarios: List[Dict[str, Any]] = [] | |
| # Proportions: ~45% Green, ~35% Non-Green, ~10% Edge, ~10% Scam | |
| num_green = int(count * 0.45) | |
| num_non_green = int(count * 0.35) | |
| num_edge = int(count * 0.10) | |
| num_scam = max(1, count - (num_green + num_non_green + num_edge)) | |
| pools = [ | |
| (GREEN_JOB_TEMPLATES, num_green), | |
| (NON_GREEN_TEMPLATES, num_non_green), | |
| (EDGE_CASE_TEMPLATES, num_edge), | |
| (SCAM_TEMPLATES, num_scam), | |
| ] | |
| idx = 1 | |
| for template_pool, n in pools: | |
| for _ in range(n): | |
| tmpl = random.choice(template_pool) | |
| loc = random.choice(LOCATIONS) | |
| salt = random.randint(100, 999) | |
| # Add slight variations to prevent exact digest collisions | |
| title_var = f"{tmpl['title']}" if random.random() > 0.3 else f"{tmpl['title']} (Batch {salt})" | |
| desc_var = f"{tmpl['desc']} Lokasi penempatan: {loc}. Kualifikasi: Min S1/D3 relevan, pengalaman min 1-2 tahun." | |
| scenario = { | |
| "id": f"sim_{idx:04d}", | |
| "title": title_var, | |
| "company": f"{tmpl['company']}", | |
| "location": loc, | |
| "description": desc_var, | |
| "ground_truth": { | |
| "is_green": tmpl["is_green"], | |
| "sector": tmpl["sector"], | |
| "is_scam": tmpl["is_scam"], | |
| "auth_score": tmpl["auth_score"], | |
| } | |
| } | |
| scenarios.append(scenario) | |
| idx += 1 | |
| random.shuffle(scenarios) | |
| return scenarios | |
| # ============================================================================ | |
| # Simulator Engine | |
| # ============================================================================ | |
| class LayaShadowSimulator: | |
| def __init__( | |
| self, | |
| supabase_url: Optional[str] = None, | |
| supabase_key: Optional[str] = None, | |
| live_gemini: bool = False, | |
| table: str = "laya_shadow_decisions", | |
| ): | |
| self.supabase_url = ( | |
| supabase_url | |
| or os.getenv("SUPABASE_URL") | |
| or os.getenv("GJA_SUPABASE_URL") | |
| or "" | |
| ).rstrip("/") | |
| self.supabase_key = ( | |
| supabase_key | |
| or os.getenv("SUPABASE_KEY") | |
| or os.getenv("GJA_SUPABASE_KEY") | |
| or os.getenv("SUPABASE_SERVICE_KEY") | |
| or os.getenv("SUPABASE_SERVICE_ROLE_KEY") | |
| or "" | |
| ) | |
| self.live_gemini = live_gemini | |
| self.table = table | |
| self.laya = LayaEngine() | |
| async def evaluate_single_scenario( | |
| self, | |
| scenario: Dict[str, Any], | |
| domain: str = "all" | |
| ) -> List[Dict[str, Any]]: | |
| """ | |
| Evaluate one scenario with Laya and prepare shadow records. | |
| """ | |
| title = scenario["title"] | |
| company = scenario["company"] | |
| desc = scenario["description"] | |
| gt = scenario["ground_truth"] | |
| combined = f"{title}\n{company}\n{desc}" | |
| records: List[Dict[str, Any]] = [] | |
| # ------------------------------------------------------------------ | |
| # 1. green_gate (evaluated for 'worker_scraper' or 'analyzer') | |
| # ------------------------------------------------------------------ | |
| if domain in ("all", "worker_scraper", "analyzer"): | |
| target_domain = "worker_scraper" if domain == "worker_scraper" else "analyzer" | |
| t0 = time.perf_counter() | |
| green_res = await self.laya.noul( | |
| "Is this job a green job in sustainability or climate?", | |
| context=combined, | |
| use_cache=False, | |
| ) | |
| lat = round((time.perf_counter() - t0) * 1000.0, 2) | |
| gemini_green = gt["is_green"] | |
| agreement = (green_res.is_true == gemini_green) | |
| records.append({ | |
| "domain": target_domain, | |
| "decision_point": "green_gate", | |
| "input_digest": digest_input(title, company, desc), | |
| "laya_value": green_res.is_true, | |
| "laya_probability": green_res.probability, | |
| "laya_confidence": green_res.confidence, | |
| "laya_latency_ms": lat, | |
| "gemini_value": {"isGreenJob": gemini_green, "sectorMatch": gt["sector"] if gemini_green else None}, | |
| "gemini_source": "gemini" if self.live_gemini else "rule_engine", | |
| "agreement": agreement, | |
| "notes": f"Simulation test {scenario['id']}" | |
| }) | |
| # ------------------------------------------------------------------ | |
| # 2. sector_choice (for 'analyzer') | |
| # ------------------------------------------------------------------ | |
| if domain in ("all", "analyzer"): | |
| t0 = time.perf_counter() | |
| choice_res = await self.laya.choice( | |
| "Select the primary green economy sector for this job:", | |
| allowed_choices=GREEN_SECTORS, | |
| context=combined, | |
| use_cache=False, | |
| ) | |
| lat = round((time.perf_counter() - t0) * 1000.0, 2) | |
| gemini_sector = gt["sector"] | |
| agreement = (choice_res.selected_choice.lower() == gemini_sector.lower()) if gemini_sector in GREEN_SECTORS else False | |
| records.append({ | |
| "domain": "analyzer", | |
| "decision_point": "sector_choice", | |
| "input_digest": digest_input(title, company, desc), | |
| "laya_value": choice_res.selected_choice, | |
| "laya_probability": None, | |
| "laya_confidence": choice_res.confidence, | |
| "laya_latency_ms": lat, | |
| "gemini_value": {"sectorMatch": gemini_sector}, | |
| "gemini_source": "gemini" if self.live_gemini else "rule_engine", | |
| "agreement": agreement, | |
| "notes": f"Simulation test {scenario['id']}" | |
| }) | |
| # ------------------------------------------------------------------ | |
| # 3. scam_gate (for 'critic') | |
| # ------------------------------------------------------------------ | |
| if domain in ("all", "critic"): | |
| t0 = time.perf_counter() | |
| scam_res = await self.laya.noul( | |
| "Is this job a scam?", | |
| context=combined, | |
| use_cache=False, | |
| ) | |
| lat = round((time.perf_counter() - t0) * 1000.0, 2) | |
| gemini_scam = gt["is_scam"] | |
| agreement = (scam_res.is_true == gemini_scam) | |
| records.append({ | |
| "domain": "critic", | |
| "decision_point": "scam_gate", | |
| "input_digest": digest_input(title, company, desc), | |
| "laya_value": scam_res.is_true, | |
| "laya_probability": scam_res.probability, | |
| "laya_confidence": scam_res.confidence, | |
| "laya_latency_ms": lat, | |
| "gemini_value": {"scam_risk": gemini_scam}, | |
| "gemini_source": "gemini" if self.live_gemini else "rule_engine", | |
| "agreement": agreement, | |
| "notes": f"Simulation test {scenario['id']}" | |
| }) | |
| # ------------------------------------------------------------------ | |
| # 4. authenticity_score (for 'critic') | |
| # ------------------------------------------------------------------ | |
| if domain in ("all", "critic"): | |
| t0 = time.perf_counter() | |
| auth_res = await self.laya.score( | |
| "Rate the authenticity of direct green/decarbonization substance (0-100)", | |
| scale_min=0.0, | |
| scale_max=100.0, | |
| context=desc, | |
| use_cache=False, | |
| ) | |
| lat = round((time.perf_counter() - t0) * 1000.0, 2) | |
| def _bucket(v: float) -> str: | |
| if v >= 70: | |
| return "VERIFIED" | |
| if v >= 40: | |
| return "SUSPICIOUS" | |
| return "REJECTED" | |
| gemini_score = gt["auth_score"] | |
| agreement = (_bucket(auth_res.score) == _bucket(gemini_score)) | |
| records.append({ | |
| "domain": "critic", | |
| "decision_point": "authenticity_score", | |
| "input_digest": digest_input(title, company, desc), | |
| "laya_value": auth_res.score, | |
| "laya_probability": None, | |
| "laya_confidence": auth_res.confidence, | |
| "laya_latency_ms": lat, | |
| "gemini_value": {"authenticity_score": gemini_score}, | |
| "gemini_source": "gemini" if self.live_gemini else "rule_engine", | |
| "agreement": agreement, | |
| "notes": f"Simulation test {scenario['id']}" | |
| }) | |
| return records | |
| async def persist_records(self, records: List[Dict[str, Any]], batch_size: int = 50) -> int: | |
| """ | |
| Write shadow records to Supabase via PostgREST batch POST. | |
| """ | |
| if not self.supabase_url or not self.supabase_key: | |
| raise RuntimeError("SUPABASE_URL and SUPABASE_KEY are required for database writing.") | |
| headers = { | |
| "apikey": self.supabase_key, | |
| "Authorization": f"Bearer {self.supabase_key}", | |
| "Content-Type": "application/json", | |
| "Prefer": "return=minimal" | |
| } | |
| inserted = 0 | |
| async with httpx.AsyncClient(timeout=30) as client: | |
| for i in range(0, len(records), batch_size): | |
| chunk = records[i:i + batch_size] | |
| resp = await client.post( | |
| f"{self.supabase_url}/rest/v1/{self.table}", | |
| headers=headers, | |
| json=chunk | |
| ) | |
| if resp.status_code in (200, 201): | |
| inserted += len(chunk) | |
| else: | |
| print(f"Warning: batch insert failed [{resp.status_code}]: {resp.text[:200]}") | |
| return inserted | |
| # ============================================================================ | |
| # CLI Entrypoint | |
| # ============================================================================ | |
| async def main_async(): | |
| parser = argparse.ArgumentParser(description="Laya Shadow Mode Simulation & Calibration Tool") | |
| parser.add_argument("--count", type=int, default=100, help="Number of simulated scenarios to generate (default: 100)") | |
| parser.add_argument("--domain", type=str, default="all", choices=["all", "worker_scraper", "analyzer", "critic"], | |
| help="Filter decision domains (default: all)") | |
| parser.add_argument("--dry-run", action="store_true", help="Run simulation in memory without writing to Supabase") | |
| parser.add_argument("--live-gemini", action="store_true", help="Call live Gemini API instead of rule-engine teacher") | |
| parser.add_argument("--skip-calibrate", action="store_true", help="Skip running laya_calibrate.py after simulation") | |
| parser.add_argument("--table", type=str, default="laya_shadow_decisions", help="Target shadow table name") | |
| args = parser.parse_args() | |
| print(f"\n{'='*70}") | |
| print(f"[BRIGAWAN] LAYA SHADOW SIMULATOR") | |
| print(f"{'='*70}") | |
| print(f"• Scenarios to generate : {args.count}") | |
| print(f"• Target domain : {args.domain}") | |
| print(f"• Teacher mode : {'Live Gemini API' if args.live_gemini else 'Rule Engine (0 token)'}") | |
| print(f"• Dry run : {args.dry_run}") | |
| print(f"• Target Table : {args.table}") | |
| print(f"{'='*70}\n") | |
| # Step 1: Generate scenarios | |
| print(f"[*] Generating {args.count} realistic hybrid job scenarios...") | |
| scenarios = generate_scenarios(args.count) | |
| print(f"[+] Successfully generated {len(scenarios)} job scenarios.") | |
| # Step 2: Evaluate with Laya | |
| print(f"[*] Evaluating scenarios through Laya Decision Engine (System 1)...") | |
| simulator = LayaShadowSimulator(live_gemini=args.live_gemini, table=args.table) | |
| all_records: List[Dict[str, Any]] = [] | |
| t_start = time.perf_counter() | |
| for s in scenarios: | |
| recs = await simulator.evaluate_single_scenario(s, domain=args.domain) | |
| all_records.extend(recs) | |
| t_total = time.perf_counter() - t_start | |
| print(f"[+] Computed {len(all_records)} decisions across {len(scenarios)} scenarios in {t_total*1000:.1f}ms " | |
| f"(avg {(t_total/len(all_records))*1000:.2f}ms/decision).") | |
| # Step 3: Summary table in memory | |
| summary: Dict[Tuple[str, str], Dict[str, Any]] = {} | |
| for r in all_records: | |
| k = (r["domain"], r["decision_point"]) | |
| g = summary.setdefault(k, {"total": 0, "agreements": 0, "latencies": []}) | |
| g["total"] += 1 | |
| if r["agreement"]: | |
| g["agreements"] += 1 | |
| if r["laya_latency_ms"] is not None: | |
| g["latencies"].append(r["laya_latency_ms"]) | |
| print(f"\n{'='*70}") | |
| print(f"[METRICS] IN-MEMORY SIMULATION SUMMARY") | |
| print(f"{'='*70}") | |
| print(f"{'Domain':<18} {'Decision Point':<20} {'Samples':<8} {'Agreement':<12} {'Avg Latency'}") | |
| print(f"{'-'*70}") | |
| for (d, p), stats in sorted(summary.items()): | |
| rate = (stats["agreements"] / stats["total"]) * 100 if stats["total"] else 0 | |
| avg_lat = sum(stats["latencies"]) / len(stats["latencies"]) if stats["latencies"] else 0 | |
| print(f"{d:<18} {p:<20} {stats['total']:<8} {rate:>6.1f}% {avg_lat:>6.2f} ms") | |
| print(f"{'='*70}\n") | |
| # Step 4: Persist to Supabase | |
| if args.dry_run: | |
| print("[!] Dry-run enabled: skipping persistence to Supabase.") | |
| else: | |
| print(f"[*] Persisting {len(all_records)} records to Supabase table '{args.table}'...") | |
| inserted = await simulator.persist_records(all_records) | |
| print(f"[+] Successfully inserted {inserted}/{len(all_records)} records to database.") | |
| # Step 5: Automatically trigger calibration report | |
| if not args.dry_run and not args.skip_calibrate: | |
| print(f"\n[*] Triggering calibration analysis via laya_calibrate.py...\n") | |
| import subprocess | |
| calib_cmd = [ | |
| sys.executable, | |
| os.path.join(SCRIPT_DIR, "laya_calibrate.py"), | |
| "--days", "14", | |
| ] | |
| if args.domain != "all": | |
| calib_cmd.extend(["--domain", args.domain]) | |
| res = subprocess.run(calib_cmd, capture_output=True, text=True) | |
| if res.stdout: | |
| print(res.stdout) | |
| if res.stderr: | |
| print(res.stderr) | |
| def main(): | |
| if sys.platform == "win32": | |
| import io | |
| sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace") | |
| sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8", errors="replace") | |
| asyncio.run(main_async()) | |
| if __name__ == "__main__": | |
| main() | |