nrr26 commited on
Commit
8416a0e
·
verified ·
1 Parent(s): baeb37f

Restaurant Complaint Tagger: diner tips and owner best next action

Browse files
Files changed (3) hide show
  1. README.md +16 -5
  2. app.py +244 -0
  3. requirements.txt +6 -0
README.md CHANGED
@@ -1,13 +1,24 @@
1
  ---
2
- title: Complaint Tagger
3
- emoji: ⚡
4
- colorFrom: pink
5
  colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 6.31.0
8
- python_version: '3.13'
9
  app_file: app.py
10
  pinned: false
 
 
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Restaurant Complaint Tagger
3
+ emoji: 🍽️
4
+ colorFrom: red
5
  colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 6.31.0
8
+ python_version: "3.11"
9
  app_file: app.py
10
  pinned: false
11
+ license: mit
12
+ short_description: Paste bad restaurant reviews, see what to fix first
13
+ models:
14
+ - nrr26/yelp-complaint-tagger
15
  ---
16
 
17
+ # Restaurant Complaint Tagger
18
+
19
+ Paste your 1-2 star reviews. The page tags each complaint (wait time, staff attitude, food quality, order accuracy, price, hygiene, ambience, billing), counts them, and suggests what to fix first.
20
+
21
+ - Model: [nrr26/yelp-complaint-tagger](https://huggingface.co/nrr26/yelp-complaint-tagger) (CC BY-NC 4.0)
22
+ - Code: [github.com/namsarena/yelp-complaint-tagger](https://github.com/namsarena/yelp-complaint-tagger) (MIT)
23
+
24
+ A learning project, not production software. Use it on negative reviews only; reviews you paste are processed in memory and not stored by this app.
app.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Restaurant Complaint Tagger: a page for diners and owners on top of nrr26/yelp-complaint-tagger."""
2
+ import gradio as gr
3
+ import matplotlib
4
+ import pandas as pd
5
+ import torch
6
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
7
+
8
+ matplotlib.use("Agg")
9
+ import matplotlib.pyplot as plt
10
+
11
+ REPO = "nrr26/yelp-complaint-tagger"
12
+ MAX_REVIEWS = 200
13
+ MAX_CHARS = 2000
14
+
15
+ tok = AutoTokenizer.from_pretrained(REPO)
16
+ model = AutoModelForSequenceClassification.from_pretrained(REPO).eval()
17
+ THRESHOLDS = model.config.label_thresholds
18
+ LABELS = list(model.config.id2label.values())
19
+
20
+ NAMES = {
21
+ "wait_time": "Wait time",
22
+ "staff_attitude": "Staff attitude",
23
+ "food_quality": "Food quality",
24
+ "order_accuracy": "Order accuracy",
25
+ "price_value": "Price and value",
26
+ "hygiene_safety": "Hygiene and safety",
27
+ "ambience": "Ambience",
28
+ "billing_policy": "Billing and policy",
29
+ }
30
+
31
+ # What an owner can do about each problem; a starting checklist, not professional advice.
32
+ PLAYBOOK = {
33
+ "wait_time": ["Check staffing against your busiest hours", "Have a host greet and seat guests within 2 minutes",
34
+ "Time orders from ticket to table and set a target"],
35
+ "staff_attitude": ["Share the exact review quotes at the next team huddle", "Run a 15-minute refresher on greeting and handling complaints",
36
+ "Give a manager the job of checking in with every table"],
37
+ "food_quality": ["Taste-check the dishes named in reviews before each service", "Check holding times and temperatures for hot food",
38
+ "Ask the kitchen lead which recipe or supplier changed recently"],
39
+ "order_accuracy": ["Read orders back to guests and double-check takeout bags", "Add a final check at the pass before food leaves",
40
+ "Mark sold-out items on the menu and POS right away"],
41
+ "price_value": ["Compare portions and prices with 2-3 nearby competitors", "Make sure portions match the menu photos and descriptions",
42
+ "Highlight a good-value option on the menu"],
43
+ "hygiene_safety": ["Treat any illness report seriously: follow up with the guest and review food-safety logs",
44
+ "Add hourly checks for tables and restrooms", "Book a deep clean if several reviews mention dirt or pests"],
45
+ "ambience": ["Turn music down during dinner and test it from the tables", "Check temperature and seating comfort at peak times",
46
+ "Fix the specific issue reviews mention (noise, smell, lighting)"],
47
+ "billing_policy": ["Have a manager review every charge complaint within 24 hours", "Write down your refund and reservation policies and train staff on them",
48
+ "Check that the POS discounts and splits work correctly"],
49
+ }
50
+
51
+
52
+ # Heads-up tips for someone deciding where to eat, based only on the complaints pasted in.
53
+ DINER_TIPS = {
54
+ "wait_time": "Expect waits. Book ahead or go outside peak hours.",
55
+ "staff_attitude": "Some diners complain about service. If service matters for your occasion, go at a quieter time or consider another spot.",
56
+ "food_quality": "Reviewers mention food problems. Look at recent photos and order the dishes others praise.",
57
+ "order_accuracy": "Orders sometimes come out wrong. Check takeout and delivery orders before you leave.",
58
+ "price_value": "Some diners find it overpriced. Check the menu prices before you go.",
59
+ "hygiene_safety": "There are cleanliness or food-safety complaints. Check the latest local health inspection results first.",
60
+ "ambience": "Noise or comfort complaints. Ask for a quieter table, or pick another place for a long conversation.",
61
+ "billing_policy": "Billing complaints. Check your bill, and ask about deposits or cancellation rules up front.",
62
+ }
63
+
64
+ # Fictional restaurants with review sets written for the demo.
65
+ SAMPLES = {
66
+ "Tamarind & Tandoor · San Jose, CA · Indian": """The butter chicken was bland and the naan was burnt on one side.
67
+ Biryani was dry and the rice tasted reheated.
68
+ Waited 40 minutes for our food on a quiet Tuesday.
69
+ The paneer tikka was cold in the middle.
70
+ Samosas were greasy and stale.""",
71
+ "Pacific Patty Shack · Los Angeles, CA · American": """Waited over an hour for two burgers and fries.
72
+ Nobody took our order for 25 minutes after we sat down.
73
+ The line was out the door and only one cashier was working.
74
+ Our milkshakes took 20 minutes and the burger was overcooked.
75
+ We were seated quickly but then forgotten for half an hour.""",
76
+ "Cascade Pasta Co. · Seattle, WA · Italian": """$34 for a small plate of spaghetti. Not worth it.
77
+ Tiny portions for the price, we left hungry.
78
+ The tiramisu was $16 and the size of a matchbox.
79
+ Overpriced wine and the lasagna was just okay.
80
+ Paid $90 for two people and still went for pizza after.""",
81
+ "Pike Spice House · Seattle, WA · Indian": """Ordered lamb vindaloo for delivery and got chicken korma instead.
82
+ Our order was missing the garlic naan and the raita.
83
+ They forgot the rice with both curries.
84
+ Asked for mild and got extra spicy. Wrong order again.
85
+ Half the menu was sold out on a Friday night.""",
86
+ "Mulberry Row Trattoria · New York, NY · Italian": """The waiter rolled his eyes when we asked about gluten-free pasta.
87
+ Hostess was rude and told us to hurry up and order.
88
+ They charged us for bread we never ordered and the manager refused to remove it.
89
+ Our server was dismissive and never smiled once.
90
+ We were overcharged on the wine and had to argue to get it fixed.""",
91
+ "Hudson Corner Diner · Brooklyn, NY · American": """Found a hair in my pancakes and the table was sticky.
92
+ The restroom was filthy and had no soap.
93
+ Saw a cockroach near the booth by the window.
94
+ Music was so loud we could not hear each other.
95
+ I got food poisoning after the chicken sandwich.""",
96
+ }
97
+
98
+
99
+ def score(texts):
100
+ """Probability per label for each text."""
101
+ out = []
102
+ for i in range(0, len(texts), 16):
103
+ enc = tok(texts[i:i + 16], return_tensors="pt", truncation=True, max_length=384, padding=True)
104
+ with torch.no_grad():
105
+ out.extend(torch.sigmoid(model(**enc).logits).tolist())
106
+ return out
107
+
108
+
109
+ def tag_review(review: str) -> dict:
110
+ """Tag the complaint types in one negative restaurant review.
111
+
112
+ Args:
113
+ review: The text of one 1-2 star restaurant review, in English.
114
+
115
+ Returns:
116
+ A dict of complaint types found (wait_time, staff_attitude, food_quality, order_accuracy,
117
+ price_value, hygiene_safety, ambience, billing_policy) mapped to the model's confidence (0-1).
118
+ """
119
+ review = (review or "").strip()[:MAX_CHARS]
120
+ if not review:
121
+ return {}
122
+ p = score([review])[0]
123
+ return {l: round(p[i], 2) for i, l in enumerate(LABELS) if p[i] > THRESHOLDS[l]}
124
+
125
+
126
+ def _analyse(reviews):
127
+ """Split pasted text into reviews and tag each one."""
128
+ lines = [l.strip()[:MAX_CHARS] for l in (reviews or "").splitlines() if l.strip()][:MAX_REVIEWS]
129
+ probs = score(lines) if lines else []
130
+ found = [[l for i, l in enumerate(LABELS) if p[i] > THRESHOLDS[l]] for p in probs]
131
+ counts = pd.Series([l for f in found for l in f], dtype=object).value_counts()
132
+ return lines, found, counts
133
+
134
+
135
+ def _chart(counts, title):
136
+ if not len(counts):
137
+ return None
138
+ fig, ax = plt.subplots(figsize=(7, 0.5 * len(counts) + 1.2))
139
+ order = counts.sort_values()
140
+ ax.barh([NAMES[l] for l in order.index], order.values, color="#C8323C")
141
+ ax.set_title(title, loc="left", fontsize=12)
142
+ ax.set_xlabel("Reviews mentioning it")
143
+ ax.xaxis.get_major_locator().set_params(integer=True)
144
+ for side in ("top", "right"):
145
+ ax.spines[side].set_visible(False)
146
+ fig.tight_layout()
147
+ return fig
148
+
149
+
150
+ def _table(lines, found):
151
+ return pd.DataFrame({"Review": lines, "Problems": [", ".join(NAMES[l] for l in f) or "None found" for f in found]})
152
+
153
+
154
+ EMPTY = "Paste at least one review, one per line, or pick a sample restaurant."
155
+
156
+
157
+ def owner_report(reviews: str):
158
+ """For restaurant owners: tag 1-2 star reviews (one per line), count the complaints and give the best next action.
159
+
160
+ Args:
161
+ reviews: Several 1-2 star reviews of one restaurant, one review per line.
162
+
163
+ Returns:
164
+ A plain-English action plan (best next action plus the top 3 problems with steps), a chart of
165
+ complaint counts, and a table of each review with its complaint types.
166
+ """
167
+ lines, found, counts = _analyse(reviews)
168
+ if not lines:
169
+ return EMPTY, None, pd.DataFrame(columns=["Review", "Problems"])
170
+ if not len(counts):
171
+ return ("No complaints found. This tool is built for 1-2 star reviews; happy reviews usually show nothing.",
172
+ None, _table(lines, found))
173
+ top, n = counts.index[0], int(counts.iloc[0])
174
+ parts = [f"## Best next action\n**{PLAYBOOK[top][0]}**\n\n"
175
+ f"Why: {NAMES[top].lower()} comes up in {n} of {len(lines)} reviews, more than anything else.\n",
176
+ "## Top problems and what to do"]
177
+ for rank, (label, c) in enumerate(counts.head(3).items(), 1):
178
+ parts.append(f"### {rank}. {NAMES[label]} ({c} of {len(lines)} reviews)")
179
+ parts.extend(f"- {a}" for a in PLAYBOOK[label])
180
+ parts.append("")
181
+ parts.append("_A starting checklist, not professional advice. Run it again next week to see if the top bar got smaller._")
182
+ return "\n".join(parts), _chart(counts, "What customers complain about"), _table(lines, found)
183
+
184
+
185
+ def diner_tips(reviews: str):
186
+ """For diners: summarise what people complain about at a restaurant and give practical tips before visiting.
187
+
188
+ Args:
189
+ reviews: Several 1-2 star reviews of one restaurant, one review per line.
190
+
191
+ Returns:
192
+ Plain-English tips for a visitor, based only on the complaints provided, and a chart of complaint counts.
193
+ """
194
+ lines, found, counts = _analyse(reviews)
195
+ if not lines:
196
+ return EMPTY, None
197
+ if not len(counts):
198
+ return "No clear complaints in these reviews.", None
199
+ parts = [f"## Before you go\nBased on **{len(lines)} negative reviews**, here is what people complain about most:\n"]
200
+ for label, c in counts.head(3).items():
201
+ parts.append(f"- **{NAMES[label]}** ({c} of {len(lines)}): {DINER_TIPS[label]}")
202
+ parts.append("\n_These tips only reflect the complaints you pasted. Read recent positive reviews too before deciding._")
203
+ return "\n".join(parts), _chart(counts, "What diners complain about")
204
+
205
+
206
+ def load_sample(name):
207
+ return SAMPLES.get(name, "")
208
+
209
+
210
+ with gr.Blocks(title="Restaurant Complaint Tagger") as demo:
211
+ gr.Markdown(
212
+ "# Restaurant Complaint Tagger\n"
213
+ "Paste a restaurant's **1-2 star reviews**, one per line, and see what people complain about.\n\n"
214
+ "A learning project · [model](https://huggingface.co/nrr26/yelp-complaint-tagger) (non-commercial) · "
215
+ "[code](https://github.com/namsarena/yelp-complaint-tagger) · reviews you paste are not stored by this app"
216
+ )
217
+ with gr.Tab("For diners"):
218
+ gr.Markdown("Thinking of eating somewhere? Paste its bad reviews and get a quick heads-up.")
219
+ d_pick = gr.Dropdown(list(SAMPLES), label="Or try a sample restaurant (fictional)", value=None)
220
+ d_box = gr.Textbox(label="Reviews (one per line, up to 200)", lines=8, placeholder="Paste reviews here...")
221
+ d_run = gr.Button("Show me what to expect", variant="primary")
222
+ d_tips = gr.Markdown()
223
+ d_chart = gr.Plot(label="Complaints")
224
+ d_pick.change(load_sample, inputs=d_pick, outputs=d_box, api_visibility="private")
225
+ d_run.click(diner_tips, inputs=d_box, outputs=[d_tips, d_chart])
226
+ with gr.Tab("For restaurant owners"):
227
+ gr.Markdown("Paste this week's 1-2 star reviews and get your best next action.")
228
+ o_pick = gr.Dropdown(list(SAMPLES), label="Or try a sample restaurant (fictional)", value=None)
229
+ o_box = gr.Textbox(label="Reviews (one per line, up to 200)", lines=8, placeholder="Paste reviews here...")
230
+ o_run = gr.Button("Find my best next action", variant="primary")
231
+ o_plan = gr.Markdown()
232
+ o_chart = gr.Plot(label="Complaints this week")
233
+ o_table = gr.Dataframe(label="Each review", wrap=True)
234
+ o_pick.change(load_sample, inputs=o_pick, outputs=o_box, api_visibility="private")
235
+ o_run.click(owner_report, inputs=o_box, outputs=[o_plan, o_chart, o_table])
236
+ gr.api(tag_review)
237
+ gr.Markdown(
238
+ "**Limits:** built for complaints only (4-5 star reviews may get false tags), can misread negation "
239
+ "(\"not rude\"), may tag food quality when the real problem is a wrong order, and learned from "
240
+ "AI-labelled examples. English only. Sample restaurants and their reviews are fictional."
241
+ )
242
+
243
+ if __name__ == "__main__":
244
+ demo.launch(mcp_server=True)
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cpu
2
+ torch
3
+ transformers>=4.45
4
+ pandas
5
+ matplotlib
6
+ gradio[mcp]==6.31.0