RishiRP commited on
Commit
cecfb15
·
verified ·
1 Parent(s): 38169c5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +398 -831
app.py CHANGED
@@ -1,873 +1,440 @@
1
- import os, io, re, sys, time, json, zipfile, statistics
2
- from pathlib import Path
3
- from typing import List, Dict, Tuple, Union
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  import gradio as gr
6
- import pandas as pd
7
- import torch
8
- from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
9
 
10
- # ========= ZeroGPU support =========
11
  try:
12
- import spaces # available on HF Spaces
13
  except Exception:
14
- class _DummySpaces:
15
- def GPU(self, *args, **kwargs):
16
- def deco(f): return f
17
- return deco
18
- spaces = _DummySpaces()
19
-
20
- # ========= Auth token =========
21
- HF_TOKEN = (
22
- os.getenv("HF_TOKEN")
23
- or os.getenv("HUGGINGFACE_HUB_TOKEN")
24
- or os.getenv("HUGGINGFACEHUB_API_TOKEN")
25
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
- # Console warning at startup (helps when logs are open)
28
- if not HF_TOKEN:
29
- print(
30
- "[WARN] HF_TOKEN is not set. Gated models will fail. "
31
- "Set it in Space → Settings → Variables and secrets.",
32
- file=sys.stderr
33
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
- # ========= Labels & metrics =========
36
- ALLOWED_LABELS = [
37
- "plan_contact",
38
- "schedule_meeting",
39
- "update_contact_info_non_postal",
40
- "update_contact_info_postal_address",
41
- "update_kyc_activity",
42
- "update_kyc_origin_of_assets",
43
- "update_kyc_purpose_of_businessrelation",
44
- "update_kyc_total_assets",
45
- ]
46
- LABEL_TO_IDX = {l: i for i, l in enumerate(ALLOWED_LABELS)}
47
- FN_PENALTY = 2.0
48
- FP_PENALTY = 1.0
49
-
50
- def safe_json_load(s: str):
51
- try:
52
- return json.loads(s)
53
- except Exception:
54
- pass
55
- m = re.search(r"\{.*\}", s, re.S)
56
- if m:
57
- try:
58
- return json.loads(m.group(0))
59
- except Exception:
60
- pass
61
- return {"labels": [], "notes": "WARN: model output not valid JSON; fallback used"}
62
-
63
- def _coerce_labels_list(x):
64
- if isinstance(x, list):
65
- out = []
66
- for it in x:
67
- if isinstance(it, str): out.append(it)
68
- elif isinstance(it, dict):
69
- for k in ("label", "value", "task", "category", "name"):
70
- v = it.get(k)
71
- if isinstance(v, str):
72
- out.append(v); break
73
- else:
74
- if isinstance(it.get("labels"), list):
75
- out += [s for s in it["labels"] if isinstance(s, str)]
76
- # dedupe keep order
77
- seen = set(); norm = []
78
- for s in out:
79
- if s not in seen:
80
- norm.append(s); seen.add(s)
81
- return norm
82
- if isinstance(x, dict):
83
- for k in ("expected_labels", "labels", "targets", "y_true"):
84
- if k in x: return _coerce_labels_list(x[k])
85
- if "one_hot" in x and isinstance(x["one_hot"], dict):
86
- return [k for k, v in x["one_hot"].items() if v]
87
- return []
88
-
89
- def classic_metrics(pred_labels, exp_labels):
90
- pred = set([str(x) for x in (pred_labels or []) if isinstance(x, (str,int,float,bool))])
91
- gold = set([str(x) for x in (exp_labels or []) if isinstance(x, (str,int,float,bool))])
92
- if not pred and not gold:
93
- return True, 1.0, 1.0, 1.0, 1.0
94
- inter = pred & gold; union = pred | gold
95
- exact = (sorted(pred) == sorted(gold))
96
- precision = (len(inter) / (len(pred) if pred else 1e-9))
97
- recall = (len(inter) / (len(gold) if gold else 1e-9))
98
- f1 = 0.0 if len(inter) == 0 else 2*len(inter) / (len(pred)+len(gold)+1e-9)
99
- hamming = (len(inter) / (len(union) if union else 1e-9))
100
- return exact, precision, recall, f1, hamming
101
-
102
- def ubs_score_one(true_labels, pred_labels) -> float:
103
- tset = [l for l in (true_labels or []) if l in LABEL_TO_IDX]
104
- pset = [l for l in (pred_labels or []) if l in LABEL_TO_IDX]
105
- n_labels = len(ALLOWED_LABELS)
106
- tpos = set(tset); ppos = set(pset)
107
- fn = sum(1 for l in ALLOWED_LABELS if (l in tpos and l not in ppos))
108
- fp = sum(1 for l in ALLOWED_LABELS if (l not in tpos and l in ppos))
109
- weighted = FN_PENALTY*fn + FP_PENALTY*fp
110
- t_count = len(tpos)
111
- max_err = FN_PENALTY*t_count + FP_PENALTY*(n_labels - t_count)
112
- score = 1.0 if max_err == 0 else (1.0 - (weighted / max_err))
113
- return float(max(0.0, min(1.0, score)))
114
-
115
- # ========= Lightweight preprocessing =========
116
- EMAIL_RX = re.compile(r'\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b', re.I)
117
- TIME_RX = re.compile(r'\b(\d{1,2}:\d{2}\b|\b\d{1,2}\s?(am|pm)\b|\bafternoon\b|\bmorning\b|\bevening\b)', re.I)
118
- DATE_RX = re.compile(r'\b(jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)\b|\b\d{1,2}[/-]\d{1,2}([/-]\d{2,4})?\b|\b20\d{2}\b', re.I)
119
- MEET_RX = re.compile(r'\b(meet(ing)?|call|appointment|schedule|invite|agenda|online|in[- ]?person|phone|zoom|teams)\b', re.I)
120
- MODAL_RX = re.compile(r'\b(online|in[- ]?person|phone|zoom|teams)\b', re.I)
121
- SMALLTALK_RX = re.compile(r'^\s*(user|advisor):\s*(thanks( you)?|thank you|anything else|have a great day|you too)\b', re.I)
122
-
123
- TYPO_FIXES = [
124
- (re.compile(r'\bschedulin\s*g\b', re.I), 'scheduling'),
125
- (re.compile(r'\beeting\b', re.I), 'meeting'),
126
- (re.compile(r'\bdi?i?gtal\b', re.I), 'digital'),
127
- (re.compile(r'\bdigi\s+tal\b', re.I), 'digital'),
128
- (re.compile(r'\bspread\s*sheet\b', re.I), 'spreadsheet'),
129
- (re.compile(r'\bseats\b', re.I), 'sheets'),
130
- (re.compile(r'\bver(s|z)ion meters\b', re.I), 'version metrics'),
131
- ]
132
-
133
- def normalize_text(text: str, fix_typos: bool = True) -> str:
134
- t = text.replace('\r\n', '\n')
135
- t = re.sub(r'^\s*Speaker\s*1\s*:\s*', 'USER: ', t, flags=re.I | re.M)
136
- t = re.sub(r'^\s*Speaker\s*2\s*:\s*', 'ADVISOR: ', t, flags=re.I | re.M)
137
- t = re.sub(r'[ \t]+', ' ', t)
138
- t = re.sub(r'\n{3,}', '\n\n', t)
139
- if fix_typos:
140
- for rx, rep in TYPO_FIXES:
141
- t = rx.sub(rep, t)
142
- return t.strip()
143
-
144
- def extract_cues(text: str):
145
- emails = EMAIL_RX.findall(text)
146
- email_new, email_old = (emails[-1], emails[-2]) if len(emails)>=2 else ((emails[-1], None) if emails else (None, None))
147
- has_time = bool(TIME_RX.search(text))
148
- has_date = bool(DATE_RX.search(text))
149
- has_meet = bool(MEET_RX.search(text))
150
- modality = None
151
- m = MODAL_RX.search(text)
152
- if m:
153
- modality = m.group(0).upper().replace('IN PERSON','IN_PERSON').replace('IN-PERSON','IN_PERSON')
154
- meeting_confirmed = (has_meet and (has_time or has_date))
155
- tm = TIME_RX.search(text)
156
- norm_tm = tm.group(0) if tm else None
157
- return {
158
- "email_new": email_new,
159
- "email_old": email_old,
160
- "contact_pref": "EMAIL" if email_new else None,
161
- "meeting_time_fragment": norm_tm,
162
- "meeting_modality": modality,
163
- "meeting_confirmed": meeting_confirmed
164
- }
165
-
166
- def build_cues_header(cues: dict) -> str:
167
- has_any = any([cues.get("email_new"), cues.get("email_old"), cues.get("contact_pref"), cues.get("meeting_confirmed")])
168
- if not has_any:
169
- return ""
170
- lines = ["[DETECTED_CUES]"]
171
- if cues.get("email_new"): lines.append(f"EMAIL_NEW: {cues['email_new']}")
172
- if cues.get("email_old"): lines.append(f"EMAIL_OLD: {cues['email_old']}")
173
- if cues.get("contact_pref"): lines.append(f"CONTACT_PREF: {cues['contact_pref']}")
174
- if cues.get("meeting_confirmed"):
175
- mod = cues.get("meeting_modality") or ""
176
- tm = cues.get("meeting_time_fragment") or ""
177
- lines.append(f"MEETING: {(tm + ' ' + mod).strip()} CONFIRMED")
178
- lines.append("[/DETECTED_CUES]")
179
- return "\n".join(lines)
180
-
181
- def find_cue_lines(lines):
182
- idx = set()
183
- for i, ln in enumerate(lines):
184
- if EMAIL_RX.search(ln) or (MEET_RX.search(ln) and (TIME_RX.search(ln) or DATE_RX.search(ln))):
185
- idx.add(i)
186
- return sorted(idx)
187
-
188
- def prune_by_window(lines, cue_idx, window=3, strip_smalltalk=False):
189
- n = len(lines); keep = set()
190
- for k in cue_idx:
191
- lo, hi = max(0, k-window), min(n-1, k+window)
192
- keep.update(range(lo,hi+1))
193
- out=[]
194
- for i, ln in enumerate(lines):
195
- if i in keep:
196
- if strip_smalltalk and SMALLTALK_RX.search(ln): continue
197
- out.append(ln)
198
- return out
199
-
200
- def shrink_to_token_cap_by_lines(text: str, soft_cap_tokens: int, tokenizer,
201
- min_lines_keep: int = 30,
202
- apply_only_if_ratio: float = 1.15) -> str:
203
- ids = tokenizer(text, return_tensors=None, add_special_tokens=False).input_ids
204
- est = len(ids)
205
- threshold = int(soft_cap_tokens * apply_only_if_ratio)
206
- if est <= threshold: return text
207
- parts = text.splitlines()
208
- if len(parts) <= min_lines_keep: return text
209
-
210
- keep_flags=[]
211
- for ln in parts:
212
- is_header = ln.startswith("[DETECTED_CUES]") or ln.startswith("[/DETECTED_CUES]") \
213
- or ln.startswith("EMAIL_") or ln.startswith("CONTACT_") or ln.startswith("MEETING:")
214
- is_cue = bool(EMAIL_RX.search(ln) or MEET_RX.search(ln) or DATE_RX.search(ln) or TIME_RX.search(ln))
215
- keep_flags.append(is_header or is_cue)
216
-
217
- pruned = [ln for ln, keep in zip(parts, keep_flags) if keep]
218
- if len(pruned) < min_lines_keep:
219
- pad_needed = min_lines_keep - len(pruned)
220
- non_cue_lines = [ln for ln, keep in zip(parts, keep_flags) if not keep]
221
- pruned = pruned + non_cue_lines[:pad_needed]
222
-
223
- candidate = "\n".join(pruned)
224
- cand_tokens = len(tokenizer(candidate, return_tensors=None, add_special_tokens=False).input_ids)
225
- if cand_tokens > threshold:
226
- mid = len(parts)//2
227
- half = max(min_lines_keep//2, 50)
228
- slice_parts = parts[max(0, mid-half): min(len(parts), mid+half)]
229
- candidate2 = "\n".join(slice_parts)
230
- candidate2_tokens = len(tokenizer(candidate2, return_tensors=None, add_special_tokens=False).input_ids)
231
- candidate = candidate if cand_tokens <= candidate2_tokens else candidate2
232
-
233
- if len(candidate.splitlines()) < min_lines_keep: return text
234
- return candidate
235
-
236
- def enforce_rules(labels, transcript_text):
237
- labels = set(labels or [])
238
- if (TIME_RX.search(transcript_text) or DATE_RX.search(transcript_text)) and MEET_RX.search(transcript_text):
239
- labels.add("schedule_meeting"); labels.discard("plan_contact")
240
- if EMAIL_RX.search(transcript_text) and re.search(r'\b(update|new|set|change|confirm(ed)?|for all communication)\b', transcript_text, re.I):
241
- labels.add("update_contact_info_non_postal")
242
- kyc_rx = re.compile(r'\b(kyc|aml|compliance|employer|occupation|purpose of (relationship|account)|source of (wealth|funds)|net worth|total assets)\b', re.I)
243
- if "update_kyc_activity" in labels and not kyc_rx.search(transcript_text):
244
- labels.discard("update_kyc_activity")
245
- return sorted(labels)
246
-
247
- # ========= HF model wrapper =========
248
  class HFModel:
249
- def __init__(self, repo_id: str, load_4bit: bool, dtype: str, trust_remote_code: bool):
 
 
 
 
 
 
 
 
 
 
 
 
250
  self.repo_id = repo_id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
  self.tokenizer = AutoTokenizer.from_pretrained(
252
- repo_id, use_fast=True, trust_remote_code=trust_remote_code, token=HF_TOKEN
 
 
 
253
  )
254
- torch_dtype = {"bfloat16": torch.bfloat16, "float16": torch.float16, "float32": torch.float32}.get(dtype, torch.bfloat16)
255
 
 
256
  self.model = None
257
- if load_4bit:
258
  try:
259
- q = BitsAndBytesConfig(
260
- load_in_4bit=True, bnb_4bit_use_double_quant=True,
261
- bnb_4bit_compute_dtype=torch_dtype, bnb_4bit_quant_type="nf4"
 
 
262
  )
263
  self.model = AutoModelForCausalLM.from_pretrained(
264
- repo_id, device_map="auto", trust_remote_code=trust_remote_code,
265
- quantization_config=q, torch_dtype=torch_dtype, token=HF_TOKEN
 
 
 
 
266
  )
267
  except Exception as e:
268
- print(f"[WARN] 4-bit load failed for {repo_id}: {e}\nFalling back to normal load...", file=sys.stderr)
 
 
269
  if self.model is None:
270
  self.model = AutoModelForCausalLM.from_pretrained(
271
- repo_id, device_map="auto", trust_remote_code=trust_remote_code,
272
- torch_dtype=torch_dtype, token=HF_TOKEN
 
 
 
273
  )
274
 
 
275
  self.max_context = getattr(self.model.config, "max_position_embeddings", None) \
276
- or getattr(self.model.config, "max_sequence_length", None) or 8192
277
-
278
- def apply_chat_template(self, system_text: str, user_text: str) -> str:
279
- if getattr(self.tokenizer, "chat_template", None):
280
- messages = [{"role":"system","content":system_text},
281
- {"role":"user","content":user_text}]
282
- return self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
283
- return ("### System\n" + system_text.strip() + "\n\n" +
284
- "### User\n" + user_text.strip() + "\n\n" +
285
- "### Assistant\n")
 
 
 
 
 
 
 
 
 
286
 
287
  @torch.inference_mode()
288
- def generate_json(self, system_text: str, user_text: str, max_new_tokens: int = 256):
289
- prompt = self.apply_chat_template(system_text, user_text)
290
- inputs = self.tokenizer(prompt, return_tensors="pt").to(self.model.device)
291
- t0 = time.perf_counter()
292
- out = self.model.generate(
293
- **inputs, max_new_tokens=max_new_tokens,
294
- do_sample=False, temperature=None, top_p=None,
295
- eos_token_id=self.tokenizer.eos_token_id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296
  )
297
- latency_ms = int((time.perf_counter() - t0) * 1000)
298
- text = self.tokenizer.decode(out[0], skip_special_tokens=True)
299
- if text.startswith(prompt): text = text[len(prompt):]
300
- return latency_ms, text, prompt
301
-
302
- MODEL_CACHE: Dict[str, HFModel] = {}
303
- def get_model(repo_id: str, load_4bit: bool, dtype: str, trust_remote_code: bool):
304
- if repo_id not in MODEL_CACHE:
305
- MODEL_CACHE[repo_id] = HFModel(repo_id, load_4bit=load_4bit, dtype=dtype, trust_remote_code=trust_remote_code)
306
- return MODEL_CACHE[repo_id]
307
-
308
- # ========= ZeroGPU functions =========
309
- @spaces.GPU(duration=180, secrets=["HF_TOKEN"]) # pass token into ZeroGPU job
310
- def gpu_generate(repo_id: str, system_text: str, user_text: str,
311
- load_4bit: bool, dtype: str, trust_remote_code: bool):
312
- token_seen = bool(os.getenv("HF_TOKEN"))
313
- hf = get_model(repo_id, load_4bit=load_4bit, dtype=dtype, trust_remote_code=trust_remote_code)
314
- lat, txt, prmpt = hf.generate_json(system_text.strip(), user_text.strip(), max_new_tokens=256)
315
- return lat, txt, prmpt, token_seen
316
-
317
- @spaces.GPU(duration=15, secrets=["HF_TOKEN"])
318
- def gpu_check_token():
319
- return bool(os.getenv("HF_TOKEN"))
320
-
321
- # ========= ZIP helpers =========
322
- def _read_zip_bytes(dataset_zip: Union[bytes, str, dict, None]) -> bytes:
323
- if dataset_zip is None: raise ValueError("No ZIP provided")
324
- if isinstance(dataset_zip, bytes): return dataset_zip
325
- if isinstance(dataset_zip, str):
326
- with open(dataset_zip, "rb") as f: return f.read()
327
- if isinstance(dataset_zip, dict) and "path" in dataset_zip:
328
- with open(dataset_zip["path"], "rb") as f: return f.read()
329
- path = getattr(dataset_zip, "name", None)
330
- if path and os.path.exists(path):
331
- with open(path, "rb") as f: return f.read()
332
- raise ValueError("Unsupported file object from Gradio")
333
-
334
- def parse_zip(zip_bytes: bytes) -> Dict[str, Tuple[str, List[str]]]:
335
- zf = zipfile.ZipFile(io.BytesIO(zip_bytes))
336
- samples = {}
337
- for n in zf.namelist():
338
- p = Path(n)
339
- if p.suffix.lower() == ".txt":
340
- samples.setdefault(p.stem, ["", []])[0] = zf.read(n).decode("utf-8", "replace")
341
- elif p.suffix.lower() == ".json":
342
  try:
343
- js = json.loads(zf.read(n).decode("utf-8", "replace"))
344
  except Exception:
345
- js = []
346
- samples.setdefault(p.stem, ["", []])[1] = _coerce_labels_list(js)
347
- return samples
348
-
349
- # ========= Prompts =========
350
- DEFAULT_SYSTEM = (
351
- "You are a task extraction assistant. "
352
- "Always output valid JSON with a field \"labels\" (list of strings). "
353
- "Use only from this set: " + json.dumps(ALLOWED_LABELS) + ". "
354
- "Return JSON only."
355
- )
356
- DEFAULT_CONTEXT = (
357
- "- plan_contact: conversation without a concrete meeting (no date/time)\n"
358
- "- schedule_meeting: explicit date/time/modality confirmation\n"
359
- "- update_contact_info_non_postal: changes to email/phone\n"
360
- "- update_contact_info_postal_address: changes to mailing address\n"
361
- "- update_kyc_*: KYC updates (activity, purpose, origin of assets, total assets)"
362
- )
363
-
364
- # ========= Preprocess + build input =========
365
- def prepare_input_text(raw_txt: str, soft_cap: int, preprocess: bool, pre_window: int,
366
- add_cues: bool, strip_smalltalk: bool, tokenizer) -> Tuple[str, int, int]:
367
- before = len(tokenizer(raw_txt, return_tensors=None, add_special_tokens=False).input_ids)
368
- proc_text = raw_txt
369
- if preprocess:
370
- t_norm = normalize_text(proc_text, fix_typos=True)
371
- lines = [ln.strip() for ln in t_norm.splitlines() if ln.strip()]
372
- cue_lines = find_cue_lines(lines)
373
- if cue_lines:
374
- kept = prune_by_window(lines, cue_lines, window=pre_window, strip_smalltalk=strip_smalltalk)
375
  else:
376
- kept = [ln for ln in lines if not (strip_smalltalk and SMALLTALK_RX.search(ln))]
377
- t_kept = "\n".join(kept)
378
- cues = extract_cues(t_kept)
379
- header = build_cues_header(cues) if add_cues else ""
380
- proc_text = (header + "\n\n" + t_kept).strip() if header else t_kept
381
- proc_text = shrink_to_token_cap_by_lines(proc_text, soft_cap, tokenizer)
382
- if len(proc_text.splitlines()) < 30:
383
- proc_text = t_norm
384
- after = len(tokenizer(proc_text, return_tensors=None, add_special_tokens=False).input_ids)
385
- return proc_text, before, after
386
-
387
- def explain_params_markdown() -> str:
388
- return (
389
- "**Parameter help** \n"
390
- "- **Soft token cap**: target max input size; we prune long transcripts toward this size to save latency. \n"
391
- "- **Enable preprocessing**: normalizes speaker tags, fixes obvious typos, and focuses on cue lines. \n"
392
- "- **Window ± lines around cues**: how many lines we keep around detected cues (dates/emails/‘meeting’, etc.). \n"
393
- "- **Add cues header**: inserts a short summary block (email, meeting signal) above the transcript to guide the model. \n"
394
- "- **Strip smalltalk**: removes lines like ‘thanks, bye’ to keep only useful content. \n"
395
- "- **Load in 4-bit (GPU only)**: memory-saving quantization; has no effect on CPU Spaces."
396
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
397
 
398
- # ========= Single mode =========
399
- def single_mode(
400
- preset_model: str, custom_model: str,
401
- system_text: str, context_text: str,
402
- transcript_text: str, transcript_file,
403
- expected_labels_json,
404
- soft_cap: int, preprocess: bool, pre_window: int, add_cues: bool, strip_smalltalk: bool,
405
- load_4bit: bool, dtype: str, trust_remote_code: bool
406
- ):
407
- repo_id = custom_model.strip() or preset_model.strip()
408
- if not repo_id:
409
- return "Please choose a model.", "", "", "", None, None, None, ""
410
-
411
- txt = (transcript_text or "").strip()
412
- if transcript_file and hasattr(transcript_file, "name") and os.path.exists(transcript_file.name):
413
- with open(transcript_file.name, "r", encoding="utf-8", errors="replace") as f:
414
- txt = f.read()
415
- if not txt:
416
- return "Please paste a transcript or upload a .txt file.", "", "", "", None, None, None, ""
417
-
418
- exp = []
419
- if expected_labels_json and hasattr(expected_labels_json, "name") and os.path.exists(expected_labels_json.name):
420
- try:
421
- with open(expected_labels_json.name, "r", encoding="utf-8", errors="replace") as f:
422
- exp = _coerce_labels_list(json.load(f))
423
- except Exception:
424
- exp = []
425
-
426
- # tokenizer for preprocessing
427
- try:
428
- dummy_tok = AutoTokenizer.from_pretrained(repo_id, use_fast=True, trust_remote_code=trust_remote_code, token=HF_TOKEN)
429
- except Exception as e:
430
- msg = (f"Failed to load tokenizer for `{repo_id}`. "
431
- "If gated, accept license and set HF_TOKEN in Space → Settings → Secrets.\n\nError: " + str(e))
432
- return msg, "", "", "", None, None, None, banner_text()
433
-
434
- proc_text, tok_before, tok_after = prepare_input_text(
435
- txt, soft_cap, preprocess, pre_window, add_cues, strip_smalltalk, dummy_tok
436
- )
437
- system = (system_text or DEFAULT_SYSTEM).strip()
438
- user = (context_text or DEFAULT_CONTEXT).strip() + "\n\nTRANSCRIPT\n" + proc_text.strip()
439
 
440
- try:
441
- latency_ms, raw_text, _prompt, gpu_token_seen = gpu_generate(
442
- repo_id, system, user, load_4bit, dtype, trust_remote_code
443
- )
444
- except Exception as e:
445
- msg = (f"Failed to run `{repo_id}`. If gated, accept license and set HF_TOKEN.\n\nError: {e}")
446
- return msg, "", "", "", None, None, None, banner_text()
447
-
448
- out = safe_json_load(raw_text)
449
- pred_labels = enforce_rules(out.get("labels", []), proc_text)
450
- exact, prec, rec, f1, ham = classic_metrics(pred_labels, exp)
451
- ubs = ubs_score_one(exp, pred_labels) if exp else None
452
-
453
- kpi1 = f"**F1**\n\n{f1:.3f}" if exp else "**F1**\n\n—"
454
- kpi2 = f"**UBS score**\n\n{ubs:.3f}" if ubs is not None else "**UBS score**\n\n—"
455
- kpi3 = f"**Latency (ms)**\n\n{latency_ms}"
456
-
457
- zbuf = io.BytesIO()
458
- with zipfile.ZipFile(zbuf, "w", zipfile.ZIP_DEFLATED) as zout:
459
- zout.writestr("PREPROCESSED.txt", proc_text)
460
- zout.writestr("MODEL_OUTPUT.raw.txt", raw_text)
461
- final_json = {
462
- "labels": pred_labels,
463
- "diagnostics": {
464
- "model_name": repo_id,
465
- "latency_ms": latency_ms,
466
- "token_in_est_before": tok_before,
467
- "token_in_est_after": tok_after,
468
- "preprocess": preprocess,
469
- "pre_window": pre_window,
470
- "pre_add_cues_header": add_cues if preprocess else False,
471
- "pre_strip_smalltalk": strip_smalltalk if preprocess else False,
472
- "pre_soft_token_cap": soft_cap if preprocess else None,
473
- "model_calls": 1
474
- },
475
- "evaluation": None if not exp else {
476
- "exact_match": exact, "precision": prec, "recall": rec,
477
- "f1": f1, "hamming": ham, "ubs_score": ubs
478
- }
479
- }
480
- zout.writestr("FINAL.json", json.dumps(final_json, ensure_ascii=False, indent=2))
481
- zbuf.seek(0); zbuf.name = "artifacts_single.zip"
482
-
483
- row = pd.DataFrame([{
484
- "model": repo_id,
485
- "latency_ms": latency_ms,
486
- "token_before": tok_before,
487
- "token_after": tok_after,
488
- "model_calls": 1,
489
- "pred_labels": json.dumps(pred_labels, ensure_ascii=False),
490
- "exp_labels": json.dumps(exp, ensure_ascii=False),
491
- "exact_match": exact if exp else None,
492
- "precision": round(prec,6) if exp else None,
493
- "recall": round(rec,6) if exp else None,
494
- "f1": round(f1,6) if exp else None,
495
- "hamming": round(ham,6) if exp else None,
496
- "ubs_score": round(ubs,6) if ubs is not None else None
497
- }])
498
-
499
- csv_buf = io.BytesIO(row.to_csv(index=False).encode("utf-8")); csv_buf.name = "results_single.csv"
500
-
501
- return (
502
- "Done.",
503
- kpi1, kpi2, kpi3,
504
- row, csv_buf, zbuf,
505
- banner_text(gpu_token_seen)
506
- )
507
 
508
- # ========= Batch mode =========
509
- def run_batch_ui(models_list, custom_models_str, instructions_text, context_text, dataset_zip,
510
- soft_cap, preprocess, pre_window, add_cues, strip_smalltalk,
511
- repeats, max_total_runs, load_4bit, dtype, trust_remote_code):
512
 
513
- models = [m for m in (models_list or [])]
514
- models += [m.strip() for m in (custom_models_str or "").split(",") if m.strip()]
515
- if not models:
516
- return pd.DataFrame(), None, None, "Please pick at least one model.", banner_text()
517
 
518
- if not dataset_zip:
519
- return pd.DataFrame(), None, None, "Please upload a ZIP with *.txt (+ optional matching *.json).", banner_text()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
520
 
 
521
  try:
522
- zip_bytes = _read_zip_bytes(dataset_zip)
523
- samples = parse_zip(zip_bytes)
524
- except Exception as e:
525
- return pd.DataFrame(), None, None, f"Failed to read ZIP: {e}", banner_text()
526
-
527
- rows = []; total_runs = 0
528
- all_artifacts = io.BytesIO()
529
- zout = zipfile.ZipFile(all_artifacts, "w", zipfile.ZIP_DEFLATED)
530
- last_gpu_token_seen = None
531
-
532
- for repo_id in models:
533
- # tokenizer for preprocessing (auth check)
534
- try:
535
- dummy_tok = AutoTokenizer.from_pretrained(repo_id, use_fast=True, trust_remote_code=trust_remote_code, token=HF_TOKEN)
536
- except Exception as e:
537
- # gated or missing token; record a summary row and continue
538
- rows.append({
539
- "timestamp": pd.Timestamp.now().isoformat(timespec="seconds"),
540
- "sample_id": None,
541
- "model": repo_id,
542
- "is_summary": True,
543
- "run_index": None,
544
- "preprocess": preprocess,
545
- "pre_window": pre_window,
546
- "add_cues_header": add_cues,
547
- "strip_smalltalk": strip_smalltalk,
548
- "soft_cap": soft_cap,
549
- "median_latency_ms": None,
550
- "latency_ms": None,
551
- "token_before": None,
552
- "token_after": None,
553
- "model_calls": None,
554
- "pred_labels": "[]",
555
- "exp_labels": "[]",
556
- "exact_match": None,
557
- "precision": None,
558
- "recall": None,
559
- "f1": None,
560
- "hamming": None,
561
- "ubs_score": None,
562
- })
563
- continue
564
-
565
- for sample_id, (transcript_text, exp_labels) in samples.items():
566
- if not transcript_text.strip(): continue
567
- latencies = []; last_pred = None
568
- for r in range(1, repeats+1):
569
- if total_runs >= max_total_runs: break
570
- proc_text, before_tok, after_tok = prepare_input_text(
571
- transcript_text, soft_cap, preprocess, pre_window, add_cues, strip_smalltalk, dummy_tok
572
  )
573
- system_text = (instructions_text or DEFAULT_SYSTEM).strip()
574
- user_text = (context_text or DEFAULT_CONTEXT).strip() + "\n\nTRANSCRIPT\n" + proc_text.strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
575
 
576
- try:
577
- latency_ms, raw_text, _prompt, token_seen = gpu_generate(
578
- repo_id, system_text, user_text, load_4bit, dtype, trust_remote_code
579
- )
580
- last_gpu_token_seen = token_seen
581
- except Exception as e:
582
- base = f"{repo_id.replace('/','_')}/{sample_id}/error_r{r}"
583
- zout.writestr(base + "/ERROR.txt", f"Failed to run model via @spaces.GPU. If gated, accept license and set HF_TOKEN.\n\n{e}")
584
- total_runs += 1
585
- continue
586
-
587
- out = safe_json_load(raw_text)
588
- pred_labels = enforce_rules(out.get("labels", []), proc_text)
589
-
590
- exact, prec, rec, f1, ham = classic_metrics(pred_labels, exp_labels)
591
- ubs = ubs_score_one(exp_labels, pred_labels)
592
-
593
- rows.append({
594
- "timestamp": pd.Timestamp.now().isoformat(timespec="seconds"),
595
- "sample_id": sample_id,
596
- "model": repo_id,
597
- "is_summary": False,
598
- "run_index": r,
599
- "preprocess": preprocess,
600
- "pre_window": pre_window,
601
- "add_cues_header": add_cues,
602
- "strip_smalltalk": strip_smalltalk,
603
- "soft_cap": soft_cap,
604
- "latency_ms": latency_ms,
605
- "token_before": before_tok,
606
- "token_after": after_tok,
607
- "model_calls": 1,
608
- "pred_labels": json.dumps(pred_labels, ensure_ascii=False),
609
- "exp_labels": json.dumps(exp_labels, ensure_ascii=False),
610
- "exact_match": exact,
611
- "precision": round(prec, 6),
612
- "recall": round(rec, 6),
613
- "f1": round(f1, 6),
614
- "hamming": round(ham, 6),
615
- "ubs_score": round(ubs, 6),
616
- })
617
-
618
- base = f"{repo_id.replace('/','_')}/{sample_id}/pre{int(preprocess)}_win{pre_window}_cues{int(add_cues)}_small{int(strip_smalltalk)}_cap{soft_cap}_r{r}"
619
- zout.writestr(base + "/PREPROCESSED.txt", proc_text)
620
- zout.writestr(base + "/MODEL_OUTPUT.raw.txt", raw_text)
621
- final_json = {
622
- "labels": pred_labels,
623
- "diagnostics": {
624
- "model_name": repo_id,
625
- "latency_ms": latency_ms,
626
- "token_in_est_before": before_tok,
627
- "token_in_est_after": after_tok,
628
- "preprocess": preprocess,
629
- "pre_window": pre_window,
630
- "pre_add_cues_header": add_cues if preprocess else False,
631
- "pre_strip_smalltalk": strip_smalltalk if preprocess else False,
632
- "pre_soft_token_cap": soft_cap if preprocess else None,
633
- "model_calls": 1
634
- }
635
- }
636
- zout.writestr(base + "/FINAL.json", json.dumps(final_json, ensure_ascii=False, indent=2))
637
-
638
- latencies.append(latency_ms)
639
- last_pred = pred_labels
640
- total_runs += 1
641
-
642
- if latencies:
643
- med = int(statistics.median(latencies))
644
- exact, prec, rec, f1, ham = classic_metrics(last_pred, exp_labels) if last_pred is not None else (None,)*5
645
- ubs = ubs_score_one(exp_labels, last_pred) if last_pred is not None else None
646
- rows.append({
647
- "timestamp": pd.Timestamp.now().isoformat(timespec="seconds"),
648
- "sample_id": sample_id,
649
- "model": repo_id,
650
- "is_summary": True,
651
- "run_index": None,
652
- "preprocess": preprocess,
653
- "pre_window": pre_window,
654
- "add_cues_header": add_cues,
655
- "strip_smalltalk": strip_smalltalk,
656
- "soft_cap": soft_cap,
657
- "median_latency_ms": med,
658
- "latency_ms": None,
659
- "token_before": None,
660
- "token_after": None,
661
- "model_calls": None,
662
- "pred_labels": json.dumps(last_pred or [], ensure_ascii=False),
663
- "exp_labels": json.dumps(exp_labels or [], ensure_ascii=False),
664
- "exact_match": exact,
665
- "precision": round(prec, 6) if prec is not None else None,
666
- "recall": round(rec, 6) if rec is not None else None,
667
- "f1": round(f1, 6) if f1 is not None else None,
668
- "hamming": round(ham, 6) if ham is not None else None,
669
- "ubs_score": round(ubs, 6) if ubs is not None else None,
670
- })
671
-
672
- if total_runs >= max_total_runs:
673
- break
674
-
675
- zout.close()
676
- df = pd.DataFrame(rows)
677
- if df.empty:
678
- return pd.DataFrame(), None, None, "No runs executed (empty dataset / exceeded cap / gated models).", banner_text(last_gpu_token_seen)
679
-
680
- csv_pair = ("results.csv", df.to_csv(index=False).encode("utf-8"))
681
- zip_pair = ("artifacts.zip", all_artifacts.getvalue())
682
- return df, csv_pair, zip_pair, "Done.", banner_text(last_gpu_token_seen)
683
-
684
- # ========= UI helpers =========
685
- OPEN_MODEL_PRESETS = [
686
- "mistralai/Mistral-7B-Instruct-v0.2",
687
- "Qwen/Qwen2.5-7B-Instruct",
688
- "HuggingFaceH4/zephyr-7b-beta",
689
- "tiiuae/falcon-7b-instruct",
690
- ]
691
-
692
- def banner_text(gpu_token_seen: bool | None = None) -> str:
693
- app_seen = bool(HF_TOKEN)
694
- lines = []
695
- if not app_seen:
696
- lines.append("🟡 **HF_TOKEN not detected in App** — gated models will fail unless you set it in **Settings → Variables and secrets**.")
697
- else:
698
- lines.append("🟢 **HF_TOKEN detected in App**.")
699
- if gpu_token_seen is None:
700
- lines.append("ℹ️ ZeroGPU token status: click **Run** or **Check ZeroGPU token** to verify.")
701
- else:
702
- lines.append("🟢 **HF_TOKEN detected inside ZeroGPU job.**" if gpu_token_seen else "🔴 **HF_TOKEN missing inside ZeroGPU job** (add `secrets=[\"HF_TOKEN\"]` to @spaces.GPU).")
703
- lines.append("✅ Tip: use **Open models** (no license gating): " + ", ".join(OPEN_MODEL_PRESETS))
704
- return "\n\n".join(lines)
705
-
706
- # ========= UI (dark red) =========
707
- DARK_RED_CSS = """
708
- :root, .gradio-container {
709
- --color-background: #0b0b0d;
710
- --color-foreground: #e6e6e6;
711
- --color-primary: #e11d48;
712
- --color-secondary: #111216;
713
- --color-border: #1f2024;
714
- --color-muted: #9ca3af;
715
- }
716
- .gradio-container { background: var(--color-background) !important; color: var(--color-foreground) !important; }
717
- .gr-box, .gr-panel, .gr-group, .gr-form, .wrap.svelte-1ipelgc {
718
- background: var(--color-secondary) !important;
719
- border: 1px solid var(--color-border) !important;
720
- border-radius: 10px !important;
721
- }
722
- button, .gr-button {
723
- border-radius: 10px !important;
724
- border: 1px solid var(--color-primary) !important;
725
- background: linear-gradient(180deg, #b91c1c, #7f1d1d) !important;
726
- color: white !important;
727
- }
728
- .kpi {
729
- border: 1px solid #e11d48; border-radius: 10px; padding: 12px; text-align: center;
730
- background: #1a0f10; font-size: 18px;
731
- }
732
- """
733
 
734
- with gr.Blocks(title="From Talk to Task — HF Space", css=DARK_RED_CSS) as demo:
735
- gr.Markdown("## 🟥 From Talk to Task — Batch & Single Task Extraction")
736
- help_md = (
737
- "This tool extracts **task labels** from transcripts using Hugging Face models. \n"
738
- "1) Pick a model (or paste a custom repo id). \n"
739
- "2) Provide **Instructions** and **Context**, then supply a transcript (single) or a ZIP (batch). \n"
740
- "3) Adjust parameters (soft token cap, preprocessing). \n"
741
- "4) Run and review **latency**, **precision/recall/F1**, **UBS score**, and download artifacts."
742
- )
743
- gr.Markdown(help_md)
744
-
745
- # Status banner (token presence info)
746
- banner = gr.Markdown(banner_text())
747
-
748
- check_btn = gr.Button("Check ZeroGPU token")
749
- def _check_token():
750
- try:
751
- present = gpu_check_token()
752
- except Exception:
753
- present = None
754
- return banner_text(present)
755
- check_btn.click(_check_token, outputs=banner)
756
-
757
- with gr.Tabs():
758
- # Single
759
- with gr.TabItem("Single Transcript (default)"):
760
- with gr.Row():
761
- with gr.Column():
762
- preset_model = gr.Dropdown(choices=OPEN_MODEL_PRESETS, value=OPEN_MODEL_PRESETS[0],
763
- label="Model (Open presets — no gating)")
764
- custom_model = gr.Textbox(label="Custom model repo id (overrides preset)",
765
- placeholder="e.g. meta-llama/Meta-Llama-3-8B-Instruct")
766
- instructions = gr.Textbox(label="Instructions (System)", lines=8, value=DEFAULT_SYSTEM)
767
- context = gr.Textbox(label="Context (User prefix before transcript)", lines=6, value=DEFAULT_CONTEXT)
768
- with gr.Column():
769
- transcript_text = gr.Textbox(label="Paste transcript text", lines=14, placeholder="Paste your transcript here...")
770
- transcript_file = gr.File(label="...or upload a single transcript .txt", file_types=[".txt"], file_count="single", type="filepath")
771
- expected_labels_json = gr.File(label="(Optional) Expected labels JSON for metrics", file_types=[".json"], file_count="single", type="filepath")
772
-
773
- with gr.Row():
774
- with gr.Column():
775
- soft_cap_s = gr.Slider(1024, 32768, value=8192, step=512, label="Soft token cap")
776
- preprocess_s = gr.Checkbox(value=True, label="Enable preprocessing")
777
- pre_window_s = gr.Slider(0, 6, value=3, step=1, label="Window ± lines around cues")
778
- add_cues_s = gr.Checkbox(value=True, label="Add cues header")
779
- strip_smalltalk_s = gr.Checkbox(value=False, label="Strip smalltalk")
780
- gr.Markdown(explain_params_markdown())
781
- with gr.Column():
782
- load_4bit_s = gr.Checkbox(value=False, label="Load in 4-bit (GPU only)")
783
- dtype_s = gr.Dropdown(choices=["bfloat16","float16","float32"], value="bfloat16", label="Compute dtype")
784
- trust_remote_code_s = gr.Checkbox(value=True, label="Trust remote code")
785
-
786
- run_single_btn = gr.Button("Run (Single)")
787
- kpi1 = gr.Markdown(elem_classes=["kpi"]); kpi2 = gr.Markdown(elem_classes=["kpi"]); kpi3 = gr.Markdown(elem_classes=["kpi"])
788
- single_table = gr.Dataframe(label="Single run — metrics & diagnostics", interactive=False)
789
- single_csv = gr.File(label="Download CSV", interactive=False)
790
- single_zip = gr.File(label="Download Artifacts ZIP", interactive=False)
791
- single_status = gr.Markdown("")
792
-
793
- def _run_single(*args):
794
- status, m1, m2, m3, df, csv_buf, zip_buf, btxt = single_mode(*args)
795
- return m1 or "", m2 or "", m3 or "", (df if isinstance(df, pd.DataFrame) else pd.DataFrame()), csv_buf, zip_buf, (status or ""), (btxt or banner_text())
796
-
797
- run_single_btn.click(
798
- _run_single,
799
- inputs=[preset_model, custom_model, instructions, context,
800
- transcript_text, transcript_file, expected_labels_json,
801
- soft_cap_s, preprocess_s, pre_window_s, add_cues_s, strip_smalltalk_s,
802
- load_4bit_s, dtype_s, trust_remote_code_s],
803
- outputs=[kpi1, kpi2, kpi3, single_table, single_csv, single_zip, single_status, banner]
804
- )
805
 
806
- # Batch
807
- with gr.TabItem("Batch (ZIP of many transcripts)"):
808
- with gr.Row():
809
- with gr.Column():
810
- models_list = gr.Checkboxgroup(
811
- choices=OPEN_MODEL_PRESETS, value=[OPEN_MODEL_PRESETS[0]],
812
- label="Models (Open presets — select one or more)"
813
- )
814
- custom_models = gr.Textbox(label="Custom model repo ids (comma-separated)",
815
- placeholder="e.g. meta-llama/Meta-Llama-3-8B-Instruct, Qwen/Qwen2.5-7B-Instruct")
816
- instructions_b = gr.Textbox(label="Instructions (System)", lines=8, value=DEFAULT_SYSTEM)
817
- context_b = gr.Textbox(label="Context (User prefix before transcript)", lines=6, value=DEFAULT_CONTEXT)
818
- with gr.Column():
819
- dataset_zip = gr.File(
820
- label="Upload ZIP of transcripts (*.txt) + expected (*.json)",
821
- file_types=[".zip"], file_count="single", type="filepath"
822
- )
823
- gr.Markdown("Zip must contain pairs like `ID.txt` and optional `ID.json` with expected labels (same base filename).")
824
-
825
- with gr.Row():
826
- with gr.Column():
827
- soft_cap = gr.Slider(1024, 32768, value=8192, step=512, label="Soft token cap")
828
- preprocess = gr.Checkbox(value=True, label="Enable preprocessing")
829
- pre_window = gr.Slider(0, 6, value=3, step=1, label="Window ± lines around cues")
830
- add_cues = gr.Checkbox(value=True, label="Add cues header")
831
- strip_smalltalk = gr.Checkbox(value=False, label="Strip smalltalk")
832
- gr.Markdown(explain_params_markdown())
833
- with gr.Column():
834
- repeats = gr.Slider(1, 6, value=3, step=1, label="Repeats per config")
835
- max_total_runs = gr.Slider(1, 200, value=40, step=1, label="Max total runs")
836
- load_4bit = gr.Checkbox(value=False, label="Load in 4-bit (GPU only)")
837
- dtype = gr.Dropdown(choices=["bfloat16","float16","float32"], value="bfloat16", label="Compute dtype")
838
- trust_remote_code = gr.Checkbox(value=True, label="Trust remote code")
839
-
840
- run_btn = gr.Button("Run Batch")
841
- kpi_b1 = gr.Markdown(elem_classes=["kpi"]); kpi_b2 = gr.Markdown(elem_classes=["kpi"]); kpi_b3 = gr.Markdown(elem_classes=["kpi"])
842
- table = gr.Dataframe(label="Batch results (per run + summary rows)", interactive=False)
843
- csv_dl = gr.File(label="Download CSV", interactive=False)
844
- zip_dl = gr.File(label="Download Artifacts ZIP", interactive=False)
845
- status = gr.Markdown("")
846
-
847
- def _run_batch(*args):
848
- df, csv_pair, zip_pair, msg, btxt = run_batch_ui(*args)
849
- m1 = m2 = m3 = ""
850
- if isinstance(df, pd.DataFrame) and not df.empty:
851
- summaries = df[df["is_summary"] == True]
852
- if not summaries.empty:
853
- last = summaries.iloc[-1]
854
- f1 = last.get("f1"); ubs = last.get("ubs_score"); med = last.get("median_latency_ms")
855
- m1 = f"**F1 (last summary)**\n\n{f1:.3f}" if pd.notna(f1) else "**F1 (last summary)**\n\n—"
856
- m2 = f"**UBS (last summary)**\n\n{ubs:.3f}" if pd.notna(ubs) else "**UBS (last summary)**\n\n—"
857
- m3 = f"**Median latency (ms)**\n\n{int(med) if pd.notna(med) else '—'}"
858
- csv_buf = zip_buf = None
859
- if isinstance(csv_pair, tuple):
860
- name, data = csv_pair; csv_buf = io.BytesIO(data); csv_buf.name = name
861
- if isinstance(zip_pair, tuple):
862
- name, data = zip_pair; zip_buf = io.BytesIO(data); zip_buf.name = name
863
- return m1, m2, m3, (df if isinstance(df, pd.DataFrame) else pd.DataFrame()), csv_buf, zip_buf, (msg or ""), (btxt or banner_text())
864
-
865
- run_btn.click(
866
- _run_batch,
867
- inputs=[models_list, custom_models, instructions_b, context_b, dataset_zip,
868
- soft_cap, preprocess, pre_window, add_cues, strip_smalltalk,
869
- repeats, max_total_runs, load_4bit, dtype, trust_remote_code],
870
- outputs=[kpi_b1, kpi_b2, kpi_b3, table, csv_dl, zip_dl, status, banner]
871
- )
872
 
873
- demo.launch()
 
 
1
+ # app.py
2
+ # ---------------------------------------------------------------------------
3
+ # Talk2Task Demo (single-file, Spaces-friendly, robust model loader)
4
+ # - Loads open-source chat/instruct models (default: mistralai/Mistral-7B-Instruct-v0.2)
5
+ # - Pins model files locally via snapshot_download to avoid corrupt/partial shards
6
+ # - Optional 4-bit quant for small GPU / ZeroGPU
7
+ # - Simple "transcript -> actions JSON" generation with guardrails
8
+ # - Compact but well-commented for easy maintenance
9
+ # ---------------------------------------------------------------------------
10
+
11
+ import os
12
+ import sys
13
+ import json
14
+ import time
15
+ import re
16
+ from typing import Dict, Optional, Tuple
17
 
18
  import gradio as gr
 
 
 
19
 
20
+ # NOTE: On Spaces, 'spaces' is available. We use the GPU decorator if present.
21
  try:
22
+ from spaces import GPU # type: ignore
23
  except Exception:
24
+ # Fallback shim if not running on Spaces — decorator becomes a no-op
25
+ def GPU(*args, **kwargs):
26
+ def deco(fn):
27
+ return fn
28
+ return deco
29
+
30
+ import torch
31
+ from transformers import (
32
+ AutoTokenizer,
33
+ AutoModelForCausalLM,
34
+ BitsAndBytesConfig
35
  )
36
+ from huggingface_hub import snapshot_download
37
+
38
+
39
+ # ------------------------------
40
+ # 1) “Hardcoded revision” strategy
41
+ # ------------------------------
42
+ # We let you "hardcode" a revision per repo in this mapping. If empty/None, we default to "main".
43
+ # Best practice: keep this dict and optionally override via environment variables without editing code.
44
+ # For example, set env var MODEL_REVISION__MISTRALAI_MISTRAL_7B_INSTRUCT_V0_2="<commit-hash>"
45
+ # in the Space's "Variables and secrets".
46
+ PRESET_MODELS: Dict[str, Dict[str, Optional[str]]] = {
47
+ # Key is a human-readable label for the dropdown
48
+ "Mistral 7B Instruct v0.2": {
49
+ "repo_id": "mistralai/Mistral-7B-Instruct-v0.2",
50
+ "revision": None # leave None to use "main" by default (or override via env)
51
+ },
52
+ "Qwen2 7B Instruct": {
53
+ "repo_id": "Qwen/Qwen2-7B-Instruct",
54
+ "revision": None
55
+ },
56
+ "Zephyr 7B Beta": {
57
+ "repo_id": "HuggingFaceH4/zephyr-7b-beta",
58
+ "revision": None
59
+ },
60
+ "Falcon 7B Instruct": {
61
+ "repo_id": "tiiuae/falcon-7b-instruct",
62
+ "revision": None
63
+ },
64
+ }
65
 
66
+ # You can add/replace presets above. The loader below will:
67
+ # - Look up env var MODEL_REVISION__<REPO_ID_SLUG> if set
68
+ # - Else use the dict's "revision"
69
+ # - Else use "main"
70
+
71
+ def _slug_repo_id(repo_id: str) -> str:
72
+ """Turn 'org/model-name' into 'ORG_MODEL_NAME' for clean env var keys."""
73
+ return re.sub(r"[^A-Za-z0-9]", "_", repo_id).upper()
74
+
75
+ def resolve_revision(repo_id: str, default_revision: Optional[str]) -> str:
76
+ """
77
+ Priority order for revision:
78
+ 1) Env var MODEL_REVISION__<ORG_MODEL_SLUG>
79
+ 2) Given default_revision
80
+ 3) Fallback "main"
81
+ """
82
+ env_key = f"MODEL_REVISION__{_slug_repo_id(repo_id)}"
83
+ env_rev = os.getenv(env_key, "").strip()
84
+ if env_rev:
85
+ return env_rev
86
+ if default_revision and default_revision.strip():
87
+ return default_revision.strip()
88
+ return "main"
89
+
90
+
91
+ # ------------------------------
92
+ # 2) Space/Runtime-safe defaults
93
+ # ------------------------------
94
+ # Use the persistent storage on Spaces so model files survive restarts.
95
+ os.environ.setdefault("HF_HOME", "/data/.cache/huggingface")
96
+
97
+ # Optional token if you plan to use gated/private models in future.
98
+ HF_TOKEN = os.getenv("HF_TOKEN", None)
99
+
100
+
101
+ # ------------------------------
102
+ # 3) Minimal model wrapper with caching
103
+ # ------------------------------
104
+ MODEL_CACHE: Dict[Tuple[str, bool, str, bool, str], "HFModel"] = {}
105
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  class HFModel:
107
+ """
108
+ A small helper that:
109
+ - Downloads the full model snapshot at a specific *pinned* revision into the HF cache
110
+ - Loads tokenizer and model (optionally 4-bit)
111
+ - Exposes a simple generate_json() tailored for "Talk2Task" style outputs
112
+ """
113
+
114
+ def __init__(self,
115
+ repo_id: str,
116
+ revision: str,
117
+ load_4bit: bool = True,
118
+ dtype_str: str = "bfloat16",
119
+ trust_remote_code: bool = True):
120
  self.repo_id = repo_id
121
+ self.revision = revision
122
+ self.load_4bit = bool(load_4bit)
123
+ self.trust_remote_code = bool(trust_remote_code)
124
+
125
+ # Map dtype string to torch dtype (default to bfloat16 if unknown)
126
+ self.torch_dtype = {
127
+ "bfloat16": torch.bfloat16,
128
+ "float16": torch.float16,
129
+ "float32": torch.float32
130
+ }.get(dtype_str, torch.bfloat16)
131
+
132
+ # 3a) Materialize a clean local copy of the exact revision (no flaky shard streaming)
133
+ # 'allow_patterns' narrows downloads to typical files we need.
134
+ self.local_dir = snapshot_download(
135
+ repo_id=self.repo_id,
136
+ revision=self.revision,
137
+ allow_patterns=[
138
+ "*.json", "*.safetensors", "*.bin", "*.model",
139
+ "tokenizer.*", "config.json", "generation_config.json", "*.py"
140
+ ],
141
+ resume_download=True,
142
+ local_dir=None, # keep in HF cache path
143
+ local_dir_use_symlinks=False,
144
+ token=HF_TOKEN,
145
+ )
146
+
147
+ # 3b) Load tokenizer
148
  self.tokenizer = AutoTokenizer.from_pretrained(
149
+ self.local_dir,
150
+ use_fast=True,
151
+ trust_remote_code=self.trust_remote_code,
152
+ token=HF_TOKEN,
153
  )
 
154
 
155
+ # 3c) Load model (try 4-bit, fall back to normal if unavailable)
156
  self.model = None
157
+ if self.load_4bit:
158
  try:
159
+ qconf = BitsAndBytesConfig(
160
+ load_in_4bit=True,
161
+ bnb_4bit_use_double_quant=True,
162
+ bnb_4bit_quant_type="nf4",
163
+ bnb_4bit_compute_dtype=self.torch_dtype,
164
  )
165
  self.model = AutoModelForCausalLM.from_pretrained(
166
+ self.local_dir,
167
+ device_map="auto",
168
+ trust_remote_code=self.trust_remote_code,
169
+ quantization_config=qconf,
170
+ torch_dtype=self.torch_dtype,
171
+ token=HF_TOKEN,
172
  )
173
  except Exception as e:
174
+ print(f"[WARN] 4-bit load failed for {self.repo_id}@{self.revision}: {e}\n"
175
+ f"Falling back to standard load...", file=sys.stderr)
176
+
177
  if self.model is None:
178
  self.model = AutoModelForCausalLM.from_pretrained(
179
+ self.local_dir,
180
+ device_map="auto",
181
+ trust_remote_code=self.trust_remote_code,
182
+ torch_dtype=self.torch_dtype,
183
+ token=HF_TOKEN,
184
  )
185
 
186
+ # Useful to bound inputs for very long transcripts
187
  self.max_context = getattr(self.model.config, "max_position_embeddings", None) \
188
+ or getattr(self.model.config, "max_sequence_length", None) or 8192
189
+
190
+ def _chat_prompt(self, system_text: str, user_text: str) -> str:
191
+ """
192
+ Builds a simple chat-style prompt for instruct models.
193
+ Uses a generic format that works decently across Mistral/Qwen/Zephyr/Falcon.
194
+ """
195
+ # Keep system concise; we’ll ask for strict JSON to simplify parsing.
196
+ sys_part = (system_text or "").strip()
197
+ usr_part = (user_text or "").strip()
198
+
199
+ # A light structure that improves JSON-likeness across models:
200
+ prompt = (
201
+ f"<s>[SYSTEM]\n{sys_part}\n"
202
+ f"[/SYSTEM]\n"
203
+ f"[USER]\n{usr_part}\n[/USER]\n"
204
+ f"[ASSISTANT]\n"
205
+ )
206
+ return prompt
207
 
208
  @torch.inference_mode()
209
+ def generate_json(self,
210
+ system_text: str,
211
+ user_text: str,
212
+ max_new_tokens: int = 256,
213
+ temperature: float = 0.2,
214
+ top_p: float = 0.9) -> Tuple[float, Dict, str]:
215
+ """
216
+ Run generation and return (latency_secs, parsed_json, raw_prompt).
217
+ The JSON schema we request is:
218
+ {
219
+ "actions": [{"type": "...","details":"..."}],
220
+ "followups": [{"question":"..."}],
221
+ "implied_actions": [{"hypothesis":"..."}]
222
+ }
223
+ """
224
+ raw_prompt = self._chat_prompt(system_text, user_text)
225
+
226
+ inputs = self.tokenizer(
227
+ raw_prompt,
228
+ return_tensors="pt",
229
+ truncation=True,
230
+ max_length=min(4096, self.max_context - max_new_tokens - 8),
231
+ ).to(self.model.device)
232
+
233
+ t0 = time.time()
234
+ output_ids = self.model.generate(
235
+ **inputs,
236
+ max_new_tokens=max_new_tokens,
237
+ do_sample=(temperature > 0),
238
+ temperature=temperature,
239
+ top_p=top_p,
240
+ pad_token_id=self.tokenizer.eos_token_id or 0,
241
+ eos_token_id=self.tokenizer.eos_token_id,
242
  )
243
+ latency = time.time() - t0
244
+
245
+ full_text = self.tokenizer.decode(output_ids[0], skip_special_tokens=True)
246
+
247
+ # Heuristics to extract JSON from the assistant tail
248
+ # 1) Try last {...} block
249
+ maybe_json = None
250
+ m = re.findall(r"\{(?:[^{}]|(?R))*\}", full_text, flags=re.DOTALL)
251
+ if m:
252
+ maybe_json = m[-1]
253
+ else:
254
+ # 2) Attempt bracket capture if model used markdown code fences
255
+ m2 = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", full_text, flags=re.DOTALL | re.IGNORECASE)
256
+ if m2:
257
+ maybe_json = m2.group(1)
258
+
259
+ parsed = {}
260
+ if maybe_json:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
261
  try:
262
+ parsed = json.loads(maybe_json)
263
  except Exception:
264
+ # Light cleanup if trailing commas/comments sneak in
265
+ cleaned = re.sub(r"//.*?$", "", maybe_json, flags=re.MULTILINE)
266
+ cleaned = re.sub(r",\s*}", "}", cleaned)
267
+ cleaned = re.sub(r",\s*]", "]", cleaned)
268
+ try:
269
+ parsed = json.loads(cleaned)
270
+ except Exception:
271
+ parsed = {"_raw": full_text.strip()}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
272
  else:
273
+ parsed = {"_raw": full_text.strip()}
274
+
275
+ return latency, parsed, raw_prompt
276
+
277
+
278
+ # ------------------------------
279
+ # 4) High-level helpers
280
+ # ------------------------------
281
+ def get_or_load_model(repo_id: str,
282
+ revision: str,
283
+ load_4bit: bool,
284
+ dtype_str: str,
285
+ trust_remote_code: bool) -> HFModel:
286
+ key = (repo_id, bool(load_4bit), dtype_str, bool(trust_remote_code), revision)
287
+ if key not in MODEL_CACHE:
288
+ MODEL_CACHE[key] = HFModel(
289
+ repo_id=repo_id,
290
+ revision=revision,
291
+ load_4bit=load_4bit,
292
+ dtype_str=dtype_str,
293
+ trust_remote_code=trust_remote_code
294
+ )
295
+ return MODEL_CACHE[key]
296
+
297
+
298
+ # ------------------------------
299
+ # 5) “Business” prompt
300
+ # ------------------------------
301
+ SYSTEM_PROMPT = """You are an assistant that extracts structured actions from client transcripts.
302
+ Return STRICT JSON with keys: "actions", "followups", "implied_actions".
303
+ - "actions": list of { "type": string, "details": string }
304
+ - "followups": list of { "question": string }
305
+ - "implied_actions": list of { "hypothesis": string }
306
+ NO extra commentary. NO markdown fences. Plain JSON ONLY.
307
+ """
308
 
309
+ USER_GUIDE_TEMPLATE = """Transcript:
310
+ {transcript}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
 
312
+ Extract concrete "actions" (e.g., "Schedule meeting with John on Friday 3pm CET"; "Send portfolio summary"; "Open a ticket").
313
+ Extract clarifying "followups" as questions for the advisor.
314
+ Infer 1–3 "implied_actions" (what the client might want next).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
 
316
+ Respond as JSON only.
317
+ """
 
 
318
 
 
 
 
 
319
 
320
+ # ------------------------------
321
+ # 6) Inference functions (Spaces GPU aware)
322
+ # ------------------------------
323
+ @GPU(duration=180, enable_queue=True) # On Spaces with ZeroGPU/GPU; safe no-op elsewhere
324
+ def run_inference(preset_label: str,
325
+ transcript: str,
326
+ max_new_tokens: int,
327
+ temperature: float,
328
+ top_p: float,
329
+ load_4bit: bool,
330
+ dtype_str: str,
331
+ trust_remote_code: bool) -> Tuple[str, str, str]:
332
+ """
333
+ Main generation entry:
334
+ - Resolves repo_id + revision
335
+ - Loads (or reuses) a cached HFModel
336
+ - Runs generate_json()
337
+ - Returns pretty JSON, latency, and a minimal prompt echo for debugging
338
+ """
339
+ if not transcript.strip():
340
+ return "{}", "0.00s", "(no prompt)"
341
+
342
+ # Resolve repo + revision from preset
343
+ preset = PRESET_MODELS.get(preset_label)
344
+ if not preset:
345
+ return json.dumps({"error": f"Unknown preset: {preset_label}"}), "0.00s", "(no prompt)"
346
+
347
+ repo_id = preset["repo_id"] # type: ignore
348
+ revision = resolve_revision(repo_id, preset.get("revision")) # type: ignore
349
+
350
+ # Build user prompt
351
+ user_text = USER_GUIDE_TEMPLATE.format(transcript=transcript.strip())
352
+
353
+ # Load model and run
354
+ model = get_or_load_model(
355
+ repo_id=repo_id,
356
+ revision=revision,
357
+ load_4bit=load_4bit,
358
+ dtype_str=dtype_str,
359
+ trust_remote_code=trust_remote_code
360
+ )
361
+ latency, parsed, prompt = model.generate_json(
362
+ system_text=SYSTEM_PROMPT,
363
+ user_text=user_text,
364
+ max_new_tokens=max_new_tokens,
365
+ temperature=temperature,
366
+ top_p=top_p
367
+ )
368
 
369
+ # Pretty-print JSON for UI
370
  try:
371
+ pretty = json.dumps(parsed, indent=2, ensure_ascii=False)
372
+ except Exception:
373
+ pretty = json.dumps({"_raw": str(parsed)}, indent=2, ensure_ascii=False)
374
+
375
+ return pretty, f"{latency:.2f}s", f"repo={repo_id}@{revision} | dtype={dtype_str} | 4bit={load_4bit}"
376
+
377
+
378
+ # ------------------------------
379
+ # 7) Gradio UI
380
+ # ------------------------------
381
+ def build_ui() -> gr.Blocks:
382
+ with gr.Blocks(title="Talk2Task Demo", fill_height=True) as demo:
383
+ gr.Markdown(
384
+ """
385
+ # Talk2Task Demo
386
+ Paste a short client transcript. The model will extract structured **Actions JSON**.
387
+ - **Model** is pinned via snapshot download for reliability on Spaces.
388
+ - Use the advanced options if you want to try different sampling or 4-bit.
389
+ """
390
+ )
391
+
392
+ with gr.Row():
393
+ with gr.Column(scale=1):
394
+ preset = gr.Dropdown(
395
+ label="Model preset",
396
+ choices=list(PRESET_MODELS.keys()),
397
+ value="Mistral 7B Instruct v0.2"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
398
  )
399
+ transcript = gr.Textbox(
400
+ label="Transcript",
401
+ lines=10,
402
+ placeholder="Paste a client conversation or notes here…"
403
+ )
404
+ run_btn = gr.Button("Extract Actions", variant="primary")
405
+
406
+ with gr.Accordion("Advanced", open=False):
407
+ max_new = gr.Slider(64, 512, value=256, step=16, label="Max new tokens")
408
+ temperature = gr.Slider(0.0, 1.5, value=0.2, step=0.05, label="Temperature")
409
+ top_p = gr.Slider(0.1, 1.0, value=0.9, step=0.05, label="Top-p")
410
+ load_4bit = gr.Checkbox(value=True, label="Load in 4-bit (fallback to full if not available)")
411
+ dtype = gr.Radio(choices=["bfloat16", "float16", "float32"], value="bfloat16", label="Torch dtype")
412
+ trust_rc = gr.Checkbox(value=True, label="trust_remote_code (required by some repos)")
413
+
414
+ with gr.Column(scale=1):
415
+ out_json = gr.Code(label="Actions JSON", language="json", interactive=False)
416
+ with gr.Row():
417
+ latency = gr.Textbox(label="Latency", interactive=False)
418
+ meta = gr.Textbox(label="Model info", interactive=False)
419
+
420
+ # Wire up the click
421
+ run_btn.click(
422
+ fn=run_inference,
423
+ inputs=[preset, transcript, max_new, temperature, top_p, load_4bit, dtype, trust_rc],
424
+ outputs=[out_json, latency, meta]
425
+ )
426
 
427
+ gr.Markdown(
428
+ """
429
+ **Tips**
430
+ - To pin a *specific* commit without editing code, set an env var in Space settings like:
431
+ `MODEL_REVISION__MISTRALAI_MISTRAL_7B_INSTRUCT_V0_2 = <commit-hash>`
432
+ - If you later add a gated/private model, set a secret **HF_TOKEN** as well.
433
+ """
434
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
435
 
436
+ return demo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
438
 
439
+ if __name__ == "__main__":
440
+ build_ui().launch(server_name="0.0.0.0", server_port=int(os.getenv("PORT", "7860")))