pandion commited on
Commit
7ba5e90
·
verified ·
1 Parent(s): a2c1bc1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -27
app.py CHANGED
@@ -1,20 +1,75 @@
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
 
 
4
  SYSTEM_PROMPT = (
5
  "You are “Maya,” owner of Klinik Sehat Sentosa, a small outpatient clinic in Manado. "
6
- "A student analyst will interview you to gather information requirements for a simple appointment & "
7
- "queueing system (web + mobile).\n\n"
8
- "Goals: reduce patient wait time, prevent double bookings, support WhatsApp reminders, basic daily reports.\n"
9
- "Persona: friendly, busy, non-technical. Answer concretely from real operations. If the student is vague, "
10
- "ask clarifying questions.\n"
11
- "Scope boundaries: No billing, no insurance, no EMR details—just scheduling, queue order, reminders, and daily counts.\n"
12
- "Constraints: staff have low digital literacy; intermittent internet; must run on existing Android phones; budget is small.\n"
13
- "Progress strategy: do not dump everything. Reveal details only when asked well. If the student asks leading questions, "
14
- "correct gently with realistic constraints.\n"
15
- "When you believe a requirement is sufficiently specified, internally mark that slot as 'filled.'"
 
 
 
 
 
 
 
 
 
16
  )
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  def respond(
19
  message,
20
  history: list[dict[str, str]],
@@ -25,9 +80,13 @@ def respond(
25
  hf_token: gr.OAuthToken,
26
  ):
27
  """
28
- For more information on `huggingface_hub` Inference API support, please check the docs:
29
- https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
30
  """
 
 
 
 
 
31
  client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
32
 
33
  messages = [{"role": "system", "content": system_message}]
@@ -36,40 +95,34 @@ def respond(
36
 
37
  response = ""
38
  for chunk in client.chat_completion(
39
- messages,
40
  max_tokens=max_tokens,
41
  stream=True,
42
  temperature=temperature,
43
  top_p=top_p,
44
  ):
45
- choices = chunk.choices
46
  token = ""
47
- if len(choices) and choices[0].delta.content:
48
  token = choices[0].delta.content
49
  response += token
50
  yield response
51
 
52
 
53
- # ChatInterface with fixed (non-editable) system prompt
54
  chatbot = gr.ChatInterface(
55
  respond,
56
  type="messages",
57
  additional_inputs=[
58
  gr.Textbox(
59
  value=SYSTEM_PROMPT,
60
- label="System message (locked to Klinik Sehat Sentosa roleplay)",
61
- interactive=False, # set to True if you want students to edit it
62
- lines=12,
63
  ),
64
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
65
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
66
- gr.Slider(
67
- minimum=0.1,
68
- maximum=1.0,
69
- value=0.95,
70
- step=0.05,
71
- label="Top-p (nucleus sampling)",
72
- ),
73
  ],
74
  )
75
 
 
1
+ import re
2
  import gradio as gr
3
  from huggingface_hub import InferenceClient
4
 
5
+ # ---------- HARD-SCOPE SYSTEM PROMPT ----------
6
  SYSTEM_PROMPT = (
7
  "You are “Maya,” owner of Klinik Sehat Sentosa, a small outpatient clinic in Manado. "
8
+ "A student analyst is interviewing you ONLY to gather requirements for a SIMPLE appointment & queueing system "
9
+ "(web + mobile).\n\n"
10
+ "SCOPE (the ONLY things you may discuss):\n"
11
+ " Patient registration (new/returning), booking rules, time slots, working hours, public holidays.\n"
12
+ " Queue flow (walk-in vs booked), ticketing/order, no-show/late-arrival handling, capacity limits.\n"
13
+ " Preventing double bookings, conflict detection, overbooking policy.\n"
14
+ " WhatsApp reminders/notifications (timing, content, opt-in), fallback if WA fails, delivery status.\n"
15
+ " Daily reports/metrics (patient counts, cancellations, top timeslots, staff load).\n"
16
+ " Operational constraints: low digital literacy, intermittent internet, Android phones, small budget.\n"
17
+ " Non-functional needs: offline-first basics, simple UI, audit trail minimal, privacy-by-default (no medical data).\n\n"
18
+ "OUT OF SCOPE (ALWAYS refuse): any medical/clinical/health education topics, diagnosis, therapy, drugs, billing, "
19
+ "insurance, EMR/medical records, HR/payroll, inventory, website marketing, general tech support.\n\n"
20
+ "BEHAVIOR:\n"
21
+ "• If the user asks anything outside the SCOPE, answer: "
22
+ " “Maaf, saya hanya bisa membahas *kasus sistem janji temu & antrean* klinik ini.” and then ask ONE focused "
23
+ " question to steer back to requirements.\n"
24
+ "• Ask concrete clarifying questions when needed. Answer from real operations, concise and practical. "
25
+ "• Reveal details progressively—only when asked well. Correct leading questions with realistic constraints.\n"
26
+ "• Internally mark a requirement as 'filled' when sufficiently specified."
27
  )
28
 
29
+ # ---------- STRICT GUARD (DEFAULT DENY, WHITELIST ALLOWED INTENTS) ----------
30
+ # Whitelist kata kunci topik yang DIIZINKAN (ID + EN)
31
+ ALLOWED_PATTERNS = [
32
+ r"\bjadwal\b", r"\bpenjadwalan\b", r"\bappointment\b", r"\bbooking\b", r"\btime ?slot\b",
33
+ r"\bj[aá]m praktik\b", r"\bhari (libur|operasional)\b", r"\bkalender\b",
34
+ r"\bantre(an)?\b", r"\bqueue(ing)?\b", r"\btiket\b", r"\border antre\b",
35
+ r"\bwalk-?in\b", r"\bno-?show\b", r"\bterlambat\b", r"\bketerlambatan\b",
36
+ r"\bdouble booking\b", r"\btabrakan jadwal\b", r"\bconflict\b", r"\boverbooking\b",
37
+ r"\bwhats(app)?\b", r"\bnotifikasi\b", r"\bpengingat\b", r"\breminder\b",
38
+ r"\blaporan harian\b", r"\breport(s)?\b", r"\bmetrik\b", r"\bstatistik\b",
39
+ r"\bpendaftaran\b", r"\bregistrasi\b", r"\bpasien baru\b", r"\bpasien lama\b",
40
+ r"\boffline\b", r"\binternet\b", r"\bandroid\b", r"\bbudget\b", r"\banggaran\b",
41
+ r"\bUI\b", r"\buser interface\b", r"\bkemudahan\b", r"\bakses\b",
42
+ r"\bkapasitas\b", r"\bkuota\b", r"\bantrian penuh\b",
43
+ r"\bcancel(lation|)\b", r"\bbatal\b", r"\breschedule\b", r"\bjadwal ulang\b",
44
+ r"\bstaff\b", r"\bpetugas\b", r"\bloket\b", r"\bperan\b", r"\brole\b",
45
+ r"\bdata field\b", r"\bform(ulir)?\b", r"\binput\b", r"\baudit\b", r"\bprivacy\b", r"\bprivasi\b"
46
+ ]
47
+
48
+ ALLOWED_REGEX = re.compile("|".join(ALLOWED_PATTERNS), flags=re.IGNORECASE)
49
+
50
+ # Beberapa trigger umum yang pasti out-of-scope (opsional, bantu cepat menolak)
51
+ OBVIOUS_OOS = re.compile(
52
+ r"\bstunting|diabetes|hipertensi|obat|terapi|gejala|diagnos[ae]|penyakit|imunisasi|asi|nyeri|infeksi|vitamin|"
53
+ r"tagihan|asuransi|bpjs|rekam medis|emr|labor|hasil lab|farmasi|resep",
54
+ flags=re.IGNORECASE
55
+ )
56
+
57
+ def in_scope(text: str) -> bool:
58
+ if not text:
59
+ return False
60
+ # Tolak cepat bila mengandung OOS jelas
61
+ if OBVIOUS_OOS.search(text):
62
+ return False
63
+ # Hanya izinkan jika mengandung salah satu topik whitelist
64
+ return bool(ALLOWED_REGEX.search(text))
65
+
66
+ def refuse_and_redirect():
67
+ return (
68
+ "Maaf, saya hanya bisa membahas *kasus sistem janji temu & antrean* klinik ini. "
69
+ "Boleh jelaskan kebutuhan Anda terkait **jadwal/slot**, **alur antrean (walk-in vs booking)**, "
70
+ "**pencegahan double booking**, atau **pengingat WhatsApp**?"
71
+ )
72
+
73
  def respond(
74
  message,
75
  history: list[dict[str, str]],
 
80
  hf_token: gr.OAuthToken,
81
  ):
82
  """
83
+ Uses Hugging Face Inference API for chat completion.
 
84
  """
85
+ # STRICT GATE: default-deny jika pesan user di luar scope
86
+ if not in_scope(message):
87
+ yield refuse_and_redirect()
88
+ return
89
+
90
  client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
91
 
92
  messages = [{"role": "system", "content": system_message}]
 
95
 
96
  response = ""
97
  for chunk in client.chat_completion(
98
+ messages=messages,
99
  max_tokens=max_tokens,
100
  stream=True,
101
  temperature=temperature,
102
  top_p=top_p,
103
  ):
104
+ choices = getattr(chunk, "choices", [])
105
  token = ""
106
+ if choices and getattr(choices[0].delta, "content", None):
107
  token = choices[0].delta.content
108
  response += token
109
  yield response
110
 
111
 
112
+ # ---------- GRADIO UI ----------
113
  chatbot = gr.ChatInterface(
114
  respond,
115
  type="messages",
116
  additional_inputs=[
117
  gr.Textbox(
118
  value=SYSTEM_PROMPT,
119
+ label="System message (LOCKED to Klinik Sentosa case)",
120
+ interactive=False, # jangan izinkan diubah
121
+ lines=18,
122
  ),
123
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
124
+ gr.Slider(minimum=0.1, maximum=4.0, value=0.3, step=0.1, label="Temperature"), # lebih patuh
125
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.9, step=0.05, label="Top-p (nucleus sampling)"),
 
 
 
 
 
 
126
  ],
127
  )
128