eliel2003 commited on
Commit
7b51cb7
Β·
verified Β·
1 Parent(s): 64a8d0c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +320 -67
app.py CHANGED
@@ -1,6 +1,6 @@
1
  # ================================================================
2
  # ProSync AI β€” The Event Producer's Command Center
3
- # CPU-only deployment. Clean & Stable.
4
  # ================================================================
5
 
6
  import os
@@ -16,19 +16,25 @@ from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
16
  import spaces
17
 
18
  warnings.filterwarnings("ignore")
 
 
19
 
20
- os.environ["CUDA_VISIBLE_DEVICES"] = ""
21
- os.environ["TOKENIZERS_PARALLELISM"] = "false"
22
-
23
  @spaces.GPU
24
  def dummy_gpu_function():
25
  pass
26
 
27
- HF_TOKEN = os.environ.get("HF_TOKEN", "")
 
28
  EMBED_MODEL_ID = "sentence-transformers/all-MiniLM-L6-v2"
29
  GEN_MODEL_ID = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
30
  GEN_MODEL_API = "HuggingFaceH4/zephyr-7b-beta"
31
 
 
 
 
 
 
32
  VENDOR_CATEGORIES = [
33
  "Catering", "AV_Technology", "Venue", "Security",
34
  "Photography_Video", "Entertainment", "Logistics",
@@ -46,13 +52,12 @@ ALLOC_RATIOS = {
46
  CITIES = ["Beer Sheva", "Haifa", "Herzliya", "Jerusalem",
47
  "Netanya", "Petah Tikva", "Ramat Gan", "Tel Aviv"]
48
  SEASONS = ["Winter", "Spring", "Summer", "Fall"]
49
-
50
  EVENT_TYPES = [
51
  "Annual Conference", "Award Ceremony", "Bar/Bat Mitzvah", "Brand Activation",
52
- "Corporate Gala", "Family Reunion", "Investor Day", "Private Birthday",
53
- "Product Launch", "Team Building", "Tech Summit", "Trade Show", "Wedding", "Workshop Series",
 
54
  ]
55
-
56
  QUICK_STARTERS = [
57
  {
58
  "label": "πŸ™οΈ Tech Summit Β· Tel Aviv",
@@ -82,16 +87,20 @@ QUICK_STARTERS = [
82
  "notes": "Outdoor venue preferred. Vegetarian options required.",
83
  },
84
  {
85
- "label": "πŸ’ Boutique Wedding",
86
  "brief": "Intimate outdoor wedding β€” elegant catering, DJ, floral design, "
87
  "photography, and logistics for 250 guests.",
88
  "city": "Netanya", "season": "Spring", "budget": 120_000,
89
  "type": "Wedding", "guests": 250,
90
  "date": "May 14, 2027", "venue": "Private Estate, Kfar Yona Area",
91
  "notes": "Chuppah at sunset. Vegan and gluten-free menu options required.",
92
- }
93
  ]
94
 
 
 
 
 
95
  def _to_list(val):
96
  if isinstance(val, list): return val
97
  if isinstance(val, str):
@@ -125,6 +134,10 @@ except FileNotFoundError:
125
  print("❌ dataset_b_vendors.csv not found.")
126
  _df = None
127
 
 
 
 
 
128
  print("⏳ Loading embedding model …")
129
  _embed = SentenceTransformer(EMBED_MODEL_ID, device="cpu")
130
 
@@ -136,9 +149,14 @@ if _df is not None:
136
  normalize_embeddings=True, convert_to_tensor=True,
137
  device="cpu",
138
  )
 
139
  else:
140
  _vemb = None
141
 
 
 
 
 
142
  _gen_backend = "none"
143
  _gen_model = None
144
  _gen_tok = None
@@ -147,42 +165,74 @@ _gen_client = None
147
  if HF_TOKEN:
148
  try:
149
  from huggingface_hub import InferenceClient
150
- _gen_client = InferenceClient(model=GEN_MODEL_API, token=HF_TOKEN)
 
 
151
  _gen_backend = "api"
152
- except Exception: pass
 
 
153
 
154
  if _gen_backend == "none":
155
  try:
 
156
  _gen_tok = AutoTokenizer.from_pretrained(GEN_MODEL_ID)
157
  _gen_raw = AutoModelForCausalLM.from_pretrained(
158
  GEN_MODEL_ID, torch_dtype=torch.float32, low_cpu_mem_usage=True,
159
  )
160
- _gen_model = pipeline("text-generation", model=_gen_raw, tokenizer=_gen_tok, device=-1)
 
 
 
161
  _gen_backend = "local"
162
- except Exception: pass
 
 
163
 
 
164
  def _call_llm(prompt: str, max_new_tokens: int = 450) -> str:
165
  if _gen_backend == "api":
166
- try:
167
- return _gen_client.text_generation(prompt, max_new_tokens=max_new_tokens, temperature=0.7, do_sample=True).strip()
168
- except Exception as e:
169
- return f"⚠️ API Error:\n{str(e)}\n\n(Please check if your HF_TOKEN is valid and has 'Read' access.)"
 
 
 
 
 
 
 
 
 
170
  if _gen_backend == "local" and _gen_model is not None:
171
  try:
172
- out = _gen_model(prompt, max_new_tokens=max_new_tokens, do_sample=True, temperature=0.7, pad_token_id=_gen_tok.eos_token_id, return_full_text=False)
 
 
 
 
 
173
  return out[0]["generated_text"].strip()
174
  except Exception as e:
175
- return f"⚠️ Local Model Error:\n{str(e)}"
176
- return "⚠️ Generation not available. Add HF_TOKEN as a Space Secret to enable."
 
 
177
 
178
  def _prompt(system: str, user: str) -> str:
179
- if _gen_backend == "api":
180
- return f"<|system|>\n{system}</s>\n<|user|>\n{user}</s>\n<|assistant|>\n"
181
- return f"<|system|>\n{system}</s>\n<|user|>\n{user}</s>\n<|assistant|>\n"
 
 
 
 
 
182
 
183
  def recommend_vendors(brief, city, season, budget, top_n=3):
184
  if _df is None or _vemb is None:
185
- return {"error": "Vendor data not loaded."}
186
  if not brief.strip():
187
  return {"error": "Please enter an event description."}
188
 
@@ -194,9 +244,15 @@ def recommend_vendors(brief, city, season, budget, top_n=3):
194
  pool_idx = _VIDX[combined].tolist()
195
 
196
  if not pool_idx:
197
- return {"error": "No vendors matched all filters. Try a different city or higher budget."}
198
-
199
- q = _embed.encode(brief, convert_to_tensor=True, normalize_embeddings=True, device="cpu")
 
 
 
 
 
 
200
  sims = st_util.cos_sim(q, _vemb[pool_idx])[0].cpu().numpy()
201
 
202
  pool = _df.iloc[pool_idx].copy().reset_index(drop=True)
@@ -214,17 +270,70 @@ def recommend_vendors(brief, city, season, budget, top_n=3):
214
  ]].to_dict("records")
215
  return results
216
 
 
217
  def gen_run_of_show(ev_type, date, venue, city, guests, vendors, notes):
218
- lines = "\n".join(f" - {k.replace('_', ' ')}: {v}" for k, v in vendors.items())
219
- return _call_llm(_prompt("You are a senior event production manager. Write a detailed Run of Show using format HH:MM β€” Task.", f"Event: {ev_type}\nDate: {date}\nVenue: {venue}, {city}\nGuests: {guests:,}\nNotes: {notes or 'None'}\n\nVendors:\n{lines}"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
 
221
  def gen_rfp(name, cat, specs, ev_type, date, city, guests, alloc_usd, notes):
222
- return _call_llm(_prompt("You are a professional event producer writing a formal RFP (Request for Proposal) email to a vendor.", f"Vendor: {name}\nCategory: {cat.replace('_', ' ')}\nEvent: {ev_type}\nDate: {date}\nLocation: {city}\nGuests: {guests:,}\nBudget: ${alloc_usd:,.0f}\nRequirements: {notes or 'Standard service'}"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
 
224
  def _stars(r):
225
  n = min(5, max(0, int(round(float(r)))))
226
  return "β˜…" * n + "β˜†" * (5 - n)
227
 
 
228
  def _fmt_vendors(recs, budget):
229
  if "error" in recs:
230
  return f"### ⚠️ No Results\n\n```\n{recs['error']}\n```"
@@ -233,23 +342,37 @@ def _fmt_vendors(recs, budget):
233
  if cat not in recs: continue
234
  alloc = budget * ALLOC_RATIOS[cat]
235
  cat_name = cat.replace("_", " ")
236
- lines.append(f"### {CATEGORY_EMOJI[cat]} {cat_name} Β· Budget: ${alloc:,.0f}\n")
 
 
237
  for i, v in enumerate(recs[cat], 1):
238
  sp = v.get("specializations", [])
239
  if isinstance(sp, str):
240
  try: sp = json.loads(sp)
241
  except: sp = []
242
  sc = v.get("final_score", v.get("similarity", 0))
243
- lines.append(f"**#{i} {v['vendor_name']}**\n{_stars(v.get('avg_rating', 0))} Β· ${v.get('day_rate_mid', 0):,.0f}/day Β· Match `{sc:.3f}`\n\n*{', '.join(sp[:2]) if sp else 'β€”'}*\n")
 
 
 
 
 
 
244
  lines.append("---\n")
245
  return "\n".join(lines) or "_No results._"
246
 
247
- def handle_submit(brief, city, season, budget, ev_type, date, venue, guests, notes):
 
 
 
 
 
248
  recs = recommend_vendors(brief, city, season, float(budget))
249
  vendor_md = _fmt_vendors(recs, float(budget))
250
 
251
  if "error" in recs or _gen_backend == "none":
252
- msg = recs.get("error", "") or "Add HF_TOKEN to enable document generation."
 
253
  return vendor_md, msg, msg
254
 
255
  selected, targets = {}, []
@@ -262,17 +385,29 @@ def handle_submit(brief, city, season, budget, ev_type, date, venue, guests, not
262
  try: sp = json.loads(sp)
263
  except: sp = []
264
  selected[cat] = name
265
- targets.append({"name": name, "cat": cat, "specs": sp, "alloc": float(budget) * ALLOC_RATIOS[cat]})
 
 
 
266
 
267
- ros = gen_run_of_show(ev_type, date, venue, city, int(guests), selected, notes)
 
268
 
269
  blocks = []
270
  for t in sorted(targets, key=lambda x: -x["alloc"])[:3]:
271
- txt = gen_rfp(t["name"], t["cat"], t["specs"], ev_type, date, city, int(guests), t["alloc"], notes)
272
- blocks.append(f"{'═'*54}\n RFP β€” {t['cat'].replace('_',' ').upper()}\n TO : {t['name']}\n{'═'*54}\n\n" + txt + "\n")
273
-
 
 
 
 
 
 
 
274
  return vendor_md, ros, "\n\n".join(blocks)
275
 
 
276
  def _qs(idx):
277
  q = QUICK_STARTERS[idx]
278
  b, c, s, bu = q["brief"], q["city"], q["season"], q["budget"]
@@ -286,49 +421,164 @@ def _qs1(): return _qs(1)
286
  def _qs2(): return _qs(2)
287
  def _qs3(): return _qs(3)
288
 
 
 
 
 
289
  CSS = """
290
- body, .gradio-container { background-color: #FAF7F2 !important; font-family: 'Inter', sans-serif !important; color: #2C1810 !important; }
291
- .ps-header { background: linear-gradient(135deg, #3D2314 0%, #7A4E2D 60%, #B8895A 100%); border-radius: 16px; padding: 36px 40px; margin-bottom: 20px; box-shadow: 0 8px 32px rgba(61,35,20,.25); color: white; }
292
- .ps-header h1 { font-family: 'Playfair Display', serif; font-size: 2.4rem; margin: 0 0 6px; }
293
- .qs-btn { background: #F5EFE6 !important; border: 1.5px solid #D4B896 !important; color: #5C3D1E !important; border-radius: 10px !important; padding: 10px 16px !important; }
294
- .submit-btn { background: linear-gradient(135deg, #5C3D1E 0%, #8B6239 100%) !important; color: #FAF7F2 !important; border-radius: 12px !important; padding: 14px 28px !important; width: 100% !important; margin-top: 8px !important; }
295
- .status-bar { background: #F5EFE6; border: 1px solid #DDD0BE; border-radius: 8px; padding: 8px 14px; font-size: .82rem; color: #7A4E2D; margin-bottom: 14px; }
296
- .ps-footer { text-align: center; color: #A68B6A; font-size: .78rem; margin-top: 28px; border-top: 1px solid #EDE0CE; padding-top: 14px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
297
  """
298
 
299
- with gr.Blocks(css=CSS, title="ProSync AI") as demo:
300
- gr.HTML("""<div class="ps-header"><h1>🎯 ProSync AI</h1><p>The Event Producer's Command Center</p></div>""")
301
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
302
  with gr.Row():
303
  qs0 = gr.Button(QUICK_STARTERS[0]["label"], elem_classes=["qs-btn"])
304
  qs1 = gr.Button(QUICK_STARTERS[1]["label"], elem_classes=["qs-btn"])
 
305
  qs2 = gr.Button(QUICK_STARTERS[2]["label"], elem_classes=["qs-btn"])
306
  qs3 = gr.Button(QUICK_STARTERS[3]["label"], elem_classes=["qs-btn"])
307
 
308
- brief = gr.Textbox(label="Describe your event", lines=4)
 
 
 
 
 
 
309
  with gr.Row():
310
- city = gr.Dropdown(label="City", choices=CITIES, value="Tel Aviv")
311
- season = gr.Dropdown(label="Season", choices=SEASONS, value="Summer")
312
- budget = gr.Slider(label="Total Budget (USD)", minimum=20_000, maximum=600_000, step=5_000, value=200_000)
 
 
 
 
 
313
 
314
  with gr.Row():
315
- ev_type = gr.Dropdown(label="Event Type", choices=EVENT_TYPES, value="Tech Summit")
316
- guests = gr.Number(label="Guest Count", value=300)
 
 
317
  with gr.Row():
318
- date = gr.Textbox(label="Event Date", value="October 15, 2026")
319
- venue = gr.Textbox(label="Venue Name", value="Grand Convention Center")
320
- notes = gr.Textbox(label="Special Requirements", lines=2)
321
- submit = gr.Button("✨ Find Vendors & Generate Documents", elem_classes=["submit-btn"])
 
 
 
 
 
 
 
322
 
 
323
  gr.Markdown("### πŸͺ Vendor Matches")
324
- vendor_out = gr.Markdown(value="_Complete the form above to see recommendations._")
325
-
 
 
 
326
  gr.Markdown("### πŸ“‹ Run of Show")
327
- ros_out = gr.Textbox(label="", lines=15, interactive=False)
328
-
 
 
 
329
  gr.Markdown("### βœ‰οΈ RFP Emails")
330
- rfp_out = gr.Textbox(label="", lines=15, interactive=False)
 
 
 
331
 
 
 
 
 
332
  _in = [brief, city, season, budget, ev_type, date, venue, guests, notes]
333
  _out = [vendor_out, ros_out, rfp_out]
334
  _form = [brief, city, season, budget, ev_type, date, venue, guests, notes]
@@ -339,5 +589,8 @@ with gr.Blocks(css=CSS, title="ProSync AI") as demo:
339
  qs2.click(fn=_qs2, outputs=_form + _out)
340
  qs3.click(fn=_qs3, outputs=_form + _out)
341
 
 
342
  if __name__ == "__main__":
343
- demo.launch()
 
 
 
1
  # ================================================================
2
  # ProSync AI β€” The Event Producer's Command Center
3
+ # Handles both B2B (Corporate) and B2C (Private) events.
4
  # ================================================================
5
 
6
  import os
 
16
  import spaces
17
 
18
  warnings.filterwarnings("ignore")
19
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
20
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
21
 
22
+ # Required by HF GPU Space infrastructure β€” do not remove
 
 
23
  @spaces.GPU
24
  def dummy_gpu_function():
25
  pass
26
 
27
+ # ── Config ────────────────────────────────────────────────────
28
+ HF_TOKEN = os.environ.get("HF_TOKEN", "")
29
  EMBED_MODEL_ID = "sentence-transformers/all-MiniLM-L6-v2"
30
  GEN_MODEL_ID = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
31
  GEN_MODEL_API = "HuggingFaceH4/zephyr-7b-beta"
32
 
33
+ # Private events get a different (warmer, personal) prompt tone
34
+ PRIVATE_EVENT_TYPES = {
35
+ "Wedding", "Bar/Bat Mitzvah", "Private Birthday", "Family Reunion"
36
+ }
37
+
38
  VENDOR_CATEGORIES = [
39
  "Catering", "AV_Technology", "Venue", "Security",
40
  "Photography_Video", "Entertainment", "Logistics",
 
52
  CITIES = ["Beer Sheva", "Haifa", "Herzliya", "Jerusalem",
53
  "Netanya", "Petah Tikva", "Ramat Gan", "Tel Aviv"]
54
  SEASONS = ["Winter", "Spring", "Summer", "Fall"]
 
55
  EVENT_TYPES = [
56
  "Annual Conference", "Award Ceremony", "Bar/Bat Mitzvah", "Brand Activation",
57
+ "Corporate Gala", "Family Reunion", "Investor Day", "Private Birthday",
58
+ "Product Launch", "Team Building", "Tech Summit", "Trade Show",
59
+ "Wedding", "Workshop Series",
60
  ]
 
61
  QUICK_STARTERS = [
62
  {
63
  "label": "πŸ™οΈ Tech Summit Β· Tel Aviv",
 
87
  "notes": "Outdoor venue preferred. Vegetarian options required.",
88
  },
89
  {
90
+ "label": "πŸ’ Boutique Wedding Β· Netanya",
91
  "brief": "Intimate outdoor wedding β€” elegant catering, DJ, floral design, "
92
  "photography, and logistics for 250 guests.",
93
  "city": "Netanya", "season": "Spring", "budget": 120_000,
94
  "type": "Wedding", "guests": 250,
95
  "date": "May 14, 2027", "venue": "Private Estate, Kfar Yona Area",
96
  "notes": "Chuppah at sunset. Vegan and gluten-free menu options required.",
97
+ },
98
  ]
99
 
100
+ # ================================================================
101
+ # DATA β€” module level (no race condition)
102
+ # ================================================================
103
+
104
  def _to_list(val):
105
  if isinstance(val, list): return val
106
  if isinstance(val, str):
 
134
  print("❌ dataset_b_vendors.csv not found.")
135
  _df = None
136
 
137
+ # ================================================================
138
+ # EMBEDDING MODEL β€” CPU
139
+ # ================================================================
140
+
141
  print("⏳ Loading embedding model …")
142
  _embed = SentenceTransformer(EMBED_MODEL_ID, device="cpu")
143
 
 
149
  normalize_embeddings=True, convert_to_tensor=True,
150
  device="cpu",
151
  )
152
+ print(f"βœ… Embeddings: {_vemb.shape}")
153
  else:
154
  _vemb = None
155
 
156
+ # ================================================================
157
+ # GENERATION MODEL β€” with retry logic
158
+ # ================================================================
159
+
160
  _gen_backend = "none"
161
  _gen_model = None
162
  _gen_tok = None
 
165
  if HF_TOKEN:
166
  try:
167
  from huggingface_hub import InferenceClient
168
+ _gen_client = InferenceClient(
169
+ model=GEN_MODEL_API, token=HF_TOKEN, timeout=30,
170
+ )
171
  _gen_backend = "api"
172
+ print(f"βœ… Generation: HF Inference API ({GEN_MODEL_API})")
173
+ except Exception as e:
174
+ print(f"⚠️ HF API unavailable: {e}")
175
 
176
  if _gen_backend == "none":
177
  try:
178
+ print(f"⏳ Loading {GEN_MODEL_ID} on CPU …")
179
  _gen_tok = AutoTokenizer.from_pretrained(GEN_MODEL_ID)
180
  _gen_raw = AutoModelForCausalLM.from_pretrained(
181
  GEN_MODEL_ID, torch_dtype=torch.float32, low_cpu_mem_usage=True,
182
  )
183
+ _gen_model = pipeline(
184
+ "text-generation", model=_gen_raw,
185
+ tokenizer=_gen_tok, device=-1,
186
+ )
187
  _gen_backend = "local"
188
+ print("βœ… Generation model ready (CPU).")
189
+ except Exception as e:
190
+ print(f"⚠️ Generation unavailable: {e}")
191
 
192
+ # ── Retry wrapper (handles transient API drops) ───────────────
193
  def _call_llm(prompt: str, max_new_tokens: int = 450) -> str:
194
  if _gen_backend == "api":
195
+ last_err = None
196
+ for attempt in range(3): # 3 attempts, 2s gap
197
+ try:
198
+ return _gen_client.text_generation(
199
+ prompt, max_new_tokens=max_new_tokens,
200
+ temperature=0.7, repetition_penalty=1.1, do_sample=True,
201
+ ).strip()
202
+ except Exception as e:
203
+ last_err = e
204
+ import time; time.sleep(2 * (attempt + 1)) # 2s, 4s, 6s
205
+ return (f"⚠️ API failed after 3 attempts:\n{last_err}\n\n"
206
+ f"Check that your HF_TOKEN has 'Read' access.")
207
+
208
  if _gen_backend == "local" and _gen_model is not None:
209
  try:
210
+ out = _gen_model(
211
+ prompt, max_new_tokens=max_new_tokens, do_sample=True,
212
+ temperature=0.7, repetition_penalty=1.15,
213
+ pad_token_id=_gen_tok.eos_token_id,
214
+ return_full_text=False,
215
+ )
216
  return out[0]["generated_text"].strip()
217
  except Exception as e:
218
+ return f"⚠️ Local model error: {e}"
219
+
220
+ return "⚠️ Generation not available. Add HF_TOKEN as a Space Secret."
221
+
222
 
223
  def _prompt(system: str, user: str) -> str:
224
+ """Zephyr / TinyLlama chat template."""
225
+ return (f"<|system|>\n{system}</s>\n"
226
+ f"<|user|>\n{user}</s>\n"
227
+ f"<|assistant|>\n")
228
+
229
+ # ================================================================
230
+ # CORE ENGINE
231
+ # ================================================================
232
 
233
  def recommend_vendors(brief, city, season, budget, top_n=3):
234
  if _df is None or _vemb is None:
235
+ return {"error": "Vendor data not loaded. Check dataset_b_vendors.csv."}
236
  if not brief.strip():
237
  return {"error": "Please enter an event description."}
238
 
 
244
  pool_idx = _VIDX[combined].tolist()
245
 
246
  if not pool_idx:
247
+ return {"error": (
248
+ f"No vendors matched all filters "
249
+ f"(city: {int(city_ok.sum())}, season: {int(season_ok.sum())}, "
250
+ f"budget: {int(budget_ok.sum())}, combined: 0). "
251
+ f"Try a larger budget or a different city."
252
+ )}
253
+
254
+ q = _embed.encode(brief, convert_to_tensor=True,
255
+ normalize_embeddings=True, device="cpu")
256
  sims = st_util.cos_sim(q, _vemb[pool_idx])[0].cpu().numpy()
257
 
258
  pool = _df.iloc[pool_idx].copy().reset_index(drop=True)
 
270
  ]].to_dict("records")
271
  return results
272
 
273
+
274
  def gen_run_of_show(ev_type, date, venue, city, guests, vendors, notes):
275
+ """Context-aware: uses celebratory tone for private events."""
276
+ is_private = ev_type in PRIVATE_EVENT_TYPES
277
+ tone = (
278
+ "This is a personal life event. Use a warm, celebratory tone. "
279
+ "Include milestones like ceremony, first dance, toasts."
280
+ if is_private else
281
+ "This is a professional corporate event. Use formal operational language."
282
+ )
283
+ lines = "\n".join(f" - {k.replace('_', ' ')}: {v}"
284
+ for k, v in vendors.items())
285
+ return _call_llm(_prompt(
286
+ f"You are a senior event production manager. Write a detailed Run of Show "
287
+ f"using format HH:MM β€” Task. {tone}",
288
+ f"Event: {ev_type}\nDate: {date}\nVenue: {venue}, {city}\n"
289
+ f"Guests: {guests:,}\nNotes: {notes or 'None'}\n\nVendors:\n{lines}"
290
+ ), max_new_tokens=600)
291
+
292
 
293
  def gen_rfp(name, cat, specs, ev_type, date, city, guests, alloc_usd, notes):
294
+ """B2B tone for corporate events, warm personal tone for private events."""
295
+ is_private = ev_type in PRIVATE_EVENT_TYPES
296
+ specs_str = ", ".join(specs[:3]) if specs else "general services"
297
+ cat_label = cat.replace("_", " ")
298
+
299
+ if is_private:
300
+ system_msg = (
301
+ "You are a warm and professional event coordinator helping a private client "
302
+ "reach out to a vendor. Write a friendly but professional inquiry email. "
303
+ "Use a personal, human tone β€” this is a meaningful personal life event."
304
+ )
305
+ user_msg = (
306
+ f"Write a vendor inquiry email for a {ev_type} on {date} in {city}.\n\n"
307
+ f"Vendor: {name}\nCategory: {cat_label}\nSpecialisms: {specs_str}\n"
308
+ f"Guest count: {guests:,}\nBudget for this service: ${alloc_usd:,.0f}\n"
309
+ f"Special requests: {notes or 'None'}\n\n"
310
+ f"Keep the tone warm and celebratory. Request availability and a quote, "
311
+ f"and express genuine excitement about the event."
312
+ )
313
+ else:
314
+ system_msg = (
315
+ "You are a professional event producer writing a formal B2B RFP email. "
316
+ "Be specific and professional. End with a clear call to action requesting "
317
+ "availability and a detailed quote within 48 hours."
318
+ )
319
+ user_msg = (
320
+ f"Write a formal RFP email to:\n\n"
321
+ f"Vendor: {name}\nCategory: {cat_label}\nSpecialisms: {specs_str}\n\n"
322
+ f"Event: {ev_type}\nDate: {date}\nLocation: {city}\n"
323
+ f"Guests: {guests:,}\nBudget: ${alloc_usd:,.0f} for {cat_label}\n"
324
+ f"Requirements: {notes or 'Standard professional service'}"
325
+ )
326
+ return _call_llm(_prompt(system_msg, user_msg), max_new_tokens=400)
327
+
328
+ # ================================================================
329
+ # OUTPUT FORMATTERS
330
+ # ================================================================
331
 
332
  def _stars(r):
333
  n = min(5, max(0, int(round(float(r)))))
334
  return "β˜…" * n + "β˜†" * (5 - n)
335
 
336
+
337
  def _fmt_vendors(recs, budget):
338
  if "error" in recs:
339
  return f"### ⚠️ No Results\n\n```\n{recs['error']}\n```"
 
342
  if cat not in recs: continue
343
  alloc = budget * ALLOC_RATIOS[cat]
344
  cat_name = cat.replace("_", " ")
345
+ lines.append(
346
+ f"### {CATEGORY_EMOJI[cat]} {cat_name} Β· Budget: ${alloc:,.0f}\n"
347
+ )
348
  for i, v in enumerate(recs[cat], 1):
349
  sp = v.get("specializations", [])
350
  if isinstance(sp, str):
351
  try: sp = json.loads(sp)
352
  except: sp = []
353
  sc = v.get("final_score", v.get("similarity", 0))
354
+ lines.append(
355
+ f"**#{i} {v['vendor_name']}**\n"
356
+ f"{_stars(v.get('avg_rating', 0))} Β· "
357
+ f"${v.get('day_rate_mid', 0):,.0f}/day Β· "
358
+ f"Match `{sc:.3f}`\n\n"
359
+ f"*{', '.join(sp[:2]) if sp else 'β€”'}*\n"
360
+ )
361
  lines.append("---\n")
362
  return "\n".join(lines) or "_No results._"
363
 
364
+ # ================================================================
365
+ # GRADIO HANDLER
366
+ # ================================================================
367
+
368
+ def handle_submit(brief, city, season, budget, ev_type, date, venue,
369
+ guests, notes):
370
  recs = recommend_vendors(brief, city, season, float(budget))
371
  vendor_md = _fmt_vendors(recs, float(budget))
372
 
373
  if "error" in recs or _gen_backend == "none":
374
+ msg = (recs.get("error", "") or
375
+ "Add HF_TOKEN as a Space Secret to enable document generation.")
376
  return vendor_md, msg, msg
377
 
378
  selected, targets = {}, []
 
385
  try: sp = json.loads(sp)
386
  except: sp = []
387
  selected[cat] = name
388
+ targets.append({
389
+ "name": name, "cat": cat, "specs": sp,
390
+ "alloc": float(budget) * ALLOC_RATIOS[cat],
391
+ })
392
 
393
+ ros = gen_run_of_show(ev_type, date, venue, city,
394
+ int(guests), selected, notes)
395
 
396
  blocks = []
397
  for t in sorted(targets, key=lambda x: -x["alloc"])[:3]:
398
+ txt = gen_rfp(
399
+ t["name"], t["cat"], t["specs"],
400
+ ev_type, date, city, int(guests), t["alloc"], notes,
401
+ )
402
+ cat_label = t["cat"].replace("_", " ")
403
+ blocks.append(
404
+ f"{'═'*54}\n RFP β€” {cat_label.upper()}\n"
405
+ f" TO : {t['name']}\n BUDGET: ${t['alloc']:,.0f}\n"
406
+ f"{'═'*54}\n\n" + txt + "\n"
407
+ )
408
  return vendor_md, ros, "\n\n".join(blocks)
409
 
410
+
411
  def _qs(idx):
412
  q = QUICK_STARTERS[idx]
413
  b, c, s, bu = q["brief"], q["city"], q["season"], q["budget"]
 
421
  def _qs2(): return _qs(2)
422
  def _qs3(): return _qs(3)
423
 
424
+ # ================================================================
425
+ # CSS
426
+ # ================================================================
427
+
428
  CSS = """
429
+ @import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;600;700&family=Inter:wght@300;400;500;600&display=swap');
430
+ body, .gradio-container {
431
+ background-color: #FAF7F2 !important;
432
+ font-family: 'Inter', sans-serif !important;
433
+ color: #2C1810 !important;
434
+ }
435
+ .ps-header {
436
+ background: linear-gradient(135deg, #3D2314 0%, #7A4E2D 60%, #B8895A 100%);
437
+ border-radius: 16px; padding: 36px 40px; margin-bottom: 20px;
438
+ box-shadow: 0 8px 32px rgba(61,35,20,.25); color: white;
439
+ }
440
+ .ps-header h1 {
441
+ font-family: 'Playfair Display', serif;
442
+ font-size: 2.4rem; margin: 0 0 6px; letter-spacing: .5px;
443
+ }
444
+ .ps-header p { color: #DDD0BE; font-size: 1.05rem; margin: 0; }
445
+ label span, .label-wrap span {
446
+ font-weight: 500 !important; font-size: .88rem !important;
447
+ color: #5C3D1E !important; text-transform: uppercase !important;
448
+ letter-spacing: .4px !important;
449
+ }
450
+ textarea, input[type="text"], input[type="number"] {
451
+ background: #FFFFFF !important; border: 1.5px solid #DDD0BE !important;
452
+ border-radius: 10px !important; color: #2C1810 !important;
453
+ }
454
+ textarea:focus, input:focus {
455
+ border-color: #B8895A !important;
456
+ box-shadow: 0 0 0 3px rgba(184,137,90,.12) !important;
457
+ }
458
+ input[type="range"] { accent-color: #B8895A !important; }
459
+ .qs-btn {
460
+ background: #F5EFE6 !important; border: 1.5px solid #D4B896 !important;
461
+ color: #5C3D1E !important; border-radius: 10px !important;
462
+ font-weight: 500 !important; transition: all .2s !important;
463
+ }
464
+ .qs-btn:hover {
465
+ background: #EDE0CE !important; border-color: #B8895A !important;
466
+ transform: translateY(-1px) !important;
467
+ }
468
+ .submit-btn {
469
+ background: linear-gradient(135deg, #5C3D1E 0%, #8B6239 100%) !important;
470
+ color: #FAF7F2 !important; font-size: 1.05rem !important;
471
+ font-weight: 600 !important; border: none !important;
472
+ border-radius: 12px !important; padding: 14px 28px !important;
473
+ width: 100% !important; margin-top: 8px !important;
474
+ box-shadow: 0 4px 16px rgba(61,35,20,.25) !important;
475
+ }
476
+ .submit-btn:hover {
477
+ background: linear-gradient(135deg, #3D2314 0%, #7A4E2D 100%) !important;
478
+ transform: translateY(-1px) !important;
479
+ }
480
+ .status-bar {
481
+ background: #F5EFE6; border: 1px solid #DDD0BE; border-radius: 8px;
482
+ padding: 8px 14px; font-size: .82rem; color: #7A4E2D; margin-bottom: 14px;
483
+ }
484
+ .prose, .markdown-body { font-family: 'Inter', sans-serif !important;
485
+ color: #2C1810 !important; line-height: 1.7 !important; }
486
+ .prose h3 { color: #5C3D1E !important;
487
+ border-bottom: 1px solid #DDD0BE; padding-bottom: 4px; }
488
+ .prose code { background: #F5EFE6 !important; color: #7A4E2D !important;
489
+ border-radius: 4px !important; padding: 1px 5px !important; }
490
+ .ps-footer {
491
+ text-align: center; color: #A68B6A; font-size: .78rem;
492
+ margin-top: 28px; border-top: 1px solid #EDE0CE; padding-top: 14px;
493
+ }
494
  """
495
 
496
+ _status = (
497
+ f"Vendors: {'βœ… ' + str(len(_df)) + ' loaded' if _df is not None else '❌ not found'} Β· "
498
+ f"Embeddings: {'βœ…' if _vemb is not None else '❌'} Β· "
499
+ f"Generation: {_gen_backend}"
500
+ )
501
+
502
+ # ================================================================
503
+ # UI
504
+ # ================================================================
505
+
506
+ with gr.Blocks(css=CSS, theme=gr.themes.Base(), title="ProSync AI") as demo:
507
+
508
+ gr.HTML("""
509
+ <div class="ps-header">
510
+ <h1>🎯 ProSync AI</h1>
511
+ <p>The Event Producer's Command Center β€” intelligent vendor matching &amp; automated document generation</p>
512
+ </div>
513
+ """)
514
+ gr.HTML(f'<div class="status-bar">System Β· {_status}</div>')
515
+
516
+ gr.Markdown("#### ⚑ Quick Starters β€” click to auto-fill and run")
517
  with gr.Row():
518
  qs0 = gr.Button(QUICK_STARTERS[0]["label"], elem_classes=["qs-btn"])
519
  qs1 = gr.Button(QUICK_STARTERS[1]["label"], elem_classes=["qs-btn"])
520
+ with gr.Row():
521
  qs2 = gr.Button(QUICK_STARTERS[2]["label"], elem_classes=["qs-btn"])
522
  qs3 = gr.Button(QUICK_STARTERS[3]["label"], elem_classes=["qs-btn"])
523
 
524
+ gr.Markdown("---")
525
+
526
+ brief = gr.Textbox(
527
+ label="Describe your event", lines=4,
528
+ placeholder="e.g. Tech summit for 400 guests β€” advanced AV, live streaming, "
529
+ "kosher catering, VIP security…",
530
+ )
531
  with gr.Row():
532
+ city = gr.Dropdown(label="City", choices=CITIES, value="Tel Aviv")
533
+ season = gr.Dropdown(label="Season", choices=SEASONS, value="Summer")
534
+ budget = gr.Slider(
535
+ label="Total Budget (USD)",
536
+ minimum=20_000, maximum=600_000, step=5_000, value=200_000,
537
+ )
538
+
539
+ gr.Markdown("---")
540
 
541
  with gr.Row():
542
+ ev_type = gr.Dropdown(
543
+ label="Event Type", choices=EVENT_TYPES, value="Tech Summit",
544
+ )
545
+ guests = gr.Number(label="Guest Count", value=300, minimum=10, maximum=5000)
546
  with gr.Row():
547
+ date = gr.Textbox(label="Event Date", value="October 15, 2026")
548
+ venue = gr.Textbox(label="Venue Name", value="Grand Convention Center")
549
+ notes = gr.Textbox(
550
+ label="Special Requirements",
551
+ placeholder="e.g. Kosher catering, black-tie dress code, vegan menu…",
552
+ lines=2,
553
+ )
554
+ submit = gr.Button(
555
+ "✨ Find Vendors & Generate Documents",
556
+ elem_classes=["submit-btn"],
557
+ )
558
 
559
+ gr.Markdown("---")
560
  gr.Markdown("### πŸͺ Vendor Matches")
561
+ vendor_out = gr.Markdown(
562
+ value="_Complete the form above to see recommendations._",
563
+ elem_classes=["prose"],
564
+ )
565
+
566
  gr.Markdown("### πŸ“‹ Run of Show")
567
+ ros_out = gr.Textbox(
568
+ label="", lines=18, interactive=False,
569
+ placeholder="Generated schedule will appear here…",
570
+ )
571
+
572
  gr.Markdown("### βœ‰οΈ RFP Emails")
573
+ rfp_out = gr.Textbox(
574
+ label="", lines=18, interactive=False,
575
+ placeholder="Generated emails will appear here…",
576
+ )
577
 
578
+ gr.HTML('<div class="ps-footer">ProSync AI Β· Gradio + HuggingFace Β· '
579
+ 'MiniLM-L6-v2 Β· TinyLlama / Zephyr-7B</div>')
580
+
581
+ # ── Wiring ────────────────────────────────────────────────
582
  _in = [brief, city, season, budget, ev_type, date, venue, guests, notes]
583
  _out = [vendor_out, ros_out, rfp_out]
584
  _form = [brief, city, season, budget, ev_type, date, venue, guests, notes]
 
589
  qs2.click(fn=_qs2, outputs=_form + _out)
590
  qs3.click(fn=_qs3, outputs=_form + _out)
591
 
592
+
593
  if __name__ == "__main__":
594
+ # server_name="0.0.0.0" is required on HF Spaces β€”
595
+ # without it Gradio raises ValueError: When localhost is not accessible
596
+ demo.launch(server_name="0.0.0.0", server_port=7860)