Amey9766 commited on
Commit
fb65e89
·
verified ·
1 Parent(s): 445b7b8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +113 -18
app.py CHANGED
@@ -1,27 +1,122 @@
 
1
  import os
 
 
2
  import torch
3
- from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig
 
4
 
 
5
  MODEL_ID = "Amey9766/llama32B-hospitality-review-triage"
6
- HF_TOKEN = os.getenv("HF_TOKEN")
7
 
8
- tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, token=HF_TOKEN)
 
9
 
10
- config = AutoConfig.from_pretrained(MODEL_ID, token=HF_TOKEN)
11
 
12
- # IMPORTANT: remove quantization_config cleanly
13
- if hasattr(config, "quantization_config"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  try:
15
- delattr(config, "quantization_config") # best option
 
16
  except Exception:
17
- config.quantization_config = {} # fallback
18
-
19
- model = AutoModelForCausalLM.from_pretrained(
20
- MODEL_ID,
21
- token=HF_TOKEN,
22
- config=config,
23
- quantization_config=None, # prevents auto-quant logic
24
- device_map="auto",
25
- dtype=torch.float16 if torch.cuda.is_available() else torch.float32
26
- )
27
- model.eval()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
  import os
3
+ import re
4
+ import json
5
  import torch
6
+ import gradio as gr
7
+ from transformers import AutoTokenizer, AutoModelForCausalLM
8
 
9
+ # ✅ Your model repo (exact)
10
  MODEL_ID = "Amey9766/llama32B-hospitality-review-triage"
 
11
 
12
+ # If your model is private/gated, add HF_TOKEN as a Space Secret
13
+ HF_TOKEN = os.getenv("HF_TOKEN", None)
14
 
 
15
 
16
+ def extract_first_json(text: str) -> str:
17
+ """
18
+ Extract the first JSON object from a string. Falls back to raw text.
19
+ """
20
+ match = re.search(r"\{.*\}", text, flags=re.S)
21
+ return match.group(0) if match else text
22
+
23
+
24
+ def load_model():
25
+ """
26
+ Load tokenizer/model once. Keep it simple: no 4-bit, no bitsandbytes.
27
+ This avoids the bitsandbytes / quantization crashes on Spaces.
28
+ """
29
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, token=HF_TOKEN)
30
+
31
+ # Ensure pad token is set
32
+ if tokenizer.pad_token is None:
33
+ tokenizer.pad_token = tokenizer.eos_token
34
+
35
+ model = AutoModelForCausalLM.from_pretrained(
36
+ MODEL_ID,
37
+ token=HF_TOKEN,
38
+ device_map="auto",
39
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
40
+ )
41
+ model.eval()
42
+ return tokenizer, model
43
+
44
+
45
+ tokenizer, model = load_model()
46
+
47
+
48
+ def triage(review_text: str, max_new_tokens: int = 256, temperature: float = 0.0):
49
+ if not review_text or not review_text.strip():
50
+ return "Please enter a hotel review."
51
+
52
+ messages = [
53
+ {
54
+ "role": "system",
55
+ "content": (
56
+ "You are a hospitality review triage assistant. "
57
+ "Output ONLY valid JSON (no extra text)."
58
+ ),
59
+ },
60
+ {"role": "user", "content": review_text.strip()},
61
+ ]
62
+
63
+ prompt = tokenizer.apply_chat_template(messages, tokenize=False)
64
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
65
+
66
+ do_sample = float(temperature) > 0.0
67
+
68
+ with torch.no_grad():
69
+ output_ids = model.generate(
70
+ **inputs,
71
+ max_new_tokens=int(max_new_tokens),
72
+ do_sample=do_sample,
73
+ temperature=float(temperature) if do_sample else None,
74
+ pad_token_id=tokenizer.eos_token_id,
75
+ )
76
+
77
+ decoded = tokenizer.decode(output_ids[0], skip_special_tokens=True)
78
+
79
+ # Try to isolate JSON and pretty print it
80
+ json_text = extract_first_json(decoded)
81
  try:
82
+ obj = json.loads(json_text)
83
+ return json.dumps(obj, indent=2)
84
  except Exception:
85
+ return json_text
86
+
87
+
88
+ # ✅ Gradio UI
89
+ with gr.Blocks(title="Hospitality Review Triage") as demo:
90
+ gr.Markdown("# 🏨 Hospitality Review → JSON Triage")
91
+ gr.Markdown(
92
+ "Paste a guest review and get structured JSON for routing/triage. "
93
+ "The model is instructed to output **JSON only**."
94
+ )
95
+
96
+ review_in = gr.Textbox(
97
+ label="Guest Review",
98
+ lines=6,
99
+ placeholder="Example: The room was dirty and the AC didn’t work. Front desk didn’t respond.",
100
+ )
101
+
102
+ with gr.Row():
103
+ max_tokens = gr.Slider(64, 512, value=256, step=32, label="Max new tokens")
104
+ temp = gr.Slider(0.0, 1.0, value=0.0, step=0.1, label="Temperature")
105
+
106
+ output = gr.Code(label="JSON Output", language="json")
107
+
108
+ btn = gr.Button("Generate JSON", variant="primary")
109
+ btn.click(triage, inputs=[review_in, max_tokens, temp], outputs=output)
110
+
111
+ gr.Examples(
112
+ examples=[
113
+ ["The room was dirty and the AC didn’t work. I called twice and no one came."],
114
+ ["Great location and staff were friendly, but breakfast was overpriced and slow."],
115
+ ["I found bugs in the bathroom. This is unacceptable and I want a refund."],
116
+ ["Noise from the hallway kept us awake all night. The bed was uncomfortable."],
117
+ ],
118
+ inputs=review_in,
119
+ label="Try examples",
120
+ )
121
+
122
+ demo.launch()