Upload folder using huggingface_hub
Browse filesFiles changed (18)
- README.md+24-4
- __pycache__/main.cpython-311.pycAdded
- __pycache__/ner_extractor.cpython-311.pycAdded
- __pycache__/nlu_engine.cpython-311.pycAdded
- __pycache__/schema.cpython-311.pycAdded
- __pycache__/session_store.cpython-311.pycAdded
- __pycache__/state_manager.cpython-311.pycAdded
- app.pyAdded+98
- main.pyAdded+154
- ner_extractor.pyAdded+417
- nlu_engine.pyAdded+476
- requirements.txtAdded+6
- schema.pyAdded+247
- session_store.pyAdded+118
- state_manager.pyAdded+465
- static/app.jsAdded+125
- static/index.htmlAdded+51
- static/style.cssAdded+248
12345678910111213---title: Payparseemoji: 💻colorFrom: greencolorTo: indigosdk: gradiosdk_version: 6.26.0python_version: '3.12'app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233---title: Payparseemoji: 🎤colorFrom: greencolorTo: indigosdk: gradiosdk_version: 5.0.0python_version: '3.11'app_file: app.pypinned: falselicense: mit---# PayParse — Indonesian NLU Voice AssistantZero-shot LLM NLU (Gemini Flash) + rule-based NER + slot-filling state machinefor Indonesian financial voice queries (GoPay-style).## Supported Intents- **Transfer Uang** — "transfer 50 ribu ke Budi"- **Beli Pulsa** — "beliin anton pulsa 10rb"- **Bayar PLN** — "bayar tagihan listrik id 4512345678"- **Gojek** — "gojek ke stasiun"- **GoFood** — "gofood nasi goreng"## API Endpoints- `POST /api/chat` — process one dialogue turn- `DELETE /api/session/{id}` — reset conversation- `GET /health` — liveness probe- `GET /gradio` — web chat interface## SecretsSet `GEMINI_API_KEY` in Space Settings → Variables and secrets.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""app.py — Hugging Face Spaces entry point (Gradio SDK)
Combines:- FastAPI REST API at /api/* (for the Android app)- Gradio ChatInterface at / (for web testing)
Both run on port 7860 (HF Spaces default)."""
import osimport sys
# Ensure the backend modules are importablesys.path.insert(0, os.path.dirname(__file__))
import gradio as grimport uvicornfrom fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse
from main import app as fastapi_appfrom nlu_engine import create_enginefrom schema import ChatRequestfrom session_store import SessionStorefrom state_manager import StateManager
# --- Ensure FastAPI app has the engine initialized ---# (HF Spaces doesn't call lifespan automatically when mounted)offline = os.getenv("PAYPARSE_OFFLINE", "0") == "1"engine = create_engine(offline=offline)fastapi_app.state.engine = enginefastapi_app.state.store = SessionStore()fastapi_app.state.manager = StateManager(nlu_engine=engine, use_llm_paraphrase=False)
# --- Gradio Chat Interface (for web testing) ---def chat_with_dira(message: str, history: list) -> str: """Simple Gradio chat function that calls the backend.""" import requests # Call our own FastAPI endpoint internally session_id = "gradio-web" try: # Use direct function call instead of HTTP store = fastapi_app.state.store state = store.get_or_create(session_id)
nlu_result = fastapi_app.state.engine.extract(message, state=state) result = fastapi_app.state.manager.process( state, nlu_result, message, resolve_contacts_locally=False ) store.save(result.state)
if result.is_complete: store.delete(session_id)
return result.reply except Exception as e: return f"Error: {e}"
def chat_interface(message, history): """Gradio ChatInterface wrapper.""" if not message.strip(): return "" reply = chat_with_dira(message, history) return reply
# Create Gradio interfacedemo = gr.ChatInterface( fn=chat_interface, title="PayParse — Dira AI Assistant", description=( "Asisten suara dompet digital Indonesia. Coba bilang:\n" "- 'transfer 50 ribu ke Budi'\n" "- 'beli pulsa 25rb ke 081234567890'\n" "- 'bayar listrik id pelanggan 4512345678'\n" "- 'gojek ke stasiun'\n" "- 'gofood nasi goreng'" ), theme=gr.themes.Soft(), textbox=gr.Textbox(placeholder="Ketik pesan...", scale=7),)
# Mount Gradio onto FastAPI at root pathapp = gr.mount_gradio_app(fastapi_app, demo, path="/gradio")
# Also serve root as Gradio@app.get("/")def root(): """Redirect root to Gradio interface.""" from fastapi.responses import RedirectResponse return RedirectResponse(url="/gradio")
if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=7860)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154"""main.py-------FastAPI application serving the PayParse multi-turn NLU assistant.
Endpoints---------POST /api/chat : one dialogue turn (NLU -> slot filling -> reply)DELETE /api/session/{id} : reset a conversationGET /health : liveness probe + engine mode
Run locally: uvicorn main:app --reload
Run on Hugging Face Spaces: The Dockerfile sets PORT=7860. GEMINI_API_KEY is injected as a HF Secret. PAYPARSE_SESSION_BACKEND=memory (HF filesystem is ephemeral)."""
from __future__ import annotations
import loggingimport osfrom contextlib import asynccontextmanager
from pathlib import Path
from fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponse, JSONResponsefrom fastapi.staticfiles import StaticFiles
from nlu_engine import MockNLUEngine, create_enginefrom schema import ChatRequest, ChatResponsefrom session_store import SessionStorefrom state_manager import StateManager
STATIC_DIR = Path(__file__).parent / "static"
logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
@asynccontextmanagerasync def lifespan(app: FastAPI): """Initialize shared singletons once at startup.""" offline = os.getenv("PAYPARSE_OFFLINE", "0") == "1" use_paraphrase = os.getenv("PAYPARSE_LLM_FOLLOWUP", "0") == "1"
engine = create_engine(offline=offline) app.state.engine = engine app.state.store = SessionStore() app.state.manager = StateManager( nlu_engine=engine, use_llm_paraphrase=use_paraphrase ) logger.info( "PayParse started (engine=%s, llm_followup=%s)", type(engine).__name__, use_paraphrase, ) yield app.state.store.close()
app = FastAPI( title="PayParse — Indonesian NLU Voice Assistant", description=( "Zero-shot LLM NLU (Gemini Flash) + slot-filling state machine " "for Indonesian financial voice queries." ), version="1.0.0", lifespan=lifespan,)
# CORS — allow the Android app (and any local dev client) to call the API.app.add_middleware( CORSMiddleware, allow_origins=["*"], # portfolio project; tighten for production allow_methods=["GET", "POST", "DELETE", "OPTIONS"], allow_headers=["*"],)
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
@app.get("/")def serve_ui(): """Serve the simple chat UI, or API info if static dir is missing.""" index = STATIC_DIR / "index.html" if index.exists(): return FileResponse(index) return { "name": "PayParse — Indonesian NLU Voice Assistant", "endpoints": { "chat": "POST /api/chat", "reset": "DELETE /api/session/{id}", "health": "GET /health", }, "docs": "/docs", }
@app.get("/health")def health() -> dict: return { "status": "ok", "engine": type(app.state.engine).__name__, "offline_mode": isinstance(app.state.engine, MockNLUEngine), }
@app.post("/api/chat", response_model=ChatResponse)def chat(request: ChatRequest) -> ChatResponse: """Process one user turn in a (possibly multi-turn) conversation.""" store: SessionStore = app.state.store state = store.get_or_create(request.session_id)
nlu_result = app.state.engine.extract(request.message, state=state) logger.info( "session=%s intent=%s entities=%s", request.session_id, nlu_result.intent.value, nlu_result.entities.model_dump(exclude_none=True), )
result = app.state.manager.process( state, nlu_result, request.message, request.resolve_contacts_locally ) store.save(result.state)
# A completed transaction ends the session; a fresh one starts next turn. if result.is_complete: store.delete(request.session_id)
return ChatResponse( session_id=request.session_id, reply=result.reply, intent=result.state.intent, is_complete=result.is_complete, missing_slots=result.state.missing_slots, payload=result.payload, needs_contact_resolution=result.needs_contact_resolution, target_kontak=result.target_kontak, )
@app.delete("/api/session/{session_id}")def reset_session(session_id: str) -> dict: """Discard a conversation so the user can start over.""" deleted = app.state.store.delete(session_id) if not deleted: raise HTTPException(status_code=404, detail="Session not found.") return {"status": "reset", "session_id": session_id}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417"""ner_extractor.py----------------Rule-based Named Entity Recognition (NER) layer for Indonesian financialutterances. Runs BEFORE the LLM call as a "pre-scan" to:
1. Extract entities the LLM might miss (robust regex + slang dictionary).2. Validate LLM output against NER findings (cross-check).3. Serve as fallback when the LLM is rate-limited.
This is NOT a replacement for the LLM — it's a safety net that catcheshigh-confidence entities (amounts, phone numbers, PLN IDs) that havedeterministic patterns, leaving ambiguous entities (contact names,intent) to the LLM.
Extraction capabilities:- Amounts: slang (goceng, ceban, gocap, cepek, seceng, sejuta) + numeric (50rb, 100.000, 2jt, 75 ribu).- Phone numbers: 08xxxxxxxxxx, +62xxxxxxxxxx, 628xxxxxxxxxx.- PLN customer IDs: 8-12 digit sequences.- Contact names: pattern "ke/buat/untuk [name]" with honorific stripping.- Intent keywords: transfer/pulsa/listrik with typo tolerance."""
from __future__ import annotations
import refrom dataclasses import dataclass, fieldfrom typing import Optional
from schema import IntentType, TransactionEntities
# ---------------------------------------------------------------------------# Indonesian financial slang → integer amount# ---------------------------------------------------------------------------SLANG_AMOUNTS: dict[str, int] = { "goceng": 5_000, "ceban": 10_000, "gocap": 50_000, "cepek": 100_000, "seceng": 1_000, "sejuta": 1_000_000, "sejutaan": 1_000_000, "gocengan": 5_000, "cebuan": 10_000, "gocapan": 50_000, "cepekan": 100_000, "secengan": 1_000,}
# Numeric abbreviations: "50rb", "100ribu", "2jt", "75 k"NUMERIC_ABBREV = { "rb": 1_000, "ribu": 1_000, "k": 1_000, "jt": 1_000_000, "juta": 1_000_000, "jutaan": 1_000_000,}
# Intent keywords with common typosINTENT_KEYWORDS: dict[IntentType, list[str]] = { IntentType.TRANSFER_UANG: [ "transfer", "trasnfer", "tf", "kirim", "kirimin", "kirimin", "transferin", "ngirim", "ngirimin", "send", "kirim uang", ], IntentType.BELI_PULSA: [ "pulsa", "pusla", "pls", "isi pulsa", "isiin pulsa", "beli pulsa", "beliin pulsa", "isiin", "top up pulsa", "isipulsa", ], IntentType.BAYAR_PLN: [ "listrik", "pln", "bayar listrik", "tagihan listrik", "listrik id", "bayar pln", "token listrik", "tagihan pln", "tagihan listrik saya", "bayar tagihan pln", "bayar tagihan listrik", "listrik saya", "bayar tagihan pln saya", ], IntentType.PESAN_GOJEK: [ "gojek", "go jek", "pesan gojek", "order gojek", "booking gojek", "goride", "go ride", "naik gojek", "call gojek", ], IntentType.PESAN_GOFOOD: [ "gofood", "go food", "pesan gofood", "order gofood", "booking gofood", "beli makanan", "pesan makan", "beli makan", ],}
# Honorifics to strip from contact namesHONORIFICS = {"si", "bang", "mbak", "pak", "bu", "mas", "mbah", "kak", "ade", "adik"}
# ---------------------------------------------------------------------------# NER result# ---------------------------------------------------------------------------@dataclassclass NERResult: """Entities extracted by the rule-based NER layer."""
intent: Optional[IntentType] = None amount: Optional[int] = None phone_number: Optional[str] = None recipient_phone: Optional[str] = None recipient: Optional[str] = None target_kontak: Optional[str] = None customer_id: Optional[str] = None provider: Optional[str] = None asal: Optional[str] = None tujuan: Optional[str] = None makanan: Optional[str] = None confidence: float = 0.0 """Which fields were extracted (for merge logic).""" extracted_fields: set[str] = field(default_factory=set)
def to_entities(self) -> TransactionEntities: return TransactionEntities( recipient=self.recipient, recipient_phone=self.recipient_phone, amount=self.amount, phone_number=self.phone_number, target_kontak=self.target_kontak, customer_id=self.customer_id, provider=self.provider, asal=self.asal, tujuan=self.tujuan, makanan=self.makanan, )
# ---------------------------------------------------------------------------# Extractor# ---------------------------------------------------------------------------class NERExtractor: """Rule-based NER for Indonesian financial utterances."""
def extract(self, text: str) -> NERResult: lowered = text.lower().strip() result = NERResult()
# --- Intent classification (keyword + typo tolerant) --- result.intent = self._classify_intent(lowered) if result.intent is not None: result.extracted_fields.add("intent") result.confidence = 0.7
# --- Amount extraction --- amount = self._extract_amount(lowered) if amount is not None: result.amount = amount result.extracted_fields.add("amount")
# --- Phone number extraction --- phone = self._extract_phone_number(lowered) if phone is not None: # Assign to the right field based on intent if result.intent == IntentType.TRANSFER_UANG: result.recipient_phone = phone result.extracted_fields.add("recipient_phone") else: result.phone_number = phone result.extracted_fields.add("phone_number")
# --- PLN customer ID --- if result.intent == IntentType.BAYAR_PLN: cust_id = self._extract_customer_id(lowered) if cust_id is not None: result.customer_id = cust_id result.extracted_fields.add("customer_id")
# --- Contact name / recipient --- if result.intent in (IntentType.TRANSFER_UANG, IntentType.BELI_PULSA): contact = self._extract_contact_name(lowered) if contact is not None: if result.intent == IntentType.TRANSFER_UANG: result.recipient = contact if result.recipient_phone is None: result.target_kontak = contact result.extracted_fields.add("target_kontak") result.extracted_fields.add("recipient") else: # beli_pulsa: only set target_kontak if no phone digits if result.phone_number is None: result.target_kontak = contact result.extracted_fields.add("target_kontak")
# --- Provider (telco) --- provider = self._extract_provider(lowered) if provider is not None: result.provider = provider result.extracted_fields.add("provider")
# --- Gojek: extract tujuan (destination) --- if result.intent == IntentType.PESAN_GOJEK: tujuan = self._extract_tujuan(lowered) if tujuan is not None: result.tujuan = tujuan result.extracted_fields.add("tujuan") # Asal defaults to Bogor; extract if "dari X" is mentioned asal = self._extract_asal(lowered) if asal is not None: result.asal = asal result.extracted_fields.add("asal")
# --- GoFood: extract makanan (food item) --- if result.intent == IntentType.PESAN_GOFOOD: makanan = self._extract_makanan(lowered) if makanan is not None: result.makanan = makanan result.extracted_fields.add("makanan")
return result
# ------------------------------------------------------------------ # Intent classification # ------------------------------------------------------------------ @staticmethod def _classify_intent(lowered: str) -> Optional[IntentType]: # Check each intent's keywords (including typos) for intent, keywords in INTENT_KEYWORDS.items(): for kw in keywords: if kw in lowered: return intent return None
# ------------------------------------------------------------------ # Amount extraction # ------------------------------------------------------------------ @staticmethod def _extract_amount(lowered: str) -> Optional[int]: # 1. Slang amounts (highest priority) for slang, value in SLANG_AMOUNTS.items(): if slang in lowered: return value
# 2. Numeric + abbreviation: "50rb", "100 ribu", "2jt", "75k" m = re.search(r"(\d+(?:[.,]\d+)?)\s*(rb|ribu|k|jt|juta|jutaan)\b", lowered) if m: base = float(m.group(1).replace(",", ".")) mult = NUMERIC_ABBREV.get(m.group(2), 1) return int(base * mult)
# 3. Plain large number: "50000", "100000" (but not phone numbers) m = re.search(r"\b(\d{4,9})\b(?!\s*(?:rb|ribu|k|jt|juta))", lowered) if m and not m.group(1).startswith("08"): value = int(m.group(1)) if 500 <= value <= 100_000_000: return value
# 4. "seratus ribu", "lima puluh ribu" (word-based, basic) word_amounts = { "seratus ribu": 100_000, "lima puluh ribu": 50_000, "sepuluh ribu": 10_000, "dua puluh ribu": 20_000, "tiga puluh ribu": 30_000, "empat puluh ribu": 40_000, "tujuh puluh ribu": 70_000, "delapan puluh ribu": 80_000, "sembilan puluh ribu": 90_000, "seribu": 1_000, "dua ribu": 2_000, "lima ribu": 5_000, } for phrase, value in word_amounts.items(): if phrase in lowered: return value
return None
# ------------------------------------------------------------------ # Phone number extraction # ------------------------------------------------------------------ @staticmethod def _extract_phone_number(lowered: str) -> Optional[str]: # Match 08xxxxxxxxxx (9-13 digits), +62xxxxxxxxxx, 62xxxxxxxxxx patterns = [ r"\b08\d{8,12}\b", r"\+62\d{8,12}\b", r"\b62\d{8,12}\b", ] for pat in patterns: m = re.search(pat, lowered) if m: digits = re.sub(r"\D", "", m.group()) # Normalize +62 / 62 to 08 if digits.startswith("62"): digits = "0" + digits[2:] return digits return None
# ------------------------------------------------------------------ # PLN customer ID # ------------------------------------------------------------------ @staticmethod def _extract_customer_id(lowered: str) -> Optional[str]: # PLN IDs are typically 8-12 digits, often starting with 4 or 5 m = re.search(r"\b(\d{8,12})\b", lowered) if m: return m.group(1) return None
# ------------------------------------------------------------------ # Contact name extraction # ------------------------------------------------------------------ @staticmethod def _extract_contact_name(lowered: str) -> Optional[str]: # Pronouns for pronoun in ("nomor ini", "nomer ini", "nomorku", "nomerku", "nomor saya"): if pronoun in lowered: return pronoun
# "ke [name]", "buat [name]", "untuk [name]" with optional honorific m = re.search( r"\b(?:ke|buat|untuk)\s+(?:(?:si|bang|mbak|pak|bu|mas|mbah|kak|ade|adik)\s+)?([a-z]+)", lowered, ) if m: name = m.group(1) if name not in {"nomor", "nomer", "hp", "rekening", "pulsa", "aku", "saya", "ini"}: return name.capitalize()
# "beliin [name] pulsa", "isiin [name] pulsa" m = re.search( r"\b(?:beliin|isiin|isi|beli)\s+([a-z]+)\s+pulsa", lowered, ) if m and m.group(1) not in {"pulsa", "nomor", "nomer"}: return m.group(1).capitalize()
return None
# ------------------------------------------------------------------ # Telco provider # ------------------------------------------------------------------ @staticmethod def _extract_provider(lowered: str) -> Optional[str]: providers = { "telkomsel": "Telkomsel", "kartu as": "Telkomsel", "xl": "XL", "axis": "XL", "indosat": "Indosat", "im3": "Indosat", "mentari": "Indosat", "tri": "Tri", "smartfren": "Smartfren", } for key, value in providers.items(): if key in lowered: return value return None
# ------------------------------------------------------------------ # Gojek destination # ------------------------------------------------------------------ @staticmethod def _extract_tujuan(lowered: str) -> Optional[str]: # "gojek ke stasiun", "gojek ke bandara", "gojek ke mall botani" m = re.search(r"\bgojek\s+(?:ke|buat|untuk)\s+(.+?)(?:\s*$|\s*dari\s)", lowered) if m: dest = m.group(1).strip() if dest and dest not in {"dari", "ke", "buat"}: return dest.capitalize() # "pesan gojek ke X" m = re.search(r"\bpesan\s+gojek\s+(?:ke|buat|untuk)\s+(.+?)(?:\s*$|\s*dari\s)", lowered) if m: dest = m.group(1).strip() if dest: return dest.capitalize() # "gojek X" (without "ke") m = re.search(r"\bgojek\s+([a-z][a-z\s]+)", lowered) if m: dest = m.group(1).strip() # Exclude if it's just "ke" or intent keywords if dest and dest not in {"ke", "dari", "pesan", "order"}: return dest.capitalize() return None
# ------------------------------------------------------------------ # Gojek origin # ------------------------------------------------------------------ @staticmethod def _extract_asal(lowered: str) -> Optional[str]: # "dari bogor", "dari stasiun" m = re.search(r"\bdari\s+([a-z][a-z\s]+?)(?:\s+ke\s|$)", lowered) if m: origin = m.group(1).strip() if origin: return origin.capitalize() return None
# ------------------------------------------------------------------ # GoFood food item # ------------------------------------------------------------------ @staticmethod def _extract_makanan(lowered: str) -> Optional[str]: # "gofood nasi goreng", "pesan gofood ayam geprek" m = re.search(r"\bgofood\s+(.+?)(?:\s*$)", lowered) if m: food = m.group(1).strip() if food and food not in {"pesan", "order", "beli", "mau"}: return food.capitalize() m = re.search(r"\bpesan\s+gofood\s+(.+?)(?:\s*$)", lowered) if m: food = m.group(1).strip() if food: return food.capitalize() # "beli makan nasi goreng", "pesan makan ayam" m = re.search(r"\b(?:beli|pesan)\s+makan(?:an)?\s+(.+?)(?:\s*$)", lowered) if m: food = m.group(1).strip() if food: return food.capitalize() return None
# Singleton instancener_extractor = NERExtractor()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476"""nlu_engine.py-------------LLM-based NLU engine for PayParse.
- `NLUEngine` : zero-shot Gemini Flash with strict Pydantic structured output (`response_schema=NLUResult`), slang-aware prompt, dialogue-context injection, retries, graceful fallback.- `MockNLUEngine` : deterministic rule-based engine with the same interface, used for offline evaluation / running without an API key."""
from __future__ import annotations
import loggingimport osimport reimport timefrom typing import Optional, Protocol
from dotenv import load_dotenv
from schema import DialogueState, IntentType, NLUResult, TransactionEntitiesfrom ner_extractor import ner_extractor, NERResult
load_dotenv()logger = logging.getLogger(__name__)
MODEL_NAME = os.getenv("PAYPARSE_MODEL", "gemini-flash-lite-latest")
# ---------------------------------------------------------------------------# NER + LLM merge: NER fills gaps the LLM missed, LLM wins on conflicts.# ---------------------------------------------------------------------------def _merge_ner_with_llm(ner: NERResult, llm: NLUResult) -> NLUResult: """Merge NER pre-scan with LLM output.
Strategy: - Intent: LLM wins (more context-aware). NER only used as fallback. - Amount: NER wins if LLM missed it (NER is deterministic for amounts). - Phone/recipient_phone: NER wins if LLM missed it. - recipient/target_kontak: LLM wins (name extraction is ambiguous). - customer_id: NER wins if LLM missed it. - provider: NER wins if LLM missed it. """ e_llm = llm.entities fields = ner.extracted_fields
# Amount: NER fills gap if "amount" in fields and e_llm.amount is None and ner.amount is not None: e_llm.amount = ner.amount logger.info("NER filled amount=%d", ner.amount)
# Phone number: NER fills gap if "phone_number" in fields and e_llm.phone_number is None and ner.phone_number is not None: e_llm.phone_number = ner.phone_number logger.info("NER filled phone_number=%s", ner.phone_number)
# Recipient phone: NER fills gap if "recipient_phone" in fields and e_llm.recipient_phone is None and ner.recipient_phone is not None: e_llm.recipient_phone = ner.recipient_phone logger.info("NER filled recipient_phone=%s", ner.recipient_phone)
# Customer ID: NER fills gap if "customer_id" in fields and e_llm.customer_id is None and ner.customer_id is not None: e_llm.customer_id = ner.customer_id logger.info("NER filled customer_id=%s", ner.customer_id)
# Provider: NER fills gap if "provider" in fields and e_llm.provider is None and ner.provider is not None: e_llm.provider = ner.provider logger.info("NER filled provider=%s", ner.provider)
# Target kontak: NER fills gap (only if LLM didn't extract it and no phone) if ( "target_kontak" in fields and e_llm.target_kontak is None and ner.target_kontak is not None and e_llm.phone_number is None and e_llm.recipient_phone is None ): e_llm.target_kontak = ner.target_kontak if e_llm.recipient is None and ner.recipient is not None: e_llm.recipient = ner.recipient logger.info("NER filled target_kontak=%s", ner.target_kontak)
# Recipient: NER fills gap if "recipient" in fields and e_llm.recipient is None and ner.recipient is not None: e_llm.recipient = ner.recipient logger.info("NER filled recipient=%s", ner.recipient)
# Tujuan (Gojek destination): NER fills gap if "tujuan" in fields and e_llm.tujuan is None and ner.tujuan is not None: e_llm.tujuan = ner.tujuan logger.info("NER filled tujuan=%s", ner.tujuan)
# Asal (Gojek origin): NER fills gap if "asal" in fields and e_llm.asal is None and ner.asal is not None: e_llm.asal = ner.asal logger.info("NER filled asal=%s", ner.asal)
# Makanan (GoFood item): NER fills gap if "makanan" in fields and e_llm.makanan is None and ner.makanan is not None: e_llm.makanan = ner.makanan logger.info("NER filled makanan=%s", ner.makanan)
# Bump confidence if NER agrees with LLM if ner.intent is not None and ner.intent == llm.intent: llm.confidence = min(1.0, llm.confidence + 0.05)
return llm
# ---------------------------------------------------------------------------# System prompt: the heart of the zero-shot NLU# ---------------------------------------------------------------------------SYSTEM_PROMPT = """\Kamu adalah mesin NLU (Natural Language Understanding) untuk asisten suaradompet digital Indonesia (seperti GoPay). Tugasmu HANYA mengekstrak intentdan entities dari ucapan pengguna, lalu mengembalikan JSON sesuai skema.
## INTENT yang didukung:1. "transfer_uang" : kirim/transfer uang ke seseorang. Kata kunci: transfer, tf, kirim, kirimin, transferin, kasih uang.2. "beli_pulsa" : beli pulsa / isi ulang / top-up pulsa ke nomor HP. Kata kunci: pulsa, isi pulsa, top up, isiin.3. "bayar_pln" : bayar tagihan listrik PLN / beli token listrik. Kata kunci: listrik, PLN, token, tagihan listrik, tagihan pln, meteran.4. "pesan_gojek" : pesan ojek/ride Gojek dari asal ke tujuan. Kata kunci: gojek, go jek, goride, naik gojek, pesan gojek. Entity "asal" default "Bogor" jika tidak disebut. Entity "tujuan" adalah lokasi tujuan (stasiun, bandara, mall, dll).5. "pesan_gofood" : pesan makanan via GoFood. Kata kunci: gofood, go food, pesan makan, beli makan. Entity "makanan" adalah nama makanan (nasi goreng, ayam geprek, dll).6. "unknown" : semua permintaan di luar 5 intent di atas (contoh: tanya cuaca, ngobrol basa-basi).
## NORMALISASI SLANG UANG (WAJIB dikonversi ke integer Rupiah):- "seceng" / "seribu" = 1000- "goceng" = 5000- "ceban" = 10000- "noban" = 20000- "gocap" / "gopek ribu"? -> "gocap" = 50000, "gopek" = 500- "cepek" = 100 (uang: biasanya maksudnya "cepek ribu" = 100000 jika konteksnya transfer/pulsa; gunakan 100000 untuk konteks transaksi)- "seket" (Jawa) = 50 -> "seket ewu" = 50000- "sejuta" / "1jt" / "1 juta" = 1000000- "50rb" / "50ribu" / "50k" = 50000- "2,5jt" / "2.5 juta" = 2500000
## ATURAN PENTING:- Pengguna sering typo ("pusla" = pulsa, "trasnfer" = transfer) dan memakai bahasa lisan tidak baku. Tetap pahami maksudnya.- HANYA ekstrak entity yang DISEBUT EKSPLISIT oleh pengguna. JANGAN PERNAH mengarang/menebak nilai yang tidak diucapkan. Jika tidak disebut, biarkan null.- "recipient" adalah nama orang penerima transfer (budi, mama, bang jono).- "recipient_phone" adalah nomor HP penerima transfer, HANYA jika pengguna menyebutkan DIGIT ANGKA secara eksplisit. Jangan pernah mengarang digit.- "phone_number" adalah nomor HP tujuan pulsa, HANYA jika pengguna menyebutkan DIGIT ANGKA secara eksplisit.- "target_kontak" dipakai jika pengguna merujuk nomor HP secara TIDAK LANGSUNG: * lewat nama kontak: "beliin anton pulsa" -> target_kontak = "anton" * lewat nama kontak transfer: "tf ke budi" -> recipient = "budi", target_kontak = "budi" * lewat kata ganti : "isi ke nomor ini", "nomorku" -> target_kontak = "nomor ini" / "nomorku" Dalam kasus ini "phone_number" dan "recipient_phone" WAJIB null — jangan pernah mengarang digit. Sebaliknya, jika digit sudah disebut, "target_kontak" biarkan null.
Contoh: Ucapan: "beliin anton pulsa 10rb" -> {"intent": "beli_pulsa", "entities": {"amount": 10000, "phone_number": null, "target_kontak": "anton"}} Ucapan: "tf 50rb ke budi" -> {"intent": "transfer_uang", "entities": {"recipient": "budi", "recipient_phone": null, "target_kontak": "budi", "amount": 50000}} Ucapan: "transfer ke 081234567890 100rb" -> {"intent": "transfer_uang", "entities": {"recipient_phone": "081234567890", "recipient": null, "target_kontak": null, "amount": 100000}} Ucapan: "gojek ke stasiun" -> {"intent": "pesan_gojek", "entities": {"asal": null, "tujuan": "stasiun"}} Ucapan: "gofood nasi goreng" -> {"intent": "pesan_gofood", "entities": {"makanan": "nasi goreng"}}- "customer_id" adalah nomor ID pelanggan / meteran PLN (hanya digit).- Nomor yang diawali 08 kemungkinan besar phone_number, bukan customer_id.- Jika pengguna sedang menjawab pertanyaan lanjutan (lihat KONTEKS DIALOG), jawaban singkat seperti "buat budi" atau "50rb" adalah pengisian slot untuk intent yang SEDANG BERJALAN — pertahankan intent tersebut.- PENTING: entity yang SUDAH terisi di KONTEKS DIALOG JANGAN diulang lagi di output "entities" kecuali pengguna benar-benar menyebutkannya ulang di UCAPAN saat ini. Field "entities" HANYA berisi hal baru yang disebut di UCAPAN PENGGUNA sekarang, bukan salinan dari konteks.- "normalized_text": tulis ulang ucapan dalam bahasa Indonesia baku dan rapi.- "confidence": estimasi keyakinanmu terhadap intent (0.0 - 1.0)."""
def _build_context_block(state: Optional[DialogueState]) -> str: """Render the current dialogue state so short follow-up answers ("buat budi", "50rb") are resolved against the ongoing intent.""" if state is None or state.intent == IntentType.UNKNOWN: return "" filled = { k: v for k, v in state.entities.model_dump().items() if v is not None } return ( "\n## KONTEKS DIALOG (percakapan sedang berjalan):\n" f"- Intent aktif: {state.intent.value}\n" f"- Entity yang sudah terisi: {filled or 'belum ada'}\n" f"- Slot yang masih ditanyakan: {state.missing_slots}\n" "Ucapan berikut kemungkinan adalah jawaban untuk slot yang ditanyakan.\n" )
class BaseNLUEngine(Protocol): """Common interface so the API/eval can swap live and mock engines."""
def extract(self, text: str, state: Optional[DialogueState] = None) -> NLUResult: ...
# ---------------------------------------------------------------------------# Live Gemini engine# ---------------------------------------------------------------------------class NLUEngine: """Gemini-backed NLU with strict structured output."""
def __init__(self, api_key: Optional[str] = None, max_retries: int = 2): from google import genai # imported lazily so mock mode needs no key
api_key = api_key or os.getenv("GEMINI_API_KEY") if not api_key: raise ValueError( "GEMINI_API_KEY not set. Export it or add it to a .env file." ) self._client = genai.Client(api_key=api_key) self._max_retries = max_retries
def extract(self, text: str, state: Optional[DialogueState] = None) -> NLUResult: """Run zero-shot extraction with NER pre-scan.
Pipeline: NER pre-scan → LLM extraction → merge (NER fills gaps the LLM missed, LLM wins on conflicts for ambiguous fields).
Returns an `unknown` NLUResult on failure so the pipeline degrades gracefully instead of crashing. """ from google.genai import types
# --- NER pre-scan (rule-based, zero latency) --- ner = ner_extractor.extract(text) logger.info("NER pre-scan: %s", ner.extracted_fields)
prompt = _build_context_block(state) + f'\n## UCAPAN PENGGUNA:\n"{text}"' config = types.GenerateContentConfig( system_instruction=SYSTEM_PROMPT, response_mime_type="application/json", response_schema=NLUResult, temperature=0.0, )
for attempt in range(self._max_retries + 1): try: response = self._client.models.generate_content( model=MODEL_NAME, contents=prompt, config=config ) # SDK parses straight into the Pydantic model when # response_schema is a BaseModel subclass. llm_result = response.parsed or NLUResult.model_validate_json(response.text) return _merge_ner_with_llm(ner, llm_result) except Exception as exc: # network, rate limit, malformed JSON logger.warning("NLU attempt %d failed: %s", attempt + 1, exc) if attempt < self._max_retries: time.sleep(2 ** attempt) # 1s, 2s backoff
# --- Fallback: use NER result if LLM fails entirely --- if ner.intent is not None: logger.info("LLM failed — falling back to NER result.") return NLUResult( intent=ner.intent, entities=ner.to_entities(), confidence=ner.confidence, normalized_text=text, )
logger.error("NLU extraction failed after retries; returning unknown.") return NLUResult(intent=IntentType.UNKNOWN, normalized_text=text)
def paraphrase(self, question: str) -> str: """Optionally rephrase a templated follow-up question into a more natural, friendly sentence (hybrid follow-up generation).""" try: response = self._client.models.generate_content( model=MODEL_NAME, contents=( "Tulis ulang pertanyaan asisten dompet digital berikut agar " "terdengar ramah dan natural dalam bahasa Indonesia santai. " "Balas HANYA dengan satu kalimat pertanyaannya saja.\n" f"Pertanyaan: {question}" ), ) return (response.text or question).strip() except Exception as exc: logger.warning("Paraphrase failed, using template: %s", exc) return question
# ---------------------------------------------------------------------------# Offline mock engine (rule-based)# ---------------------------------------------------------------------------_SLANG_AMOUNTS = { "seceng": 1_000, "seribu": 1_000, "goceng": 5_000, "ceban": 10_000, "noban": 20_000, "gocap": 50_000, "cepek": 100_000, # transactional context "sejuta": 1_000_000,}
_INTENT_KEYWORDS = { IntentType.BELI_PULSA: ["pulsa", "pusla", "top up", "topup", "isi ulang", "isiin"], IntentType.BAYAR_PLN: ["listrik", "pln", "token", "meteran", "tagihan pln", "tagihan listrik"], IntentType.TRANSFER_UANG: [ "transfer", "trasnfer", "tf", "kirim", "kirimin", "transferin", "kasih", "beri" ], IntentType.PESAN_GOJEK: ["gojek", "go jek", "goride", "go ride"], IntentType.PESAN_GOFOOD: ["gofood", "go food", "pesan makan", "beli makan"],}
class MockNLUEngine: """Deterministic keyword/regex NLU with the same interface as `NLUEngine`. Good enough to exercise the state machine and run tests offline — NOT a substitute for the LLM's robustness."""
def extract(self, text: str, state: Optional[DialogueState] = None) -> NLUResult: lowered = f" {text.lower()} " intent = self._classify(lowered, state) entities = self._extract_entities(lowered, intent) return NLUResult( intent=intent, entities=entities, confidence=0.5 if intent == IntentType.UNKNOWN else 0.9, normalized_text=text, )
def paraphrase(self, question: str) -> str: return question # mock: templates pass through unchanged
def _classify(self, lowered: str, state: Optional[DialogueState]) -> IntentType: for intent, keywords in _INTENT_KEYWORDS.items(): if any(f" {kw} " in lowered or lowered.strip().startswith(kw) for kw in keywords): return intent # Short answers during slot filling keep the active intent if state is not None and state.intent != IntentType.UNKNOWN: return state.intent return IntentType.UNKNOWN
def _extract_entities( self, lowered: str, intent: IntentType ) -> TransactionEntities: entities = TransactionEntities() if intent == IntentType.UNKNOWN: return entities
entities.amount = self._parse_amount(lowered)
# Phone numbers (start with 08, 9-13 digits) vs PLN customer IDs numbers = re.findall(r"\b(\d[\d\-\s]{7,15}\d)\b", lowered) for raw in numbers: digits = re.sub(r"\D", "", raw) if digits.startswith("08") and 9 <= len(digits) <= 13: entities.phone_number = digits elif intent == IntentType.BAYAR_PLN: entities.customer_id = digits
if intent == IntentType.TRANSFER_UANG: # If raw digits were mentioned, fill recipient_phone if entities.phone_number is not None: entities.recipient_phone = entities.phone_number entities.phone_number = None # Extract recipient name m = re.search( r"\b(?:ke|buat|untuk)\s+(?:(?:si|bang|mbak|pak|bu)\s+)?([a-z]+)", lowered, ) if m and m.group(1) not in {"nomor", "rekening", "hp"}: entities.recipient = m.group(1).capitalize() # If no raw digits, fill target_kontak for resolution if entities.recipient_phone is None: entities.target_kontak = entities.recipient
# Indirect phone reference: contact name or pronoun instead of digits if intent == IntentType.BELI_PULSA and entities.phone_number is None: entities.target_kontak = self._parse_contact(lowered)
# --- Gojek: extract tujuan --- if intent == IntentType.PESAN_GOJEK: m = re.search(r"\bgojek\s+(?:ke|buat|untuk)\s+(.+?)(?:\s+dari\s|$)", lowered) if m: dest = m.group(1).strip() # Strip filler words dest = re.sub(r"\s+(?:dong|sih|deh|nih|aja|ya|yah)$", "", dest).strip() if dest: entities.tujuan = dest.capitalize() else: m = re.search(r"\bgojek\s+([a-z][a-z\s]+)", lowered) if m and m.group(1).strip() not in {"ke", "dari", "pesan"}: dest = m.group(1).strip() dest = re.sub(r"\s+(?:dong|sih|deh|nih|aja|ya|yah)$", "", dest).strip() if dest: entities.tujuan = dest.capitalize() # Asal: "dari X" or default Bogor m = re.search(r"\bdari\s+([a-z][a-z\s]+?)(?:\s+ke\s|$)", lowered) if m: entities.asal = m.group(1).strip().capitalize()
# --- GoFood: extract makanan --- if intent == IntentType.PESAN_GOFOOD: m = re.search(r"\bgofood\s+(.+?)(?:\s*$)", lowered) if m: food = m.group(1).strip() if food not in {"pesan", "order", "beli", "mau"}: entities.makanan = food.capitalize() else: m = re.search(r"\b(?:beli|pesan)\s+makan(?:an)?\s+(.+?)(?:\s*$)", lowered) if m: entities.makanan = m.group(1).strip().capitalize()
return entities
@staticmethod def _parse_contact(lowered: str) -> Optional[str]: """Detect pronouns ('nomorku', 'nomor ini') or a contact name.""" for pronoun in ("nomor ini", "nomer ini", "nomorku", "nomerku", "nomor saya"): if pronoun in lowered: return pronoun # "isi ke anton", "beliin anton pulsa" m = re.search(r"\b(?:ke|buat|untuk)\s+([a-z]+)", lowered) if m and m.group(1) not in {"nomor", "nomer", "hp", "pulsa", "aku", "saya"}: return m.group(1) m = re.search(r"\b(?:beliin|isiin|isi|beli)\s+([a-z]+)\s+pulsa", lowered) if m and m.group(1) not in {"pulsa", "nomor", "nomer"}: return m.group(1) return None
@staticmethod def _parse_amount(lowered: str) -> Optional[int]: for slang, value in _SLANG_AMOUNTS.items(): if slang in lowered: return value m = re.search(r"(\d+(?:[.,]\d+)?)\s*(rb|ribu|k|jt|juta)\b", lowered) if m: base = float(m.group(1).replace(",", ".")) mult = 1_000 if m.group(2) in {"rb", "ribu", "k"} else 1_000_000 return int(base * mult) m = re.search(r"\b(\d{4,9})\b(?!\s*(?:rb|ribu|k|jt|juta))", lowered) if m and not m.group(1).startswith("08"): value = int(m.group(1)) if 500 <= value <= 100_000_000: return value return None
def create_engine(offline: bool = False) -> "BaseNLUEngine": """Factory: live Gemini engine, or mock when offline / no key present.""" if offline: return MockNLUEngine() try: return NLUEngine() except ValueError: logger.warning("No GEMINI_API_KEY found — falling back to MockNLUEngine.") return MockNLUEngine()123456google-genai>=1.16.0pydantic>=2.7fastapi>=0.111uvicorn>=0.30python-dotenv>=1.0gradio>=4.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247"""schema.py---------Pydantic data contracts for the PayParse NLU pipeline.
Defines:- Supported intents (`IntentType`)- Extracted transaction entities (`TransactionEntities`)- The strict NLU output schema enforced on Gemini (`NLUResult`)- The multi-turn dialogue state (`DialogueState`)- FastAPI request/response models (`ChatRequest`, `ChatResponse`)- The slot-filling contract (`REQUIRED_SLOTS`)"""
from __future__ import annotations
import refrom enum import Enumfrom typing import Optional
from pydantic import BaseModel, Field, field_validator
# ---------------------------------------------------------------------------# Intents# ---------------------------------------------------------------------------class IntentType(str, Enum): """Supported user intents (GoPay-style financial actions)."""
TRANSFER_UANG = "transfer_uang" # e.g. "tf goceng ke budi" BELI_PULSA = "beli_pulsa" # e.g. "beliin pulsa 25rb ke 0812..." BAYAR_PLN = "bayar_pln" # e.g. "bayar listrik id 4512..." PESAN_GOJEK = "pesan_gojek" # e.g. "gojek ke stasiun" PESAN_GOFOOD = "pesan_gofood" # e.g. "gofood nasi goreng" UNKNOWN = "unknown" # out-of-scope / unintelligible
# Slot-filling contract: which entity fields MUST be present per intent# before the transaction payload can be confirmed.REQUIRED_SLOTS: dict[IntentType, list[str]] = { IntentType.TRANSFER_UANG: ["recipient", "recipient_phone", "amount"], IntentType.BELI_PULSA: ["phone_number", "amount"], IntentType.BAYAR_PLN: ["customer_id"], IntentType.PESAN_GOJEK: ["tujuan"], IntentType.PESAN_GOFOOD: ["makanan"], IntentType.UNKNOWN: [],}
# ---------------------------------------------------------------------------# Entities# ---------------------------------------------------------------------------class TransactionEntities(BaseModel): """Entities extracted from a user utterance. All fields optional — the state machine decides what is still missing."""
recipient: Optional[str] = Field( default=None, description="Name of the transfer recipient, e.g. 'Budi', 'mama'.", ) recipient_phone: Optional[str] = Field( default=None, description=( "Phone number of the transfer recipient, digits only. " "Filled by the state manager after resolving target_kontak, " "or directly if the user dictates digits." ), ) amount: Optional[int] = Field( default=None, description=( "Amount in Indonesian Rupiah as an integer. " "Slang must be normalized: goceng=5000, ceban=10000, " "gocap=50000, cepek=100000, seceng=1000, '50rb'=50000, " "'sejuta'=1000000." ), ) phone_number: Optional[str] = Field( default=None, description="Destination phone number for pulsa top-up, digits only.", ) target_kontak: Optional[str] = Field( default=None, description=( "Contact name or pronoun used INSTEAD of raw digits when the user " "refers to a phone number indirectly, e.g. 'Anton', 'nomorku', " "'nomor ini'. Resolved to an actual number by the state manager." ), ) customer_id: Optional[str] = Field( default=None, description="PLN customer ID / meter number, digits only.", ) provider: Optional[str] = Field( default=None, description="Telco provider if mentioned, e.g. 'Telkomsel', 'XL'.", ) asal: Optional[str] = Field( default=None, description=( "Origin location for Gojek ride booking. " "Defaults to 'Bogor' if not specified by the user." ), ) tujuan: Optional[str] = Field( default=None, description=( "Destination location for Gojek ride booking, " "e.g. 'stasiun', 'bandara', 'mall botani'." ), ) makanan: Optional[str] = Field( default=None, description=( "Food item ordered via GoFood, " "e.g. 'nasi goreng', 'ayam geprek', 'mie ayam'." ), )
@field_validator("amount") @classmethod def amount_must_be_positive(cls, v: Optional[int]) -> Optional[int]: if v is not None and v <= 0: return None # discard nonsense amounts instead of erroring return v
@field_validator("phone_number", "customer_id", "recipient_phone") @classmethod def digits_only(cls, v: Optional[str]) -> Optional[str]: """Normalize '0812-3456 7890' -> '081234567890'; drop empty results.""" if v is None: return None digits = re.sub(r"\D", "", v) return digits or None
@field_validator("target_kontak") @classmethod def clean_contact(cls, v: Optional[str]) -> Optional[str]: """Trim whitespace; drop empty strings so lookups stay predictable.""" return v.strip() or None if v else None
def filled_fields(self) -> set[str]: """Names of fields that currently hold a value.""" return {k for k, v in self.model_dump().items() if v is not None}
def merge(self, new: "TransactionEntities") -> "TransactionEntities": """Non-destructive merge: new values fill gaps or override, but never erase an existing value with None.""" data = self.model_dump() for key, value in new.model_dump().items(): if value is not None: data[key] = value return TransactionEntities(**data)
# ---------------------------------------------------------------------------# NLU output (strict schema enforced on Gemini structured output)# ---------------------------------------------------------------------------class NLUResult(BaseModel): """Single-turn NLU extraction result returned by the LLM."""
intent: IntentType = Field(description="The classified user intent.") entities: TransactionEntities = Field( default_factory=TransactionEntities, description="Entities explicitly stated in the utterance. " "Never invent values that were not said.", ) confidence: float = Field( default=0.0, ge=0.0, le=1.0, description="Model self-estimated confidence in the intent (0-1).", ) normalized_text: str = Field( default="", description="The utterance rewritten in clean formal Indonesian " "with slang and typos resolved.", )
# ---------------------------------------------------------------------------# Dialogue state (multi-turn)# ---------------------------------------------------------------------------class DialogueStatus(str, Enum): COLLECTING = "collecting" # waiting for missing slots CONFIRMING = "confirming" # all slots filled, awaiting user's ya/tidak COMPLETE = "complete" # confirmed, payload released UNKNOWN = "unknown" # out-of-scope query
class DialogueState(BaseModel): """Persistent state of one conversation session."""
session_id: str intent: IntentType = IntentType.UNKNOWN entities: TransactionEntities = Field(default_factory=TransactionEntities) missing_slots: list[str] = Field(default_factory=list) status: DialogueStatus = DialogueStatus.UNKNOWN turn_count: int = 0 history: list[str] = Field( default_factory=list, description="Raw user utterances in order, for LLM context.", )
# ---------------------------------------------------------------------------# API models# ---------------------------------------------------------------------------class ChatRequest(BaseModel): session_id: str = Field(min_length=1, description="Client-chosen session key.") message: str = Field(min_length=1, description="Raw user utterance.") resolve_contacts_locally: bool = Field( default=False, description=( "When true (mobile client), the server will NOT look up its own " "contact directory and instead signal the client to resolve " "target_kontak into a phone number on-device." ), )
class ChatResponse(BaseModel): session_id: str reply: str = Field(description="Assistant reply (follow-up question or confirmation).") intent: IntentType is_complete: bool missing_slots: list[str] payload: Optional[dict] = Field( default=None, description="Final transaction payload, present only when complete.", ) needs_contact_resolution: bool = Field( default=False, description=( "True when the server asks the client to resolve target_kontak " "into a phone number on-device (mobile flow). The client should " "open a contact picker, find the number, then send it back as " "the next message." ), ) target_kontak: Optional[str] = Field( default=None, description=( "The contact name/pronoun the client should resolve, present " "only when needs_contact_resolution is true." ), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118"""session_store.py----------------Persistence for `DialogueState`, keyed by session_id.
Two backends:- SQLite (default for local / Render / Docker with persistent volume)- In-memory dict (for Hugging Face Spaces where the filesystem is ephemeral)
The backend is selected via the `PAYPARSE_SESSION_BACKEND` env var: "sqlite" (default) → SQLite file "memory" → in-memory dict (lost on restart, fine for a demo)"""
from __future__ import annotations
import osimport sqlite3import threadingfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Optional
from schema import DialogueState
DEFAULT_DB_PATH = Path(__file__).parent / "sessions.db"
_SCHEMA = """CREATE TABLE IF NOT EXISTS sessions ( session_id TEXT PRIMARY KEY, state_json TEXT NOT NULL, updated_at TEXT NOT NULL);"""
class SessionStore: """Thread-safe session store. Delegates to SQLite or in-memory dict."""
def __init__(self, db_path: Path | str = DEFAULT_DB_PATH): backend = os.getenv("PAYPARSE_SESSION_BACKEND", "sqlite").lower() self._lock = threading.Lock() if backend == "memory": self._backend = _MemoryBackend() else: self._backend = _SQLiteBackend(db_path)
def get(self, session_id: str) -> Optional[DialogueState]: return self._backend.get(session_id)
def get_or_create(self, session_id: str) -> DialogueState: return self.get(session_id) or DialogueState(session_id=session_id)
def save(self, state: DialogueState) -> None: self._backend.save(state)
def delete(self, session_id: str) -> bool: return self._backend.delete(session_id)
def close(self) -> None: self._backend.close()
class _SQLiteBackend: """SQLite-backed persistence (local / Render / Docker with volume)."""
def __init__(self, db_path: Path | str): self._conn = sqlite3.connect(str(db_path), check_same_thread=False) self._conn.execute(_SCHEMA) self._conn.commit()
def get(self, session_id: str) -> Optional[DialogueState]: row = self._conn.execute( "SELECT state_json FROM sessions WHERE session_id = ?", (session_id,), ).fetchone() return DialogueState.model_validate_json(row[0]) if row else None
def save(self, state: DialogueState) -> None: now = datetime.now(timezone.utc).isoformat() self._conn.execute( "INSERT INTO sessions (session_id, state_json, updated_at) " "VALUES (?, ?, ?) " "ON CONFLICT(session_id) DO UPDATE SET " "state_json = excluded.state_json, updated_at = excluded.updated_at", (state.session_id, state.model_dump_json(), now), ) self._conn.commit()
def delete(self, session_id: str) -> bool: cursor = self._conn.execute( "DELETE FROM sessions WHERE session_id = ?", (session_id,) ) self._conn.commit() return cursor.rowcount > 0
def close(self) -> None: self._conn.close()
class _MemoryBackend: """In-memory dict store (Hugging Face Spaces — ephemeral filesystem)."""
def __init__(self): self._data: dict[str, str] = {}
def get(self, session_id: str) -> Optional[DialogueState]: json_str = self._data.get(session_id) return DialogueState.model_validate_json(json_str) if json_str else None
def save(self, state: DialogueState) -> None: self._data[state.session_id] = state.model_dump_json()
def delete(self, session_id: str) -> bool: return self._data.pop(session_id, None) is not None
def close(self) -> None: pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465"""state_manager.py----------------Slot-filling state machine for PayParse.
Given the persistent `DialogueState` and a fresh `NLUResult`, this module:1. Intercepts ya/tidak answers when a transaction awaits confirmation.2. Merges newly extracted entities (non-destructively).3. Handles mid-dialogue intent switches.4. Resolves `target_kontak` (contact name / pronoun) into a real phone number BEFORE deciding which slots are still missing.5. Computes which required slots are still missing (`REQUIRED_SLOTS`).6. Produces the assistant reply: a follow-up question (template-based, with optional LLM paraphrase — "hybrid" mode), a confirmation summary, or the final transaction payload once the user says "ya"."""
from __future__ import annotations
import loggingimport refrom dataclasses import dataclassfrom typing import Optional
from schema import ( REQUIRED_SLOTS, DialogueState, DialogueStatus, IntentType, NLUResult, TransactionEntities,)
logger = logging.getLogger(__name__)
MAX_TURNS = 8 # guard against endless clarification loops
# ---------------------------------------------------------------------------# Contact directory (stub for a real address-book / contacts service)# Keys MUST be lowercase; lookups are done on `target_kontak.lower()`.# ---------------------------------------------------------------------------DUMMY_CONTACTS: dict[str, str] = { "anton": "081222333444", "budi": "08555666777", "nomorku": "08999888777", "nomor ini": "08999888777", "nomor saya": "08999888777",}
# Stub GoPay registration check — in production this would query the GoPay API.# Numbers in DUMMY_CONTACTS are "registered GoPay users"; others are not._GOPAY_REGISTERED_NUMBERS: set[str] = set(DUMMY_CONTACTS.values())
def check_gopay_status(phone_number: str) -> str: """Return 'Terdaftar GoPay' or 'Belum terdaftar GoPay' for a number.""" if phone_number in _GOPAY_REGISTERED_NUMBERS: return "Terdaftar GoPay" return "Belum terdaftar GoPay"
# Affirmative / negative tokens for the ya-tidak confirmation intercept_AFFIRMATIVE = { "ya", "iya", "y", "yes", "yoi", "yup", "oke", "ok", "okay", "sip", "siap", "lanjut", "lanjutkan", "gas", "boleh", "benar", "betul", "setuju", "bener",}_NEGATIVE = { "tidak", "ga", "gak", "engga", "enggak", "nggak", "ngga", "no", "n", "batal", "batalkan", "cancel", "jangan", "stop", "salah", "bukan",}# Filler / politeness words ignored when judging an affirmative answer, so# "ya udah" or "boleh dong" still count as a clear yes._FILLER = { "hmm", "hm", "eh", "em", "ehm", "oh", "anu", "nya", "itu", "dong", "sih", "deh", "nih", "aja", "saja", "udah", "sudah", "langsung", "makasih", "terima", "kasih", "kak", "bro", "gan", "min", "pak", "bu",}
# ---------------------------------------------------------------------------# Follow-up question templates per (intent, slot) — natural Indonesian# ---------------------------------------------------------------------------FOLLOW_UP_TEMPLATES: dict[tuple[IntentType, str], str] = { (IntentType.TRANSFER_UANG, "recipient"): "Mau transfer ke siapa?", (IntentType.TRANSFER_UANG, "recipient_phone"): "Berapa nomor GoPay {recipient}?", (IntentType.TRANSFER_UANG, "amount"): "Berapa jumlah yang mau ditransfer?", (IntentType.BELI_PULSA, "phone_number"): "Pulsanya mau diisi ke nomor HP berapa?", (IntentType.BELI_PULSA, "amount"): "Mau beli pulsa nominal berapa?", (IntentType.BAYAR_PLN, "customer_id"): "Boleh sebutkan nomor ID pelanggan PLN-nya?", (IntentType.PESAN_GOJEK, "tujuan"): "Mau pesan Gojek ke mana tujuannya?", (IntentType.PESAN_GOFOOD, "makanan"): "Mau pesan makanan apa di GoFood?",}
CONTACT_NOT_FOUND_TEMPLATE = ( "Maaf, nomor untuk {kontak} tidak ditemukan. Berapa nomor angkanya?")CONTACT_NOT_FOUND_GOPAY_TEMPLATE = ( "Maaf, kontak {kontak} tidak ditemukan di daftar kontakmu. " "Berapa nomor GoPay {kontak}?")
CONFIRM_PROMPT_RETRY = ( "Maaf, aku belum paham. Balas 'ya' untuk melanjutkan atau 'tidak' untuk " "membatalkan transaksi ini.")
CANCEL_REPLY = "Oke, transaksinya dibatalkan. Ada lagi yang bisa aku bantu?"
UNKNOWN_REPLY = ( "Maaf, aku belum bisa bantu untuk permintaan itu. Saat ini aku bisa bantu " "transfer uang, beli pulsa, bayar tagihan listrik PLN, pesan Gojek, atau " "pesan GoFood. Ada yang mau dibantu dari salah satunya?")
MAX_TURNS_REPLY = ( "Sepertinya kita belum ketemu detail transaksinya. Yuk mulai lagi dari awal — " "coba sebutkan lengkap, misalnya: 'transfer 50 ribu ke Budi'.")
INTENT_LABELS = { IntentType.TRANSFER_UANG: "Transfer Uang", IntentType.BELI_PULSA: "Beli Pulsa", IntentType.BAYAR_PLN: "Bayar Listrik PLN", IntentType.PESAN_GOJEK: "Gojek", IntentType.PESAN_GOFOOD: "GoFood",}
def format_rupiah(amount: int) -> str: """1500000 -> 'Rp1.500.000'""" return f"Rp{amount:,}".replace(",", ".")
@dataclassclass TurnResult: """Outcome of processing one user turn."""
state: DialogueState reply: str is_complete: bool payload: Optional[dict] = None needs_contact_resolution: bool = False target_kontak: Optional[str] = None
@dataclassclass _ContactResolution: """Internal result of _resolve_contact."""
reply: str needs_client_resolution: bool = False contact_name: Optional[str] = None
class StateManager: """Evaluates dialogue state and drives the slot-filling loop.
Parameters ---------- nlu_engine: Only needed when `use_llm_paraphrase=True`; used to rephrase templated follow-up questions into more natural language. use_llm_paraphrase: Hybrid mode switch. False (default) = deterministic templates, zero extra API calls. True = each follow-up is paraphrased by Gemini. """
def __init__(self, nlu_engine=None, use_llm_paraphrase: bool = False): self._nlu_engine = nlu_engine self._use_llm_paraphrase = use_llm_paraphrase and nlu_engine is not None
# ------------------------------------------------------------------ # Main entry point # ------------------------------------------------------------------ def process( self, state: DialogueState, nlu_result: NLUResult, user_text: str, resolve_contacts_locally: bool = False, ) -> TurnResult: state.turn_count += 1 state.history.append(user_text)
# --- Ya/Tidak confirmation intercept (highest priority) ------- # When a transaction is awaiting confirmation, this turn is a decision, # not a new extraction — handle it before any slot logic runs. if state.status == DialogueStatus.CONFIRMING: decision = self._classify_confirmation(user_text) if decision is True: return self._finalize(state) if decision is False: self._reset(state) return TurnResult(state, CANCEL_REPLY, is_complete=False) # Neither ya nor tidak: allow a genuine correction/new request to # fall through, otherwise re-ask for a clear decision. has_correction = ( nlu_result.intent != IntentType.UNKNOWN and bool(nlu_result.entities.filled_fields()) ) if not has_correction: return TurnResult(state, CONFIRM_PROMPT_RETRY, is_complete=False)
# --- Out-of-scope handling ----------------------------------- if nlu_result.intent == IntentType.UNKNOWN: if state.intent == IntentType.UNKNOWN: # No active transaction: politely state our scope. state.status = DialogueStatus.UNKNOWN return TurnResult(state, UNKNOWN_REPLY, is_complete=False) # Active transaction, but this turn was unintelligible: # re-ask for the pending slot instead of derailing. return self._ask_next_slot(state)
# --- Intent switch mid-dialogue ------------------------------ if ( state.intent != IntentType.UNKNOWN and nlu_result.intent != state.intent ): logger.info( "Intent switch: %s -> %s (resetting entities)", state.intent.value, nlu_result.intent.value, ) state.entities = TransactionEntities()
state.intent = nlu_result.intent
# --- Detect contact name change → clear old resolved number --- # If the user mentions a NEW target_kontak (different name from the # current one), the previously resolved phone number is stale and # must be cleared so the new contact gets its own resolution. new_kontak = nlu_result.entities.target_kontak old_kontak = state.entities.target_kontak if ( new_kontak is not None and old_kontak is not None and new_kontak.lower() != old_kontak.lower() ): logger.info( "Contact changed: '%s' -> '%s' (clearing old phone number)", old_kontak, new_kontak, ) state.entities.recipient_phone = None state.entities.phone_number = None
state.entities = state.entities.merge(nlu_result.entities)
# --- Contact resolution --------------------------------------- # Runs BEFORE the missing-slot check so a resolvable contact name # ("beliin anton pulsa") never triggers a redundant "nomor berapa?". unresolved = self._resolve_contact(state, resolve_contacts_locally) if unresolved is not None: if unresolved.needs_client_resolution: state.status = DialogueStatus.COLLECTING state.missing_slots = self._compute_missing(state) return TurnResult( state, unresolved.reply, is_complete=False, needs_contact_resolution=True, target_kontak=unresolved.contact_name, ) state.status = DialogueStatus.COLLECTING state.missing_slots = self._compute_missing(state) return TurnResult(state, unresolved.reply, is_complete=False)
state.missing_slots = self._compute_missing(state)
# --- Loop guard ---------------------------------------------- if state.missing_slots and state.turn_count >= MAX_TURNS: self._reset(state) return TurnResult(state, MAX_TURNS_REPLY, is_complete=False)
# --- Ask for confirmation or keep collecting ------------------ if not state.missing_slots: return self._confirm(state) return self._ask_next_slot(state)
# ------------------------------------------------------------------ # Helpers # ------------------------------------------------------------------ @staticmethod def _compute_missing(state: DialogueState) -> list[str]: required = REQUIRED_SLOTS[state.intent] filled = state.entities.filled_fields() return [slot for slot in required if slot not in filled]
def _ask_next_slot(self, state: DialogueState) -> TurnResult: state.status = DialogueStatus.COLLECTING slot = state.missing_slots[0] question = FOLLOW_UP_TEMPLATES.get( (state.intent, slot), f"Boleh lengkapi informasi '{slot}'?" ) # Fill in template placeholders (e.g. {recipient} for GoPay number ask) if state.entities.recipient and "{recipient}" in question: question = question.format(recipient=state.entities.recipient) if self._use_llm_paraphrase: question = self._nlu_engine.paraphrase(question) return TurnResult(state, question, is_complete=False)
@staticmethod def _resolve_contact( state: DialogueState, client_resolves: bool = False ) -> Optional["_ContactResolution"]: """Resolve `target_kontak` (a name or pronoun) into a real number.
Handles both beli_pulsa (→ phone_number) and transfer_uang (→ recipient_phone). Returns None when nothing needs resolving or resolution succeeded. Otherwise returns a _ContactResolution describing the follow-up: - When client_resolves is True, signals the client to resolve on-device (needs_client_resolution=True). - When False (web/demo), tries DUMMY_CONTACTS first, then asks for raw digits if the contact is unknown. """ entities = state.entities intent = state.intent
# Determine which slot needs a phone number and whether it's already filled if intent == IntentType.BELI_PULSA: phone_slot = "phone_number" current_phone = entities.phone_number not_found_template = CONTACT_NOT_FOUND_TEMPLATE elif intent == IntentType.TRANSFER_UANG: phone_slot = "recipient_phone" current_phone = entities.recipient_phone not_found_template = CONTACT_NOT_FOUND_GOPAY_TEMPLATE else: return None
if entities.target_kontak is None or current_phone is not None: return None
# Mobile flow: delegate to the client immediately. if client_resolves: logger.info( "Asking client to resolve contact '%s'", entities.target_kontak ) return _ContactResolution( reply=( f"Boleh pilih kontak {entities.target_kontak} dari daftar " f"kontakmu?" ), needs_client_resolution=True, contact_name=entities.target_kontak, )
# Web/demo flow: try the built-in directory first. key = entities.target_kontak.lower() number = DUMMY_CONTACTS.get(key) if number: setattr(entities, phone_slot, number) logger.info("Resolved contact '%s' -> %s (slot=%s)", key, number, phone_slot) return None
logger.info("Contact '%s' not found in directory", key) return _ContactResolution( reply=not_found_template.format(kontak=entities.target_kontak), needs_client_resolution=False, )
@staticmethod def _classify_confirmation(user_text: str) -> Optional[bool]: """True = confirmed, False = cancelled, None = unclear.
Asymmetric on purpose (fail-safe for money movement): - Any negative token cancels — over-cancelling is harmless. - An affirmative only counts if the WHOLE utterance is affirmative (after dropping fillers). Otherwise Indonesian fillers like "apa ya" / "gimana ya" would falsely confirm a transaction. """ tokens = set(re.findall(r"[a-z]+", user_text.lower())) if tokens & _NEGATIVE: return False meaningful = tokens - _FILLER if meaningful and meaningful <= _AFFIRMATIVE: return True return None
def _confirm(self, state: DialogueState) -> TurnResult: """All slots filled: show the summary and WAIT for ya/tidak. The payload is withheld until the user actually confirms.""" state.status = DialogueStatus.CONFIRMING return TurnResult( state, self._build_confirmation_text(state), is_complete=False )
def _finalize(self, state: DialogueState) -> TurnResult: """User said ya: release the transaction payload.""" state.status = DialogueStatus.COMPLETE payload = self._build_payload(state) label = INTENT_LABELS[state.intent]
# Gojek/GoFood: show "mencari driver" + "menunggu driver" message if state.intent == IntentType.PESAN_GOJEK: reply = ( f"Mencari driver terdekat untuk rute " f"{state.entities.asal or 'Bogor'} - {state.entities.tujuan}...\n" f"Silakan menunggu driver Budi (default). " f"Transaksi {label} berhasil diproses. Terima kasih!" ) elif state.intent == IntentType.PESAN_GOFOOD: reply = ( f"Mencari driver terdekat untuk pesanan {state.entities.makanan}...\n" f"Silakan menunggu driver Budi (default). " f"Transaksi {label} berhasil diproses. Terima kasih!" ) else: reply = f"Transaksi {label} berhasil diproses. Terima kasih!"
return TurnResult( state, reply, is_complete=True, payload=payload, )
@staticmethod def _build_payload(state: DialogueState) -> dict: """Machine-consumable transaction payload for downstream services.""" entities = state.entities.model_dump(exclude_none=True) return { "transaction_type": state.intent.value, "entities": entities, "turns_to_complete": state.turn_count, }
@staticmethod def _build_confirmation_text(state: DialogueState) -> str: e = state.entities label = INTENT_LABELS[state.intent] lines = [f"Siap! Konfirmasi {label}:"] if state.intent == IntentType.TRANSFER_UANG: nama = e.recipient or "(tanpa nama)" nomor = e.recipient_phone or "?" gopay = check_gopay_status(nomor) lines.append(f"- Nama : {nama}") lines.append(f"- Nomor : {nomor}") lines.append(f"- Status : {gopay}") lines.append(f"- Jumlah : {format_rupiah(e.amount)}") elif state.intent == IntentType.BELI_PULSA: nomor = e.phone_number if e.target_kontak: nomor = f"{e.phone_number} ({e.target_kontak})" lines.append(f"- Nomor HP : {nomor}") lines.append(f"- Nominal : {format_rupiah(e.amount)}") if e.provider: lines.append(f"- Provider : {e.provider}") elif state.intent == IntentType.BAYAR_PLN: lines.append(f"- ID Pelanggan : {e.customer_id}") if e.amount: lines.append(f"- Nominal : {format_rupiah(e.amount)}") elif state.intent == IntentType.PESAN_GOJEK: asal = e.asal or "Bogor" lines.append(f"- Asal : {asal}") lines.append(f"- Tujuan : {e.tujuan}") elif state.intent == IntentType.PESAN_GOFOOD: lines.append(f"- Pesanan : {e.makanan}") lines.append("Lanjutkan?") return "\n".join(lines)
@staticmethod def _reset(state: DialogueState) -> None: state.intent = IntentType.UNKNOWN state.entities = TransactionEntities() state.missing_slots = [] state.status = DialogueStatus.UNKNOWN state.turn_count = 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125// PayParse — minimal vanilla-JS chat client for the /api/chat endpoint.
const chatWindow = document.getElementById("chatWindow");const composerForm = document.getElementById("composerForm");const messageInput = document.getElementById("messageInput");const sendButton = document.getElementById("sendButton");const resetButton = document.getElementById("resetButton");const engineBadge = document.getElementById("engineBadge");const quickReplies = document.getElementById("quickReplies");
let sessionId = crypto.randomUUID();
function scrollToBottom() { chatWindow.scrollTop = chatWindow.scrollHeight;}
function appendMessage(text, sender) { const row = document.createElement("div"); row.className = `msg msg-${sender}`; const bubble = document.createElement("div"); bubble.className = "bubble"; bubble.textContent = text; row.appendChild(bubble); chatWindow.appendChild(row); scrollToBottom(); return row;}
function appendPayload(payload) { const row = document.createElement("div"); row.className = "msg msg-bot"; const bubble = document.createElement("div"); bubble.className = "bubble payload"; bubble.textContent = JSON.stringify(payload, null, 2); row.appendChild(bubble); chatWindow.appendChild(row); scrollToBottom();}
function showTyping() { const row = document.createElement("div"); row.className = "msg msg-bot typing"; row.id = "typingIndicator"; row.innerHTML = `<div class="bubble"><span class="dot"></span><span class="dot"></span><span class="dot"></span></div>`; chatWindow.appendChild(row); scrollToBottom();}
function hideTyping() { const el = document.getElementById("typingIndicator"); if (el) el.remove();}
async function loadHealth() { try { const res = await fetch("/health"); const data = await res.json(); engineBadge.textContent = data.offline_mode ? "Mode: Offline (Mock)" : "Mode: Gemini Live"; } catch { engineBadge.textContent = "Tidak terhubung"; }}
async function sendMessage(text) { appendMessage(text, "user"); messageInput.value = ""; sendButton.disabled = true; showTyping();
try { const res = await fetch("/api/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ session_id: sessionId, message: text }), }); if (!res.ok) throw new Error(`HTTP ${res.status}`); const data = await res.json();
hideTyping(); appendMessage(data.reply, "bot");
if (data.is_complete && data.payload) { appendPayload(data.payload); // Transaction finished server-side; start a fresh session for the next one. sessionId = crypto.randomUUID(); } } catch (err) { hideTyping(); appendMessage("Maaf, terjadi kendala koneksi ke server. Coba lagi ya.", "bot"); console.error(err); } finally { sendButton.disabled = false; messageInput.focus(); }}
composerForm.addEventListener("submit", (e) => { e.preventDefault(); const text = messageInput.value.trim(); if (!text) return; sendMessage(text);});
quickReplies.addEventListener("click", (e) => { const chip = e.target.closest(".chip"); if (!chip) return; sendMessage(chip.dataset.text);});
resetButton.addEventListener("click", async () => { try { await fetch(`/api/session/${sessionId}`, { method: "DELETE" }); } catch { /* session may already be gone; ignore */ } sessionId = crypto.randomUUID(); chatWindow.innerHTML = ""; appendMessage( 'Oke, mulai dari awal. Mau dibantu transfer, beli pulsa, atau bayar listrik?', "bot" );});
loadHealth();messageInput.focus();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051<!DOCTYPE html><html lang="id"><head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>PayParse — Asisten Keuangan</title> <link rel="stylesheet" href="/static/style.css" /></head><body> <div class="app"> <header class="app-header"> <div class="brand"> <span class="brand-dot"></span> <span class="brand-name">PayParse</span> </div> <div class="engine-badge" id="engineBadge">memuat…</div> </header>
<main class="chat-shell"> <div class="chat-window" id="chatWindow"> <div class="msg msg-bot"> <div class="bubble"> Halo! Aku bisa bantu <b>transfer uang</b>, <b>beli pulsa</b>, atau <b>bayar listrik PLN</b>. Coba ketik misalnya: <em>"tf goceng ke budi"</em>. </div> </div> </div>
<div class="quick-replies" id="quickReplies"> <button class="chip" data-text="transfer 50 ribu ke Budi">transfer 50 ribu ke Budi</button> <button class="chip" data-text="beliin pulsa 25rb ke 081234567890">beli pulsa 25rb</button> <button class="chip" data-text="bayar listrik id pelanggan 4512345678">bayar listrik PLN</button> </div>
<form class="composer" id="composerForm"> <input type="text" id="messageInput" placeholder="Ketik pesan… misal: tf goceng ke budi" autocomplete="off" /> <button type="submit" id="sendButton">Kirim</button> <button type="button" id="resetButton" title="Mulai percakapan baru">Reset</button> </form> </main> </div>
<script src="/static/app.js"></script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248:root { --goto-green: #00ad3d; --pure-white: #ffffff; --light-mint: #e6f8ed; --dark-slate: #0f172a; --soft-gray: #f1f5f9;}
* { box-sizing: border-box;}
body { margin: 0; font-family: "Segoe UI", "Inter", system-ui, -apple-system, sans-serif; background: var(--soft-gray); color: var(--dark-slate);}
.app { max-width: 560px; margin: 0 auto; min-height: 100vh; display: flex; flex-direction: column; background: var(--pure-white); box-shadow: 0 0 24px rgba(15, 23, 42, 0.06);}
/* ---------- Header ---------- */.app-header { display: flex; align-items: center; justify-content: space-between; padding: 18px 20px; background: var(--goto-green); color: var(--pure-white);}
.brand { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 1.1rem; letter-spacing: 0.2px;}
.brand-dot { width: 10px; height: 10px; border-radius: 50%; background: var(--pure-white); box-shadow: 0 0 0 4px rgba(255, 255, 255, 0.25);}
.engine-badge { font-size: 0.72rem; padding: 4px 10px; border-radius: 999px; background: rgba(255, 255, 255, 0.18); color: var(--pure-white); font-weight: 600;}
/* ---------- Chat area ---------- */.chat-shell { flex: 1; display: flex; flex-direction: column; min-height: 0;}
.chat-window { flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; gap: 12px; background: var(--pure-white);}
.msg { display: flex;}
.msg-user { justify-content: flex-end;}
.msg-bot { justify-content: flex-start;}
.bubble { max-width: 80%; padding: 12px 16px; border-radius: 16px; line-height: 1.45; font-size: 0.95rem; white-space: pre-wrap;}
.msg-bot .bubble { background: var(--light-mint); color: var(--dark-slate); border-bottom-left-radius: 4px;}
.msg-user .bubble { background: var(--goto-green); color: var(--pure-white); border-bottom-right-radius: 4px;}
.bubble.payload { background: var(--dark-slate); color: var(--pure-white); font-family: "Consolas", monospace; font-size: 0.82rem; border-radius: 12px;}
.typing .bubble { display: flex; align-items: center; gap: 4px; padding: 14px 16px;}
.typing .dot { width: 6px; height: 6px; border-radius: 50%; background: var(--goto-green); opacity: 0.4; animation: blink 1.2s infinite ease-in-out;}
.typing .dot:nth-child(2) { animation-delay: 0.2s; }.typing .dot:nth-child(3) { animation-delay: 0.4s; }
@keyframes blink { 0%, 80%, 100% { opacity: 0.25; transform: translateY(0); } 40% { opacity: 1; transform: translateY(-2px); }}
/* ---------- Quick replies ---------- */.quick-replies { display: flex; flex-wrap: wrap; gap: 8px; padding: 0 20px 12px; background: var(--pure-white);}
.chip { border: 1px solid var(--light-mint); background: var(--light-mint); color: var(--goto-green); font-weight: 600; font-size: 0.8rem; padding: 8px 12px; border-radius: 999px; cursor: pointer; transition: background 0.15s ease, transform 0.1s ease;}
.chip:hover { background: #d3f3e0;}
.chip:active { transform: scale(0.97);}
/* ---------- Composer ---------- */.composer { display: flex; gap: 8px; padding: 14px 16px; border-top: 1px solid var(--soft-gray); background: var(--pure-white);}
#messageInput { flex: 1; border: 1px solid var(--soft-gray); background: var(--soft-gray); border-radius: 12px; padding: 12px 14px; font-size: 0.95rem; color: var(--dark-slate); outline: none; transition: border-color 0.15s ease, background 0.15s ease;}
#messageInput:focus { border-color: var(--goto-green); background: var(--pure-white);}
#sendButton { background: var(--goto-green); color: var(--pure-white); border: none; border-radius: 12px; padding: 0 20px; font-weight: 700; font-size: 0.9rem; cursor: pointer; transition: opacity 0.15s ease;}
#sendButton:disabled { opacity: 0.5; cursor: not-allowed;}
#sendButton:not(:disabled):hover { opacity: 0.9;}
#resetButton { background: var(--soft-gray); color: var(--dark-slate); border: none; border-radius: 12px; padding: 0 16px; font-weight: 600; font-size: 0.85rem; cursor: pointer;}
#resetButton:hover { background: #e3e9ef;}
/* ---------- Scrollbar ---------- */.chat-window::-webkit-scrollbar { width: 6px;}
.chat-window::-webkit-scrollbar-thumb { background: var(--light-mint); border-radius: 999px;}README.md+24-4
__pycache__/main.cpython-311.pycAdded
__pycache__/ner_extractor.cpython-311.pycAdded
__pycache__/nlu_engine.cpython-311.pycAdded
__pycache__/schema.cpython-311.pycAdded
__pycache__/session_store.cpython-311.pycAdded
__pycache__/state_manager.cpython-311.pycAdded
app.pyAdded+98
main.pyAdded+154
ner_extractor.pyAdded+417
nlu_engine.pyAdded+476
requirements.txtAdded+6
schema.pyAdded+247
session_store.pyAdded+118
state_manager.pyAdded+465
static/app.jsAdded+125
static/index.htmlAdded+51
static/style.cssAdded+248