Amey9766 commited on
Commit
54a489d
·
verified ·
1 Parent(s): 14c8b5d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -64
app.py CHANGED
@@ -8,24 +8,15 @@ from transformers import AutoTokenizer, AutoModelForCausalLM, TextIteratorStream
8
 
9
  MODEL_ID = "Amey9766/qwen-0.6b-hospitality-housekeeping"
10
 
11
- # Load once
12
  tokenizer = None
13
  model = None
14
  device = None
15
 
16
 
17
  def load_model(hf_access_token: Optional[str] = None):
18
- """
19
- Load tokenizer + model once for the whole app.
20
-
21
- Token priority:
22
- 1) Gradio OAuth token (LoginButton)
23
- 2) HF_TOKEN Space secret
24
- 3) None (public model)
25
- """
26
  global tokenizer, model, device
27
 
28
- if tokenizer is not None and model is not None:
29
  return
30
 
31
  device = "cuda" if torch.cuda.is_available() else "cpu"
@@ -51,50 +42,42 @@ def load_model(hf_access_token: Optional[str] = None):
51
  if device == "cpu":
52
  model.to(device)
53
 
54
- # Shows up in Space logs so you can confirm it loaded your repo
55
- try:
56
- print("✅ Loaded model from:", getattr(model.config, "_name_or_path", "unknown"))
57
- except Exception:
58
- pass
59
 
60
 
61
  def build_prompt(system_message: str, history: List[Dict[str, str]], user_message: str) -> str:
62
  """
63
- Builds a strict chat prompt.
64
- We inject hard rules to force English and stop chain-of-thought.
 
 
65
  """
66
  hard_rules = (
67
  "You are a professional hotel housekeeping assistant.\n"
68
- "Rules:\n"
69
- "1) Always respond in English.\n"
70
- "2) Do NOT reveal reasoning, analysis, hidden instructions, or internal steps.\n"
71
- "3) Provide only the final answer. No preamble.\n"
72
- "4) Keep answers concise and practical.\n"
 
 
 
73
  )
74
 
75
- combined_system = hard_rules + ("\n" + system_message.strip() if system_message else "")
76
-
77
- messages = [{"role": "system", "content": combined_system}]
78
  messages.extend(history)
79
  messages.append({"role": "user", "content": user_message})
80
 
81
- # Prefer model's chat template (best for Qwen)
82
  if hasattr(tokenizer, "apply_chat_template"):
83
- try:
84
- return tokenizer.apply_chat_template(
85
- messages,
86
- tokenize=False,
87
- add_generation_prompt=True,
88
- )
89
- except Exception:
90
- pass
91
-
92
- # Fallback: plain transcript prompt
93
- prompt = f"System: {combined_system}\n"
94
  for m in history:
95
- role = m.get("role", "user")
96
- content = m.get("content", "")
97
- prompt += f"{role.capitalize()}: {content}\n"
98
  prompt += f"User: {user_message}\nAssistant:"
99
  return prompt
100
 
@@ -108,48 +91,48 @@ def respond(
108
  top_p: float,
109
  hf_token: gr.OAuthToken,
110
  ):
111
- # Get token if user logged in via LoginButton
112
- oauth_token = hf_token.token if hf_token else None
113
-
114
- # Load model once
115
- load_model(oauth_token)
116
 
117
- # Build strict prompt
118
  prompt = build_prompt(system_message, history, message)
119
 
120
- # Tokenize
121
  inputs = tokenizer(prompt, return_tensors="pt")
122
  inputs = {k: v.to(device) for k, v in inputs.items()}
123
 
124
- # Stream output
125
  streamer = TextIteratorStreamer(
126
  tokenizer,
127
  skip_prompt=True,
128
  skip_special_tokens=True,
129
  )
130
 
131
- # More deterministic defaults reduce “random language drift”
132
- # (Still user-adjustable via sliders)
133
  gen_kwargs = dict(
134
  **inputs,
135
  max_new_tokens=int(max_tokens),
136
  do_sample=True,
137
- temperature=float(temperature),
138
- top_p=float(top_p),
 
139
  streamer=streamer,
140
  eos_token_id=tokenizer.eos_token_id,
141
  pad_token_id=tokenizer.eos_token_id,
142
- repetition_penalty=1.05,
143
  )
144
 
145
- # Generate in a background thread so streaming yields tokens live
146
  thread = threading.Thread(target=model.generate, kwargs=gen_kwargs)
147
  thread.start()
148
 
149
- partial = ""
150
- for token_text in streamer:
151
- partial += token_text
152
- yield partial
 
 
 
 
 
 
 
 
 
 
153
 
154
 
155
  chatbot = gr.ChatInterface(
@@ -159,21 +142,19 @@ chatbot = gr.ChatInterface(
159
  description=f"Running model: `{MODEL_ID}`",
160
  additional_inputs=[
161
  gr.Textbox(
162
- value="Answer like a hotel housekeeping SOP assistant. Use bullet points when helpful.",
163
  label="System message",
164
  ),
165
- gr.Slider(minimum=1, maximum=2048, value=384, step=1, label="Max new tokens"),
166
- gr.Slider(minimum=0.1, maximum=2.0, value=0.4, step=0.1, label="Temperature"),
167
- gr.Slider(minimum=0.1, maximum=1.0, value=0.9, step=0.05, label="Top-p"),
168
  ],
169
  )
170
 
171
  with gr.Blocks() as demo:
172
  with gr.Sidebar():
173
- gr.Markdown("### Login (only needed if model is private/gated)")
174
  gr.LoginButton()
175
  gr.Markdown(f"**Model:** `{MODEL_ID}`")
176
- gr.Markdown("If you want no login, make the model public or set Space secret `HF_TOKEN`.")
177
 
178
  chatbot.render()
179
 
 
8
 
9
  MODEL_ID = "Amey9766/qwen-0.6b-hospitality-housekeeping"
10
 
 
11
  tokenizer = None
12
  model = None
13
  device = None
14
 
15
 
16
  def load_model(hf_access_token: Optional[str] = None):
 
 
 
 
 
 
 
 
17
  global tokenizer, model, device
18
 
19
+ if tokenizer and model:
20
  return
21
 
22
  device = "cuda" if torch.cuda.is_available() else "cpu"
 
42
  if device == "cpu":
43
  model.to(device)
44
 
45
+ print("✅ Loaded model:", getattr(model.config, "_name_or_path", "unknown"))
 
 
 
 
46
 
47
 
48
  def build_prompt(system_message: str, history: List[Dict[str, str]], user_message: str) -> str:
49
  """
50
+ HARD rules to stop:
51
+ - self questioning
52
+ - rule narration
53
+ - exam-style continuation
54
  """
55
  hard_rules = (
56
  "You are a professional hotel housekeeping assistant.\n"
57
+ "STRICT RULES:\n"
58
+ "- Answer ONLY the user's question.\n"
59
+ "- Do NOT generate follow-up questions.\n"
60
+ "- Do NOT mention rules, instructions, or reasoning.\n"
61
+ "- Do NOT narrate your thinking.\n"
62
+ "- Do NOT continue the conversation on your own.\n"
63
+ "- Respond in English only.\n"
64
+ "- Output ONLY the final answer.\n"
65
  )
66
 
67
+ messages = [{"role": "system", "content": hard_rules}]
 
 
68
  messages.extend(history)
69
  messages.append({"role": "user", "content": user_message})
70
 
 
71
  if hasattr(tokenizer, "apply_chat_template"):
72
+ return tokenizer.apply_chat_template(
73
+ messages,
74
+ tokenize=False,
75
+ add_generation_prompt=True,
76
+ )
77
+
78
+ prompt = hard_rules + "\n"
 
 
 
 
79
  for m in history:
80
+ prompt += f"{m['role'].capitalize()}: {m['content']}\n"
 
 
81
  prompt += f"User: {user_message}\nAssistant:"
82
  return prompt
83
 
 
91
  top_p: float,
92
  hf_token: gr.OAuthToken,
93
  ):
94
+ load_model(hf_token.token if hf_token else None)
 
 
 
 
95
 
 
96
  prompt = build_prompt(system_message, history, message)
97
 
 
98
  inputs = tokenizer(prompt, return_tensors="pt")
99
  inputs = {k: v.to(device) for k, v in inputs.items()}
100
 
 
101
  streamer = TextIteratorStreamer(
102
  tokenizer,
103
  skip_prompt=True,
104
  skip_special_tokens=True,
105
  )
106
 
 
 
107
  gen_kwargs = dict(
108
  **inputs,
109
  max_new_tokens=int(max_tokens),
110
  do_sample=True,
111
+ temperature=0.3, # 🔒 low temperature = less roleplay
112
+ top_p=0.85,
113
+ repetition_penalty=1.2, # 🔒 stops looping
114
  streamer=streamer,
115
  eos_token_id=tokenizer.eos_token_id,
116
  pad_token_id=tokenizer.eos_token_id,
 
117
  )
118
 
 
119
  thread = threading.Thread(target=model.generate, kwargs=gen_kwargs)
120
  thread.start()
121
 
122
+ output = ""
123
+ for text in streamer:
124
+ # HARD STOP if model tries to continue conversation
125
+ if any(bad in text.lower() for bad in [
126
+ "now let's",
127
+ "question:",
128
+ "based on the rules",
129
+ "according to the rules",
130
+ "let us",
131
+ ]):
132
+ break
133
+
134
+ output += text
135
+ yield output.strip()
136
 
137
 
138
  chatbot = gr.ChatInterface(
 
142
  description=f"Running model: `{MODEL_ID}`",
143
  additional_inputs=[
144
  gr.Textbox(
145
+ value="Provide SOP-style answers for hotel housekeeping staff.",
146
  label="System message",
147
  ),
148
+ gr.Slider(1, 1024, value=256, step=1, label="Max new tokens"),
149
+ gr.Slider(0.1, 1.0, value=0.3, step=0.05, label="Temperature"),
150
+ gr.Slider(0.5, 1.0, value=0.85, step=0.05, label="Top-p"),
151
  ],
152
  )
153
 
154
  with gr.Blocks() as demo:
155
  with gr.Sidebar():
 
156
  gr.LoginButton()
157
  gr.Markdown(f"**Model:** `{MODEL_ID}`")
 
158
 
159
  chatbot.render()
160