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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -72
app.py CHANGED
@@ -2,73 +2,66 @@ 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,
@@ -80,11 +73,11 @@ def respond(
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")
@@ -93,7 +86,7 @@ def respond(
93
  messages.extend(history)
94
  messages.append({"role": "user", "content": message})
95
 
96
- response = ""
97
  for chunk in client.chat_completion(
98
  messages=messages,
99
  max_tokens=max_tokens,
@@ -105,23 +98,23 @@ def respond(
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
  )
 
2
  import gradio as gr
3
  from huggingface_hub import InferenceClient
4
 
5
+ # ---------------- SYSTEM PROMPT (Catherine's Catering case only) ----------------
6
  SYSTEM_PROMPT = (
7
+ "You are a stakeholder at **Catherine’s Catering**, a small business that caters meals, "
8
+ "receptions, and banquets for business and social occasions (luncheon meetings, weddings, etc.). "
9
+ "You are being interviewed by a student analyst to discuss ONLY the problems, objectives, user requirements, "
10
+ "and testing related to THIS CASE below. Do not answer questions unrelated to this case.\n\n"
11
+ "=== CASE SUMMARY ===\n"
12
+ "Catherine’s Catering grew from small projects to many events as reputation improved. A new convention center and "
13
+ "prospering business community increased demand. Operations were managed with spreadsheets/word processing but "
14
+ "endless calls about available meals, guest count changes, and specialty dietary items (vegan/vegetarian/low-fat/"
15
+ "low-carb/gluten-free, etc.) became difficult. More part-time staff were hired; scheduling complexity overwhelmed "
16
+ "the HR manager. An IT/Business consulting company was engaged.\n\n"
17
+ "=== CONSULTANTS' CONCERNS ===\n"
18
+ "1) Master chef orders supplies per event, while suppliers give discounts for consolidated orders across a timeframe.\n"
19
+ "2) Customers frequently change guest counts, sometimes 1–2 days before the event.\n"
20
+ "3) Handling each catering request is time-consuming; ~60% of calls become contracts.\n"
21
+ "4) Employee schedule conflicts lead to understaffed events and timeliness complaints.\n"
22
+ "5) No summary/trend info on number of events and meal types; trends would help guide customers.\n"
23
+ "6) Sit-down meal events at banquet/meeting halls have staffing and guest-change issues.\n\n"
24
+ "=== USER REQUIREMENTS ===\n"
25
+ "1) Dynamic website for clients/prospects to view/obtain pricing for product options.\n"
26
+ "2) Let clients/prospects submit a catering request; route it to an account manager.\n"
27
+ "3) Add clients to a client DB; assign userID/password for project access.\n"
28
+ "4) Client site to view/update guest counts; restrict updates when event < 5 days away.\n"
29
+ "5) Software to communicate directly with event facility personnel.\n"
30
+ "6) HR system to schedule part-time employees with constraints; allow adding employees and scheduling them.\n"
31
+ "7) Queries/reports with summary information (trends, counts, etc.).\n\n"
32
+ "=== SIMPLE TEST PLAN (initial, will evolve) ===\n"
33
+ "1) Design test data so clients can view every product type.\n"
34
+ "2) Validate catering request data (valid + each invalid condition) and routing to correct account manager.\n"
35
+ "3) Validate all client fields; on success add to DB and assign userID/password.\n"
36
+ "4) Confirm clients can view event info; updates blocked < 5 days before event; test correct guest-count updates.\n"
37
+ "5) Verify software for communicating with event facilities works correctly.\n"
38
+ "6) Verify HR scheduling: add employees; invalid values rejected; scheduling updates valid; invalid entries reported.\n"
39
+ "7) Verify all queries/reports return correct summary information.\n\n"
40
+ "=== BEHAVIOR RULES ===\n"
41
+ "• Stay strictly on THIS CASE. If the user asks anything outside, politely refuse and redirect back to the case.\n"
42
+ "• Answer concretely from operations of Catherine’s Catering. Ask clarifying, requirement-driven questions.\n"
43
+ "• Be concise, practical, and progressively disclose details when asked.\n"
44
+ "• When a requirement becomes specific enough, internally mark it as ‘filled’ (no need to output that mark).\n"
45
+ "• Outputs should help toward objectives, user requirements, use cases/DFD processes, and tests—nothing else."
46
  )
47
 
48
+ # ---------------- Soft out-of-scope detector (block only obviously unrelated topics) ----------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  OBVIOUS_OOS = re.compile(
50
+ r"\bstunting|diabetes|hipertensi|vitamin|obat|terapi|gejala|diagnos[ae]|"
51
+ r"\bpenyakit|imunisasi|asi|infeksi|BPJS|rekam medis|EMR|"
52
+ r"\bcrypto|blockchain|NFT|smart ?contract|wallet|metamask|"
53
+ r"\bcalculus|trigonometri|fisika|kimia(?! dapur)|"
54
+ r"\bGPU|python (?!.*test|script|automation)|machine learning|LLM|"
55
+ r"\bWhatsApp reminder klinik|antrean klinik|rumah sakit|"
56
+ r"\bsepak bola|game|musik\b",
57
  flags=re.IGNORECASE
58
  )
59
 
60
+ REFUSAL = (
61
+ "Maaf, saya hanya bisa membahas **kasus Catherine’s Catering** (masalah, kebutuhan, solusi, dan pengujian) "
62
+ "yang tertulis di atas. Apa yang ingin Anda gali—misalnya alur request → routing ke account manager, "
63
+ "pembaruan jumlah tamu (<5 hari dibatasi), penjadwalan karyawan paruh waktu, atau ringkasan laporan/tren?"
64
+ )
 
 
 
 
 
 
 
 
 
 
65
 
66
  def respond(
67
  message,
 
73
  hf_token: gr.OAuthToken,
74
  ):
75
  """
76
+ Minimal guard: refuse only if obviously not about the Catherine’s Catering case.
77
+ Otherwise, let the model handle nuance (since the system prompt already enforces scope).
78
  """
79
+ if message and OBVIOUS_OOS.search(message):
80
+ yield REFUSAL
 
81
  return
82
 
83
  client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
 
86
  messages.extend(history)
87
  messages.append({"role": "user", "content": message})
88
 
89
+ streamed = ""
90
  for chunk in client.chat_completion(
91
  messages=messages,
92
  max_tokens=max_tokens,
 
98
  token = ""
99
  if choices and getattr(choices[0].delta, "content", None):
100
  token = choices[0].delta.content
101
+ streamed += token
102
+ yield streamed
103
 
104
 
105
+ # ---------------- Gradio UI ----------------
106
  chatbot = gr.ChatInterface(
107
  respond,
108
  type="messages",
109
  additional_inputs=[
110
  gr.Textbox(
111
  value=SYSTEM_PROMPT,
112
+ label="System message (LOCKED to Catherine’s Catering case)",
113
+ interactive=False, # keep it locked so students can't change it
114
+ lines=28,
115
  ),
116
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
117
+ gr.Slider(minimum=0.1, maximum=4.0, value=0.5, step=0.1, label="Temperature"),
118
  gr.Slider(minimum=0.1, maximum=1.0, value=0.9, step=0.05, label="Top-p (nucleus sampling)"),
119
  ],
120
  )