eliel2003 commited on
Commit
024c8d5
Β·
verified Β·
1 Parent(s): a5718f1

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +632 -361
app.py CHANGED
@@ -1,18 +1,21 @@
1
- # ============================================================
2
  # ProSync AI β€” The Event Producer's Command Center
3
- # Gradio application for Hugging Face Spaces
4
  #
5
- # File layout (all files in the same Space directory):
6
- # app.py
7
- # dataset_b_vendors.csv ← read locally, no remote fetch
8
- # dataset_a_events.csv
9
- # requirements.txt
10
- #
11
- # Space Secret (Settings β†’ Secrets):
12
- # HF_TOKEN β†’ your HF token (optional β€” enables Mistral API)
13
- # ============================================================
14
-
15
- import spaces # must be first β€” HF GPU Spaces require this
 
 
 
16
 
17
  import os
18
  import json
@@ -20,65 +23,86 @@ import warnings
20
 
21
  import numpy as np
22
  import pandas as pd
 
23
  import gradio as gr
 
 
 
 
 
 
24
 
25
  warnings.filterwarnings("ignore")
26
 
27
- # ── Config from Space Secrets ──────────────────────────────────
28
- HF_TOKEN = os.environ.get("HF_TOKEN", "")
29
- EMBED_MODEL_ID = "sentence-transformers/all-MiniLM-L6-v2"
30
- GEN_MODEL_LOCAL = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
31
- GEN_MODEL_API = "mistralai/Mistral-7B-Instruct-v0.2"
32
 
33
  VENDOR_CATEGORIES = [
34
  "Catering", "AV_Technology", "Venue", "Security",
35
  "Photography_Video", "Entertainment", "Logistics",
36
  ]
37
  CATEGORY_EMOJI = {
38
- "Catering": "🍽️", "AV_Technology": "🎬", "Venue": "πŸ›οΈ",
39
- "Security": "πŸ›‘οΈ", "Photography_Video": "πŸ“·",
40
  "Entertainment": "🎭", "Logistics": "🚚",
41
  }
42
  ALLOC_RATIOS = {
43
- "Catering": 0.304, "Venue": 0.228, "AV_Technology": 0.175,
44
- "Entertainment": 0.104, "Photography_Video": 0.076,
45
- "Logistics": 0.057, "Security": 0.057,
46
  }
47
- CITIES = ["Beer Sheva", "Haifa", "Herzliya", "Jerusalem",
48
- "Netanya", "Petah Tikva", "Ramat Gan", "Tel Aviv"]
49
- SEASONS = ["Winter", "Spring", "Summer", "Fall"]
50
  EVENT_TYPES = [
51
- "Annual Conference", "Award Ceremony", "Brand Activation",
52
- "Corporate Gala", "Investor Day", "Product Launch",
53
- "Team Building", "Tech Summit", "Trade Show", "Workshop Series",
54
  ]
 
55
  QUICK_STARTERS = [
56
- [
57
- "Large-scale tech summit with advanced AV production, LED walls, "
58
- "live streaming, kosher catering for 400 guests, VIP executive security.",
59
- "Tel Aviv", "Summer", 250_000,
60
- ],
61
- [
62
- "Elegant corporate gala for 200 guests β€” plated fine dining, "
63
- "live band entertainment, professional photography and videography.",
64
- "Jerusalem", "Winter", 140_000,
65
- ],
66
- [
67
- "Outdoor team building day for 150 employees β€” interactive entertainment, "
68
- "DJ, logistics coordination, casual catering.",
69
- "Haifa", "Spring", 65_000,
70
- ],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  ]
72
 
73
- # ── Module-level singletons ────────────────────────────────────
74
- _df_vendors = None
75
- _embed_model = None
76
- _vendor_embeddings = None
77
- _vcities = _vseasons = _vcats = _vrates = _vcomp = _vidx = None
78
- _gen_backend = _gen_model = _gen_tokenizer = _gen_client = None
79
 
 
 
 
80
 
81
  def _safe_to_list(val) -> list:
 
82
  if isinstance(val, list):
83
  return val
84
  if isinstance(val, str):
@@ -90,107 +114,113 @@ def _safe_to_list(val) -> list:
90
  return []
91
 
92
 
93
- # ============================================================
94
- # DEFERRED STARTUP (called via demo.load β€” models load after Gradio starts)
95
- # ============================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
- def load_all():
98
- global _df_vendors, _embed_model, _vendor_embeddings
99
- global _vcities, _vseasons, _vcats, _vrates, _vcomp, _vidx
100
- global _gen_backend, _gen_model, _gen_tokenizer, _gen_client
101
 
102
- # 1. Dataset β€” read directly from the Space directory
103
- try:
104
- _df_vendors = pd.read_csv("dataset_b_vendors.csv")
105
- print(f"βœ… Dataset: {len(_df_vendors):,} vendors")
106
- except FileNotFoundError:
107
- print("❌ dataset_b_vendors.csv not found. "
108
- "Make sure it is uploaded to the Space Files tab.")
109
- return
110
- except Exception as e:
111
- print(f"❌ Dataset failed: {e}")
112
- return
113
-
114
- for col in ["coverage_cities", "seasonal_availability",
115
- "specializations", "certifications"]:
116
- _df_vendors[col] = _df_vendors[col].apply(_safe_to_list)
117
-
118
- _df_vendors["day_rate_mid"] = (
119
- (_df_vendors["day_rate_min_usd"] + _df_vendors["day_rate_max_usd"]) / 2
120
- )
121
- rmin = _df_vendors["avg_rating"].min()
122
- rmax = _df_vendors["avg_rating"].max()
123
- _df_vendors["rating_norm"] = (_df_vendors["avg_rating"] - rmin) / (rmax - rmin + 1e-9)
124
- _df_vendors["value_score"] = 1 - (_df_vendors["price_tier"] - 1) / 4
125
- _df_vendors["composite_score"] = (
126
- 0.4 * _df_vendors["rating_norm"]
127
- + 0.4 * _df_vendors["sla_compliance_rate"]
128
- + 0.2 * _df_vendors["value_score"]
129
- )
130
- _vcities = _df_vendors["coverage_cities"].tolist()
131
- _vseasons = _df_vendors["seasonal_availability"].tolist()
132
- _vcats = _df_vendors["category"].values
133
- _vrates = _df_vendors["day_rate_mid"].values
134
- _vcomp = _df_vendors["composite_score"].values
135
- _vidx = np.arange(len(_df_vendors))
136
-
137
- # 2. Embedding model β€” torch imported inside function, not at module level
138
- try:
139
- import torch
140
- from sentence_transformers import SentenceTransformer
141
- _embed_model = SentenceTransformer(EMBED_MODEL_ID)
142
- texts = _df_vendors["vendor_profile_text"].tolist()
143
- _vendor_embeddings = _embed_model.encode(
144
- texts, batch_size=64, show_progress_bar=False,
145
- convert_to_tensor=True, normalize_embeddings=True,
146
- )
147
- print(f"βœ… Embeddings: {_vendor_embeddings.shape}")
148
- except Exception as e:
149
- print(f"❌ Embedding model failed: {e}")
150
 
151
- # 3. Generation model
152
- if HF_TOKEN:
153
- try:
154
- from huggingface_hub import InferenceClient
155
- _gen_client = InferenceClient(model=GEN_MODEL_API, token=HF_TOKEN)
156
- _gen_backend = "api"
157
- print(f"βœ… Generation: HF API ({GEN_MODEL_API})")
158
- return
159
- except Exception:
160
- pass
161
 
 
 
 
 
 
 
 
 
 
 
162
  try:
163
- import torch
164
- from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
165
- device = "cuda" if torch.cuda.is_available() else "cpu"
166
- dtype = torch.float16 if torch.cuda.is_available() else torch.float32
167
- _gen_tokenizer = AutoTokenizer.from_pretrained(GEN_MODEL_LOCAL)
168
- _gen_raw = AutoModelForCausalLM.from_pretrained(
169
- GEN_MODEL_LOCAL, torch_dtype=dtype, device_map="auto",
170
  )
171
- _gen_model = pipeline(
172
- "text-generation", model=_gen_raw,
173
- tokenizer=_gen_tokenizer, device_map="auto",
 
174
  )
175
  _gen_backend = "local"
176
- print(f"βœ… Generation: local ({GEN_MODEL_LOCAL}, {device.upper()})")
177
- except Exception as e:
 
178
  _gen_backend = "none"
179
- print(f"⚠️ Generation unavailable: {e}")
180
 
181
 
182
- # ============================================================
183
- # CORE ENGINE
184
- # ============================================================
 
 
185
 
186
- @spaces.GPU
187
  def _call_llm(prompt: str, max_new_tokens: int = 450) -> str:
 
188
  if _gen_backend == "api":
189
  return _gen_client.text_generation(
190
  prompt, max_new_tokens=max_new_tokens,
191
  temperature=0.7, repetition_penalty=1.1, do_sample=True,
192
  ).strip()
193
- elif _gen_backend == "local":
194
  out = _gen_model(
195
  prompt, max_new_tokens=max_new_tokens, do_sample=True,
196
  temperature=0.7, repetition_penalty=1.15,
@@ -198,77 +228,90 @@ def _call_llm(prompt: str, max_new_tokens: int = 450) -> str:
198
  return_full_text=False,
199
  )
200
  return out[0]["generated_text"].strip()
201
- return "[Generation unavailable β€” add HF_TOKEN as a Space Secret to enable Mistral.]"
202
 
203
 
204
  def _build_prompt(system_msg: str, user_msg: str) -> str:
205
  if _gen_backend == "api":
206
  return f"<s>[INST] {system_msg}\n\n{user_msg} [/INST]"
207
- return (
208
- f"<|system|>\n{system_msg}</s>\n"
209
- f"<|user|>\n{user_msg}</s>\n"
210
- f"<|assistant|>\n"
211
- )
212
 
 
 
 
213
 
214
- @spaces.GPU
215
  def recommend_vendors(
216
- event_brief: str, event_city: str,
217
- event_season: str, total_budget_usd: float, top_n: int = 3,
 
 
 
218
  ) -> dict:
219
- from sentence_transformers import util as st_util
220
- if _embed_model is None or _vendor_embeddings is None:
221
- return {"error": "Models still loading β€” please wait a moment and try again."}
 
 
222
  if not event_brief.strip():
223
  return {"error": "Please enter an event description."}
224
 
225
- city_ok = np.array([event_city in c for c in _vcities], dtype=bool)
226
- season_ok = np.array([event_season in s for s in _vseasons], dtype=bool)
 
227
  alloc_vec = np.array(
228
- [total_budget_usd * ALLOC_RATIOS.get(cat, 0.10) for cat in _vcats],
229
  dtype=float,
230
  )
231
- budget_ok = _vrates <= alloc_vec
232
  combined = city_ok & season_ok & budget_ok
233
- pool_idx = _vidx[combined].tolist()
234
 
235
  if not pool_idx:
 
236
  return {"error": (
237
- f"No vendors matched all filters "
238
- f"(city: {int(city_ok.sum())}, season: {int(season_ok.sum())}, "
239
- f"budget: {int(budget_ok.sum())}, combined: 0). "
240
- f"Try a larger budget or a different city."
 
 
241
  )}
242
 
 
243
  q_vec = _embed_model.encode(
244
  event_brief, convert_to_tensor=True, normalize_embeddings=True,
245
  )
246
  pool_embeds = _vendor_embeddings[pool_idx]
247
  sims = st_util.cos_sim(q_vec, pool_embeds)[0].cpu().numpy()
248
 
249
- pool_df = _df_vendors.iloc[pool_idx].copy().reset_index(drop=True)
250
- pool_df["semantic_similarity"] = sims
251
- pool_df["final_score"] = 0.8 * sims + 0.2 * _vcomp[pool_idx]
 
252
 
253
  results = {}
254
  for cat in VENDOR_CATEGORIES:
255
  sub = pool_df[pool_df["category"] == cat].nlargest(top_n, "final_score")
256
  if len(sub):
257
  results[cat] = sub[[
258
- "vendor_name", "category", "price_tier",
259
- "avg_rating", "sla_compliance_rate", "day_rate_mid",
260
- "specializations", "semantic_similarity",
261
- "composite_score", "final_score",
262
  ]].to_dict("records")
263
  return results
264
 
265
 
266
- def generate_run_of_show(
267
- event_type, event_date, venue_name, city,
268
- guest_count, selected_vendors, special_notes="",
269
- ) -> str:
 
 
270
  vendor_lines = "\n".join(
271
- f" - {cat.replace('_', ' ')}: {name}"
272
  for cat, name in selected_vendors.items()
273
  )
274
  system_msg = (
@@ -277,25 +320,22 @@ def generate_run_of_show(
277
  "using format HH:MM β€” Task. Be specific about timings."
278
  )
279
  user_msg = (
280
- f"Write a complete Run of Show for:\n\n"
281
- f"Event Type : {event_type}\n"
282
- f"Date : {event_date}\n"
283
- f"Venue : {venue_name}, {city}\n"
284
- f"Guests : {guest_count:,}\n"
285
- f"Special Notes: {special_notes or 'None'}\n\n"
286
- f"Confirmed Vendors:\n{vendor_lines}\n\n"
287
- f"Cover: vendor arrivals, setup, guest arrival, programme, breakdown."
288
  )
289
  return _call_llm(_build_prompt(system_msg, user_msg), max_new_tokens=500)
290
 
291
 
292
- def generate_rfp(
293
- vendor_name, vendor_category, specializations,
294
- event_type, event_date, city, guest_count,
295
- allocated_budget_usd, special_requirements="",
296
- ) -> str:
297
- specs_str = ", ".join(specializations[:3]) if specializations else "general services"
298
- cat_label = vendor_category.replace("_", " ")
299
  system_msg = (
300
  "You are a professional event producer writing formal B2B emails. "
301
  "Be specific and professional. End with a clear call to action."
@@ -304,204 +344,408 @@ def generate_rfp(
304
  f"Write a formal RFP email to:\n\n"
305
  f"Company : {vendor_name}\n"
306
  f"Category : {cat_label}\n"
307
- f"Specialisms : {specs_str}\n\n"
308
  f"Event:\n"
309
- f" Type : {event_type}\n"
310
- f" Date : {event_date}\n"
311
  f" Location : {city}\n"
312
- f" Guests : {guest_count:,}\n"
313
- f" Budget : ${allocated_budget_usd:,.0f} for {cat_label}\n"
314
- f" Requirements: {special_requirements or 'Standard service'}\n\n"
315
  f"Request availability and a quote within 48 hours."
316
  )
317
  return _call_llm(_build_prompt(system_msg, user_msg), max_new_tokens=350)
318
 
319
 
320
- # ============================================================
321
- # GRADIO HANDLERS
322
- # ============================================================
323
 
324
- def _stars(rating: float) -> str:
325
- n = int(round(float(rating)))
326
- return "⭐" * n + "β˜†" * (5 - n)
327
 
328
 
329
- def _format_recommendations(recs: dict, total_budget: float) -> str:
330
  if "error" in recs:
331
- return f"### ⚠️ No Results\n\n{recs['error']}"
332
- lines = ["## πŸͺ Recommended Vendors\n"]
333
  for cat in VENDOR_CATEGORIES:
334
  if cat not in recs:
335
  continue
336
- alloc = total_budget * ALLOC_RATIOS[cat]
337
- lines.append(
338
- f"### {CATEGORY_EMOJI[cat]} {cat.replace('_', ' ')} "
339
- f"Β· Budget: ${alloc:,.0f}"
340
- )
341
  for rank, v in enumerate(recs[cat], 1):
342
  specs = v.get("specializations", [])
343
  if isinstance(specs, str):
344
- try:
345
- specs = json.loads(specs)
346
- except Exception:
347
- specs = []
348
- score = v.get("final_score", v.get("semantic_similarity", 0))
349
  lines.append(
350
- f"**#{rank} {v['vendor_name']}** \n"
351
- f"{_stars(v.get('avg_rating', 0))} Β· "
352
- f"{v.get('sla_compliance_rate', 0):.0%} SLA Β· "
353
- f"${v.get('day_rate_mid', 0):,.0f}/day \n"
354
- f"*{', '.join(specs[:2]) if specs else 'β€”'}* Β· "
355
- f"Match: `{score:.3f}`\n"
356
  )
357
- lines.append("---")
358
- return "\n".join(lines)
359
-
360
 
361
- def handle_recommend(brief: str, city: str, season: str, budget: float) -> str:
362
- if _df_vendors is None:
363
- return "⏳ Still loading β€” please wait a moment and try again."
364
- recs = recommend_vendors(brief, city, season, budget)
365
- return _format_recommendations(recs, budget)
366
 
 
 
 
367
 
368
- def handle_generate(
369
  brief, city, season, budget,
370
- ev_type, ev_date, ev_venue, guests, notes,
371
- progress=gr.Progress(),
372
- ) -> tuple:
373
- if _gen_backend in ("none", None):
374
- msg = "⚠️ Generation unavailable. Add HF_TOKEN as a Space Secret."
375
- return msg, msg
376
-
377
- progress(0, desc="Finding vendors...")
378
- recs = recommend_vendors(brief, city, season, float(budget))
379
- if "error" in recs:
380
- return f"⚠️ {recs['error']}", f"⚠️ {recs['error']}"
381
-
382
- selected_vendors = {}
383
- rfp_targets = []
 
 
 
384
  for cat in VENDOR_CATEGORIES:
385
  if cat not in recs or not recs[cat]:
386
  continue
387
  top = recs[cat][0]
388
- name = top.get("vendor_name", "Unknown")
389
- specs = top.get("specializations", [])
390
- if isinstance(specs, str):
391
- try:
392
- specs = json.loads(specs)
393
- except Exception:
394
- specs = []
395
- selected_vendors[cat] = name
396
  rfp_targets.append({
397
- "vendor_name": name, "category": cat,
 
398
  "specializations": specs,
399
- "allocated_usd": float(budget) * ALLOC_RATIOS[cat],
400
  })
401
 
402
- progress(0.2, desc="Generating Run of Show...")
403
- ros = generate_run_of_show(
404
- event_type=ev_type, event_date=ev_date, venue_name=ev_venue,
405
- city=city, guest_count=int(guests),
406
- selected_vendors=selected_vendors, special_notes=notes,
407
  )
408
 
409
  top3 = sorted(rfp_targets, key=lambda x: -x["allocated_usd"])[:3]
410
  rfp_blocks = []
411
  for j, t in enumerate(top3, 1):
412
- progress(0.2 + 0.25 * j, desc=f"Generating RFP {j}/3...")
413
- rfp_text = generate_rfp(
414
- vendor_name=t["vendor_name"], vendor_category=t["category"],
415
- specializations=t["specializations"], event_type=ev_type,
416
- event_date=ev_date, city=city, guest_count=int(guests),
417
- allocated_budget_usd=t["allocated_usd"], special_requirements=notes,
418
  )
419
- cat_label = t["category"].replace("_", " ")
420
  rfp_blocks.append(
421
- f"{'='*58}\n RFP β€” {cat_label.upper()}\n"
422
- f" TO: {t['vendor_name']}\n"
 
423
  f" BUDGET: ${t['allocated_usd']:,.0f}\n"
424
- f"{'='*58}\n\n" + rfp_text + "\n"
 
425
  )
426
- return ros, "\n\n".join(rfp_blocks)
427
 
 
 
428
 
429
- def _qs_and_find(idx: int):
430
- brief, city, season, budget = QUICK_STARTERS[idx]
431
- md = handle_recommend(brief, city, season, budget)
432
- return brief, city, season, budget, md
433
 
 
 
 
 
434
 
435
- # ============================================================
436
- # GRADIO UI
437
- # ============================================================
 
438
 
439
  CSS = """
440
- .prosync-header {
441
- background: linear-gradient(135deg, #2C3E50 0%, #1a6ea8 100%);
442
- border-radius: 12px; padding: 28px 32px; margin-bottom: 8px;
 
 
 
 
 
443
  }
444
- .prosync-header h1 { margin: 0; font-size: 2rem; font-weight: 700; color: white; }
445
- .prosync-header p { margin: 6px 0 0; opacity: 0.85; color: white; font-size: 1rem; }
446
- .qs-btn {
447
- background: #EBF5FB !important; border: 1px solid #3498DB !important;
448
- color: #1a6ea8 !important; font-weight: 600 !important; border-radius: 8px !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
449
  }
450
- .qs-btn:hover { background: #D6EAF8 !important; }
451
- .find-btn {
452
- background: #2C3E50 !important; color: white !important;
453
- font-size: 1rem !important; font-weight: 700 !important;
454
- border-radius: 8px !important; padding: 12px !important;
 
 
455
  }
456
- .gen-btn {
457
- background: #1a6ea8 !important; color: white !important;
458
- font-size: 0.95rem !important; font-weight: 600 !important;
 
459
  border-radius: 8px !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
460
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
461
  """
462
 
463
- with gr.Blocks(theme=gr.themes.Soft(), css=CSS, title="ProSync AI") as demo:
 
 
 
 
464
 
465
- gr.HTML("""
466
- <div class="prosync-header">
467
- <h1>🎯 ProSync AI</h1>
468
- <p>The Event Producer's Command Center β€” intelligent vendor matching &amp; document generation</p>
469
- </div>
470
- """)
471
 
472
- with gr.Row():
473
- with gr.Column(scale=1, min_width=320):
474
- gr.Markdown("### ⚑ Quick Starters")
475
- gr.Markdown("Click to auto-fill and search instantly.")
476
- with gr.Row():
477
- qs0 = gr.Button("πŸ™οΈ Tech Summit Β· Tel Aviv", elem_classes=["qs-btn"])
478
- qs1 = gr.Button("🍽️ Gala Dinner · Jerusalem", elem_classes=["qs-btn"])
 
 
 
 
 
 
 
 
479
  with gr.Row():
480
- qs2 = gr.Button("🌿 Team Building · Haifa", elem_classes=["qs-btn"])
 
 
 
 
 
481
 
482
- gr.Markdown("---")
483
- gr.Markdown("### πŸ“‹ Event Brief")
484
  brief_input = gr.Textbox(
485
  label="Describe your event",
486
  placeholder=(
487
- "e.g. Tech summit for 400 guests β€” advanced AV, live streaming, "
488
- "kosher catering, VIP security..."
489
  ),
490
  lines=4,
491
  )
 
492
  with gr.Row():
493
  city_input = gr.Dropdown(label="City", choices=CITIES, value="Tel Aviv")
494
  season_input = gr.Dropdown(label="Season", choices=SEASONS, value="Summer")
 
495
  budget_input = gr.Slider(
496
  label="Total Budget (USD)",
497
  minimum=20_000, maximum=600_000, step=5_000, value=200_000,
498
  )
499
- find_btn = gr.Button(
500
- "πŸ” Find Vendors", variant="primary", elem_classes=["find-btn"],
501
- )
502
 
503
- gr.Markdown("---")
504
- gr.Markdown("### πŸ“ Document Settings")
 
505
  with gr.Row():
506
  ev_type_input = gr.Dropdown(
507
  label="Event Type", choices=EVENT_TYPES, value="Tech Summit",
@@ -510,78 +754,105 @@ with gr.Blocks(theme=gr.themes.Soft(), css=CSS, title="ProSync AI") as demo:
510
  label="Guest Count", value=300, minimum=10, maximum=5000,
511
  )
512
  with gr.Row():
513
- date_input = gr.Textbox(label="Event Date", value="October 15, 2025")
514
- venue_input = gr.Textbox(label="Venue Name", value="Grand Convention Center")
 
515
  notes_input = gr.Textbox(
516
- label="Special Requirements (optional)",
517
- placeholder="e.g. Kosher catering, VIP lounge for 20 guests...",
518
  lines=2,
519
  )
520
- gen_btn = gr.Button(
521
- "πŸ“ Generate Run of Show + RFP Emails",
522
- variant="secondary", elem_classes=["gen-btn"],
 
 
 
 
 
 
 
523
  )
524
 
525
- with gr.Column(scale=2, min_width=480):
 
 
526
  with gr.Tabs():
527
- with gr.Tab("πŸͺ Vendor Matches"):
 
 
 
 
 
528
  vendor_output = gr.Markdown(
529
- value="_Click **Find Vendors** or a Quick Starter to see results._",
 
 
 
 
 
 
 
530
  )
531
- with gr.Tab("πŸ“‹ Run of Show"):
532
  ros_output = gr.Textbox(
533
- label="Generated Run of Show", lines=28,
534
- interactive=False,
535
- placeholder="Click 'Generate Documents' to produce a schedule...",
 
 
 
 
 
 
 
536
  )
537
- with gr.Tab("βœ‰οΈ RFP Emails"):
538
  rfp_output = gr.Textbox(
539
- label="Generated RFP Emails (top 3 by spend)", lines=28,
540
- interactive=False,
541
- placeholder="Click 'Generate Documents' to produce RFP emails...",
 
542
  )
543
 
544
- gr.Markdown("---")
545
- gr.Markdown("#### πŸ“š Example Inputs")
546
- gr.Examples(
547
- examples=[[q[0], q[1], q[2], q[3]] for q in QUICK_STARTERS],
548
- inputs=[brief_input, city_input, season_input, budget_input],
549
- outputs=[vendor_output],
550
- fn=handle_recommend,
551
- cache_examples=False,
552
- label="Quick Start Examples",
553
  )
554
 
555
- # ── Event wiring ──────────────────────────────────────────
556
- _qs_outs = [brief_input, city_input, season_input, budget_input, vendor_output]
557
- qs0.click(fn=lambda: _qs_and_find(0), outputs=_qs_outs)
558
- qs1.click(fn=lambda: _qs_and_find(1), outputs=_qs_outs)
559
- qs2.click(fn=lambda: _qs_and_find(2), outputs=_qs_outs)
 
 
560
 
561
- find_btn.click(
562
- fn=handle_recommend,
563
- inputs=[brief_input, city_input, season_input, budget_input],
564
- outputs=[vendor_output],
 
 
 
 
 
 
 
 
 
 
 
565
  )
566
- gen_btn.click(
567
- fn=handle_generate,
568
- inputs=[
569
- brief_input, city_input, season_input, budget_input,
570
- ev_type_input, date_input, venue_input, guests_input, notes_input,
571
- ],
572
- outputs=[ros_output, rfp_output],
573
  )
574
-
575
- gr.Markdown(
576
- "<br><center style='color:#95A5A6; font-size:0.8rem;'>"
577
- "ProSync AI Β· Gradio + HuggingFace Β· "
578
- "Embedding: all-MiniLM-L6-v2 Β· Generation: TinyLlama-1.1B"
579
- "</center>"
580
  )
581
 
582
- # ── Deferred startup β€” runs after Gradio initialises ──
583
- demo.load(fn=load_all, inputs=[], outputs=[])
584
-
585
 
586
  if __name__ == "__main__":
587
- demo.launch()
 
1
+ # ================================================================
2
  # ProSync AI β€” The Event Producer's Command Center
3
+ # Hugging Face Space | GPU tier | Gradio 4.x
4
  #
5
+ # Architecture:
6
+ # β€’ import spaces FIRST (mandatory for GPU Spaces)
7
+ # β€’ CSV + feature engineering loaded at MODULE LEVEL
8
+ # β†’ eliminates the "no matches" race condition
9
+ # β€’ Embedding model + vendor vectors computed at MODULE LEVEL
10
+ # β†’ MiniLM on CPU is fast enough (~30 s); no GPU needed
11
+ # β€’ @spaces.GPU(duration=120) wraps only the LLM forward pass
12
+ # β†’ satisfies the GPU Space decorator requirement
13
+ # β†’ generation runs on the GPU when available
14
+ # β€’ Two-tab flow: Step 1 (Input) β†’ Step 2 (Results)
15
+ # β†’ clicking submit auto-switches to the results tab
16
+ # ================================================================
17
+
18
+ import spaces # ← MUST be line 1 on GPU Spaces
19
 
20
  import os
21
  import json
 
23
 
24
  import numpy as np
25
  import pandas as pd
26
+ import torch
27
  import gradio as gr
28
+ from sentence_transformers import SentenceTransformer, util as st_util
29
+ from transformers import (
30
+ pipeline,
31
+ AutoTokenizer,
32
+ AutoModelForCausalLM,
33
+ )
34
 
35
  warnings.filterwarnings("ignore")
36
 
37
+ # ── Configuration ─────────────────────────────────────────────
38
+ HF_TOKEN = os.environ.get("HF_TOKEN", "")
39
+ EMBED_MODEL_ID = "sentence-transformers/all-MiniLM-L6-v2"
40
+ GEN_MODEL_ID = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
41
+ GEN_MODEL_API = "mistralai/Mistral-7B-Instruct-v0.2"
42
 
43
  VENDOR_CATEGORIES = [
44
  "Catering", "AV_Technology", "Venue", "Security",
45
  "Photography_Video", "Entertainment", "Logistics",
46
  ]
47
  CATEGORY_EMOJI = {
48
+ "Catering": "🍽️", "AV_Technology": "🎬", "Venue": "πŸ›οΈ",
49
+ "Security": "πŸ›‘οΈ", "Photography_Video": "πŸ“·",
50
  "Entertainment": "🎭", "Logistics": "🚚",
51
  }
52
  ALLOC_RATIOS = {
53
+ "Catering": 0.304, "Venue": 0.228, "AV_Technology": 0.175,
54
+ "Entertainment": 0.104, "Photography_Video": 0.076,
55
+ "Logistics": 0.057, "Security": 0.057,
56
  }
57
+ CITIES = ["Beer Sheva","Haifa","Herzliya","Jerusalem",
58
+ "Netanya","Petah Tikva","Ramat Gan","Tel Aviv"]
59
+ SEASONS = ["Winter","Spring","Summer","Fall"]
60
  EVENT_TYPES = [
61
+ "Annual Conference","Award Ceremony","Brand Activation",
62
+ "Corporate Gala","Investor Day","Product Launch",
63
+ "Team Building","Tech Summit","Trade Show","Workshop Series",
64
  ]
65
+
66
  QUICK_STARTERS = [
67
+ {
68
+ "label": "πŸ™οΈ Tech Summit Β· Tel Aviv",
69
+ "brief": "Large-scale tech summit β€” advanced AV, LED walls, live streaming, "
70
+ "kosher catering for 400 guests, VIP executive security.",
71
+ "city": "Tel Aviv", "season": "Summer", "budget": 250_000,
72
+ "type": "Tech Summit", "guests": 400,
73
+ "date": "October 15, 2025",
74
+ "venue": "The Tel Aviv Convention Center",
75
+ "notes": "Kosher catering required. VIP lounge for 30 executives.",
76
+ },
77
+ {
78
+ "label": "🍽️ Corporate Gala · Jerusalem",
79
+ "brief": "Elegant annual corporate gala β€” plated fine dining, live band, "
80
+ "professional photography and videography for 200 guests.",
81
+ "city": "Jerusalem", "season": "Winter", "budget": 140_000,
82
+ "type": "Corporate Gala", "guests": 200,
83
+ "date": "December 5, 2025",
84
+ "venue": "The King David Hotel Ballroom",
85
+ "notes": "Black-tie dress code. Award presentation segment.",
86
+ },
87
+ {
88
+ "label": "🌿 Team Building · Haifa",
89
+ "brief": "Outdoor team building day β€” interactive entertainment, DJ, "
90
+ "logistics coordination, casual catering for 150 employees.",
91
+ "city": "Haifa", "season": "Spring", "budget": 65_000,
92
+ "type": "Team Building", "guests": 150,
93
+ "date": "April 22, 2025",
94
+ "venue": "Carmel Forest Resort",
95
+ "notes": "Outdoor venue preferred. Vegetarian options required.",
96
+ },
97
  ]
98
 
 
 
 
 
 
 
99
 
100
+ # ================================================================
101
+ # DATA LOADING β€” module level (no race condition possible)
102
+ # ================================================================
103
 
104
  def _safe_to_list(val) -> list:
105
+ """Parse a column value to list regardless of storage type."""
106
  if isinstance(val, list):
107
  return val
108
  if isinstance(val, str):
 
114
  return []
115
 
116
 
117
+ print("⏳ Loading vendor data …")
118
+ try:
119
+ _df = pd.read_csv("dataset_b_vendors.csv")
120
+
121
+ # Parse JSON list columns
122
+ for _col in ["coverage_cities","seasonal_availability",
123
+ "specializations","certifications"]:
124
+ _df[_col] = _df[_col].apply(_safe_to_list)
125
+
126
+ # Feature engineering (mirrors EDA Cell 3)
127
+ _df["day_rate_mid"] = (_df["day_rate_min_usd"] + _df["day_rate_max_usd"]) / 2
128
+ _rmin = _df["avg_rating"].min(); _rmax = _df["avg_rating"].max()
129
+ _df["rating_norm"] = (_df["avg_rating"] - _rmin) / (_rmax - _rmin + 1e-9)
130
+ _df["value_score"] = 1 - (_df["price_tier"] - 1) / 4
131
+ _df["composite_score"] = (0.4 * _df["rating_norm"]
132
+ + 0.4 * _df["sla_compliance_rate"]
133
+ + 0.2 * _df["value_score"])
134
+
135
+ # Pre-extract numpy/Python arrays for vectorized filtering
136
+ _VCITIES = _df["coverage_cities"].tolist()
137
+ _VSEASONS = _df["seasonal_availability"].tolist()
138
+ _VCATS = _df["category"].values
139
+ _VRATES = _df["day_rate_mid"].values
140
+ _VCOMP = _df["composite_score"].values
141
+ _VIDX = np.arange(len(_df))
142
+
143
+ print(f"βœ… Vendor data: {len(_df):,} rows loaded.")
144
+ except FileNotFoundError:
145
+ print("❌ dataset_b_vendors.csv not found in Space directory.")
146
+ _df = None
147
+
148
+
149
+ # ================================================================
150
+ # EMBEDDING MODEL β€” module level (CPU, ~30 s)
151
+ # ================================================================
152
+
153
+ print("⏳ Loading embedding model …")
154
+ _embed_model = SentenceTransformer(EMBED_MODEL_ID)
155
+
156
+ if _df is not None:
157
+ print("⏳ Computing vendor embeddings …")
158
+ _vendor_embeddings = _embed_model.encode(
159
+ _df["vendor_profile_text"].tolist(),
160
+ batch_size=128,
161
+ show_progress_bar=True,
162
+ normalize_embeddings=True,
163
+ convert_to_tensor=True,
164
+ )
165
+ print(f"βœ… Embeddings: {_vendor_embeddings.shape}")
166
+ else:
167
+ _vendor_embeddings = None
168
 
 
 
 
 
169
 
170
+ # ================================================================
171
+ # GENERATION MODEL β€” module level (CPU load, GPU inference)
172
+ # ================================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
 
174
+ _gen_backend = "none"
175
+ _gen_model = None
176
+ _gen_tokenizer = None
177
+ _gen_client = None
 
 
 
 
 
 
178
 
179
+ if HF_TOKEN:
180
+ try:
181
+ from huggingface_hub import InferenceClient
182
+ _gen_client = InferenceClient(model=GEN_MODEL_API, token=HF_TOKEN)
183
+ _gen_backend = "api"
184
+ print(f"βœ… Generation: HF Inference API ({GEN_MODEL_API})")
185
+ except Exception as _e:
186
+ print(f"⚠️ HF API unavailable: {_e}")
187
+
188
+ if _gen_backend == "none":
189
  try:
190
+ print(f"⏳ Loading generation model ({GEN_MODEL_ID}) …")
191
+ _gen_tokenizer = AutoTokenizer.from_pretrained(GEN_MODEL_ID)
192
+ _gen_raw = AutoModelForCausalLM.from_pretrained(
193
+ GEN_MODEL_ID,
194
+ torch_dtype=torch.float16,
195
+ device_map="cpu", # stays on CPU; GPU used only at inference
 
196
  )
197
+ _gen_model = pipeline(
198
+ "text-generation",
199
+ model=_gen_raw,
200
+ tokenizer=_gen_tokenizer,
201
  )
202
  _gen_backend = "local"
203
+ print(f"βœ… Generation model loaded (inference via @spaces.GPU).")
204
+ except Exception as _e:
205
+ print(f"⚠️ Generation model failed: {_e}")
206
  _gen_backend = "none"
 
207
 
208
 
209
+ # ================================================================
210
+ # @spaces.GPU β€” LLM INFERENCE ONLY
211
+ # This is the ONE function that needs the GPU decorator.
212
+ # Everything else runs on CPU.
213
+ # ================================================================
214
 
215
+ @spaces.GPU(duration=120)
216
  def _call_llm(prompt: str, max_new_tokens: int = 450) -> str:
217
+ """Run LLM inference on the GPU. Called by generate_* functions."""
218
  if _gen_backend == "api":
219
  return _gen_client.text_generation(
220
  prompt, max_new_tokens=max_new_tokens,
221
  temperature=0.7, repetition_penalty=1.1, do_sample=True,
222
  ).strip()
223
+ elif _gen_backend == "local" and _gen_model is not None:
224
  out = _gen_model(
225
  prompt, max_new_tokens=max_new_tokens, do_sample=True,
226
  temperature=0.7, repetition_penalty=1.15,
 
228
  return_full_text=False,
229
  )
230
  return out[0]["generated_text"].strip()
231
+ return "⚠️ Generation model not available."
232
 
233
 
234
  def _build_prompt(system_msg: str, user_msg: str) -> str:
235
  if _gen_backend == "api":
236
  return f"<s>[INST] {system_msg}\n\n{user_msg} [/INST]"
237
+ return (f"<|system|>\n{system_msg}</s>\n"
238
+ f"<|user|>\n{user_msg}</s>\n"
239
+ f"<|assistant|>\n")
240
+
 
241
 
242
+ # ================================================================
243
+ # RECOMMENDATION ENGINE β€” CPU (fast, no decorator needed)
244
+ # ================================================================
245
 
 
246
  def recommend_vendors(
247
+ event_brief: str,
248
+ event_city: str,
249
+ event_season: str,
250
+ total_budget_usd: float,
251
+ top_n: int = 3,
252
  ) -> dict:
253
+ """Three-stage pipeline: filter β†’ embed β†’ rank."""
254
+
255
+ if _df is None or _vendor_embeddings is None:
256
+ return {"error": "Vendor data not loaded. "
257
+ "Check that dataset_b_vendors.csv is in the Space Files tab."}
258
  if not event_brief.strip():
259
  return {"error": "Please enter an event description."}
260
 
261
+ # Stage 1 β€” Vectorized hard filters
262
+ city_ok = np.array([event_city in c for c in _VCITIES], dtype=bool)
263
+ season_ok = np.array([event_season in s for s in _VSEASONS], dtype=bool)
264
  alloc_vec = np.array(
265
+ [total_budget_usd * ALLOC_RATIOS.get(cat, 0.10) for cat in _VCATS],
266
  dtype=float,
267
  )
268
+ budget_ok = _VRATES <= alloc_vec
269
  combined = city_ok & season_ok & budget_ok
270
+ pool_idx = _VIDX[combined].tolist()
271
 
272
  if not pool_idx:
273
+ n_c, n_s, n_b = int(city_ok.sum()), int(season_ok.sum()), int(budget_ok.sum())
274
  return {"error": (
275
+ f"No vendors matched all three filters.\n"
276
+ f" City '{event_city}': {n_c} vendors\n"
277
+ f" Season '{event_season}': {n_s} vendors\n"
278
+ f" Budget ${total_budget_usd:,.0f}: {n_b} vendors\n"
279
+ f" Combined: 0\n\n"
280
+ f"Try increasing the budget or choosing a different city."
281
  )}
282
 
283
+ # Stage 2 β€” Semantic similarity
284
  q_vec = _embed_model.encode(
285
  event_brief, convert_to_tensor=True, normalize_embeddings=True,
286
  )
287
  pool_embeds = _vendor_embeddings[pool_idx]
288
  sims = st_util.cos_sim(q_vec, pool_embeds)[0].cpu().numpy()
289
 
290
+ # Stage 3 β€” Rank per category
291
+ pool_df = _df.iloc[pool_idx].copy().reset_index(drop=True)
292
+ pool_df["similarity"] = sims
293
+ pool_df["final_score"] = 0.8 * sims + 0.2 * _VCOMP[pool_idx]
294
 
295
  results = {}
296
  for cat in VENDOR_CATEGORIES:
297
  sub = pool_df[pool_df["category"] == cat].nlargest(top_n, "final_score")
298
  if len(sub):
299
  results[cat] = sub[[
300
+ "vendor_name","category","price_tier",
301
+ "avg_rating","sla_compliance_rate","day_rate_mid",
302
+ "specializations","similarity","composite_score","final_score",
 
303
  ]].to_dict("records")
304
  return results
305
 
306
 
307
+ # ================================================================
308
+ # GENERATION FUNCTIONS (call _call_llm which has @spaces.GPU)
309
+ # ================================================================
310
+
311
+ def _generate_run_of_show(ev_type, ev_date, venue, city,
312
+ guests, selected_vendors, notes):
313
  vendor_lines = "\n".join(
314
+ f" - {cat.replace('_',' ')}: {name}"
315
  for cat, name in selected_vendors.items()
316
  )
317
  system_msg = (
 
320
  "using format HH:MM β€” Task. Be specific about timings."
321
  )
322
  user_msg = (
323
+ f"Write a complete Run of Show:\n\n"
324
+ f"Event Type : {ev_type}\n"
325
+ f"Date : {ev_date}\n"
326
+ f"Venue : {venue}, {city}\n"
327
+ f"Guests : {guests:,}\n"
328
+ f"Special Notes: {notes or 'None'}\n\n"
329
+ f"Vendors:\n{vendor_lines}\n\n"
330
+ f"Cover: arrivals, setup, guest arrival, programme, breakdown."
331
  )
332
  return _call_llm(_build_prompt(system_msg, user_msg), max_new_tokens=500)
333
 
334
 
335
+ def _generate_rfp(vendor_name, vendor_category, specializations,
336
+ ev_type, ev_date, city, guests, allocated_usd, notes):
337
+ specs = ", ".join(specializations[:3]) if specializations else "general services"
338
+ cat_label = vendor_category.replace("_"," ")
 
 
 
339
  system_msg = (
340
  "You are a professional event producer writing formal B2B emails. "
341
  "Be specific and professional. End with a clear call to action."
 
344
  f"Write a formal RFP email to:\n\n"
345
  f"Company : {vendor_name}\n"
346
  f"Category : {cat_label}\n"
347
+ f"Specialisms : {specs}\n\n"
348
  f"Event:\n"
349
+ f" Type : {ev_type}\n"
350
+ f" Date : {ev_date}\n"
351
  f" Location : {city}\n"
352
+ f" Guests : {guests:,}\n"
353
+ f" Budget : ${allocated_usd:,.0f} for {cat_label}\n"
354
+ f" Requirements: {notes or 'Standard service'}\n\n"
355
  f"Request availability and a quote within 48 hours."
356
  )
357
  return _call_llm(_build_prompt(system_msg, user_msg), max_new_tokens=350)
358
 
359
 
360
+ # ================================================================
361
+ # OUTPUT FORMATTERS
362
+ # ================================================================
363
 
364
+ def _stars(r: float) -> str:
365
+ n = min(5, max(0, int(round(float(r)))))
366
+ return "β˜…" * n + "β˜†" * (5 - n)
367
 
368
 
369
+ def _format_vendors(recs: dict, total_budget: float) -> str:
370
  if "error" in recs:
371
+ return f"### ⚠️ No Results\n\n```\n{recs['error']}\n```"
372
+ lines = []
373
  for cat in VENDOR_CATEGORIES:
374
  if cat not in recs:
375
  continue
376
+ alloc = total_budget * ALLOC_RATIOS[cat]
377
+ cat_name = cat.replace("_"," ")
378
+ emoji = CATEGORY_EMOJI[cat]
379
+ lines.append(f"### {emoji} {cat_name} Β· Budget: ${alloc:,.0f}\n")
 
380
  for rank, v in enumerate(recs[cat], 1):
381
  specs = v.get("specializations", [])
382
  if isinstance(specs, str):
383
+ try: specs = json.loads(specs)
384
+ except: specs = []
385
+ score = v.get("final_score", v.get("similarity", 0))
 
 
386
  lines.append(
387
+ f"**#{rank} {v['vendor_name']}**\n"
388
+ f"{_stars(v.get('avg_rating',0))} Β· "
389
+ f"{v.get('sla_compliance_rate',0):.0%} SLA Β· "
390
+ f"${v.get('day_rate_mid',0):,.0f}/day Β· "
391
+ f"Match `{score:.3f}`\n\n"
392
+ f"*{', '.join(specs[:2]) if specs else 'β€”'}*\n"
393
  )
394
+ lines.append("---\n")
395
+ return "\n".join(lines) if lines else "_No vendor results._"
 
396
 
 
 
 
 
 
397
 
398
+ # ================================================================
399
+ # MAIN GRADIO HANDLER
400
+ # ================================================================
401
 
402
+ def handle_submit(
403
  brief, city, season, budget,
404
+ ev_type, ev_date, venue, guests, notes,
405
+ progress=gr.Progress(track_tqdm=True),
406
+ ):
407
+ progress(0, desc="Finding matching vendors …")
408
+ recs = recommend_vendors(brief, city, season, float(budget))
409
+ vendor_md = _format_vendors(recs, float(budget))
410
+
411
+ if "error" in recs or _gen_backend == "none":
412
+ ros_text = ("⚠️ Generation skipped.\n\n"
413
+ + (recs.get("error","") if "error" in recs
414
+ else "Set HF_TOKEN as a Space Secret to enable generation."))
415
+ rfp_text = ros_text
416
+ return vendor_md, ros_text, rfp_text, gr.update(selected=1)
417
+
418
+ # Build selected_vendors dict (top-1 per category)
419
+ selected = {}
420
+ rfp_targets = []
421
  for cat in VENDOR_CATEGORIES:
422
  if cat not in recs or not recs[cat]:
423
  continue
424
  top = recs[cat][0]
425
+ name = top.get("vendor_name","Unknown")
426
+ specs = top.get("specializations",[])
427
+ if isinstance(specs,str):
428
+ try: specs = json.loads(specs)
429
+ except: specs = []
430
+ selected[cat] = name
 
 
431
  rfp_targets.append({
432
+ "vendor_name": name,
433
+ "category": cat,
434
  "specializations": specs,
435
+ "allocated_usd": float(budget) * ALLOC_RATIOS[cat],
436
  })
437
 
438
+ progress(0.25, desc="Generating Run of Show …")
439
+ ros_text = _generate_run_of_show(
440
+ ev_type, ev_date, venue, city, int(guests), selected, notes,
 
 
441
  )
442
 
443
  top3 = sorted(rfp_targets, key=lambda x: -x["allocated_usd"])[:3]
444
  rfp_blocks = []
445
  for j, t in enumerate(top3, 1):
446
+ progress(0.25 + 0.25 * j, desc=f"Generating RFP {j}/3 …")
447
+ rfp_text = _generate_rfp(
448
+ t["vendor_name"], t["category"], t["specializations"],
449
+ ev_type, ev_date, city, int(guests), t["allocated_usd"], notes,
 
 
450
  )
451
+ cat_label = t["category"].replace("_"," ")
452
  rfp_blocks.append(
453
+ f"{'═'*56}\n"
454
+ f" RFP β€” {cat_label.upper()}\n"
455
+ f" TO : {t['vendor_name']}\n"
456
  f" BUDGET: ${t['allocated_usd']:,.0f}\n"
457
+ f"{'═'*56}\n\n"
458
+ + rfp_text + "\n"
459
  )
 
460
 
461
+ rfp_combined = "\n\n".join(rfp_blocks) if rfp_blocks else "No RFPs generated."
462
+ return vendor_md, ros_text, rfp_combined, gr.update(selected=1)
463
 
 
 
 
 
464
 
465
+ def apply_quick_starter(idx: int):
466
+ qs = QUICK_STARTERS[idx]
467
+ return (qs["brief"], qs["city"], qs["season"], qs["budget"],
468
+ qs["type"], qs["date"], qs["venue"], qs["guests"], qs["notes"])
469
 
470
+
471
+ # ================================================================
472
+ # CSS β€” WARM BROWN / CREAM / BEIGE PALETTE
473
+ # ================================================================
474
 
475
  CSS = """
476
+ /* ── Fonts ───────────────────────────────────────────────── */
477
+ @import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;600;700&family=Inter:wght@300;400;500;600&display=swap');
478
+
479
+ /* ── Global ──────────────────────────────────────────────── */
480
+ body, .gradio-container {
481
+ background-color: #FAF7F2 !important;
482
+ font-family: 'Inter', sans-serif !important;
483
+ color: #2C1810 !important;
484
  }
485
+
486
+ /* ── Header ──────────────────────────────────────────────── */
487
+ .ps-header {
488
+ background: linear-gradient(135deg, #3D2314 0%, #7A4E2D 60%, #B8895A 100%);
489
+ border-radius: 16px;
490
+ padding: 36px 40px;
491
+ margin-bottom: 24px;
492
+ box-shadow: 0 8px 32px rgba(61,35,20,0.25);
493
+ }
494
+ .ps-header h1 {
495
+ font-family: 'Playfair Display', serif;
496
+ font-size: 2.4rem;
497
+ font-weight: 700;
498
+ color: #FAF7F2;
499
+ margin: 0 0 6px 0;
500
+ letter-spacing: 0.5px;
501
+ }
502
+ .ps-header p {
503
+ color: #DDD0BE;
504
+ font-size: 1.05rem;
505
+ font-weight: 300;
506
+ margin: 0;
507
+ letter-spacing: 0.3px;
508
  }
509
+
510
+ /* ── Tabs ────────────────────────────────────────────────── */
511
+ .tab-nav {
512
+ background: #F0EBE3 !important;
513
+ border-radius: 12px !important;
514
+ padding: 4px !important;
515
+ border: 1px solid #DDD0BE !important;
516
  }
517
+ .tab-nav button {
518
+ font-family: 'Inter', sans-serif !important;
519
+ font-weight: 500 !important;
520
+ color: #7A4E2D !important;
521
  border-radius: 8px !important;
522
+ padding: 10px 24px !important;
523
+ transition: all 0.2s ease !important;
524
+ }
525
+ .tab-nav button.selected {
526
+ background: #7A4E2D !important;
527
+ color: #FAF7F2 !important;
528
+ box-shadow: 0 2px 8px rgba(61,35,20,0.2) !important;
529
+ }
530
+
531
+ /* ── Labels ──────────────────────────────────────────────── */
532
+ label span, .label-wrap span {
533
+ font-family: 'Inter', sans-serif !important;
534
+ font-weight: 500 !important;
535
+ font-size: 0.88rem !important;
536
+ color: #5C3D1E !important;
537
+ letter-spacing: 0.4px !important;
538
+ text-transform: uppercase !important;
539
+ }
540
+
541
+ /* ── Inputs ──────────────────────────────────────────────── */
542
+ textarea, input[type="text"], input[type="number"] {
543
+ background: #FFFFFF !important;
544
+ border: 1.5px solid #DDD0BE !important;
545
+ border-radius: 10px !important;
546
+ color: #2C1810 !important;
547
+ font-family: 'Inter', sans-serif !important;
548
+ font-size: 0.95rem !important;
549
+ transition: border-color 0.2s ease !important;
550
+ }
551
+ textarea:focus, input:focus {
552
+ border-color: #B8895A !important;
553
+ box-shadow: 0 0 0 3px rgba(184,137,90,0.12) !important;
554
+ outline: none !important;
555
+ }
556
+
557
+ /* ── Dropdowns ────────────────────────────────────────────── */
558
+ .wrap-inner, select {
559
+ background: #FFFFFF !important;
560
+ border: 1.5px solid #DDD0BE !important;
561
+ border-radius: 10px !important;
562
+ color: #2C1810 !important;
563
+ }
564
+
565
+ /* ── Slider ──────────────────────────────────────────────── */
566
+ input[type="range"] {
567
+ accent-color: #B8895A !important;
568
+ }
569
+ .range-value {
570
+ color: #7A4E2D !important;
571
+ font-weight: 600 !important;
572
+ }
573
+
574
+ /* ── Quick starter buttons ───────────────────────────────── */
575
+ .qs-btn {
576
+ background: #F5EFE6 !important;
577
+ border: 1.5px solid #D4B896 !important;
578
+ color: #5C3D1E !important;
579
+ font-family: 'Inter', sans-serif !important;
580
+ font-weight: 500 !important;
581
+ font-size: 0.9rem !important;
582
+ border-radius: 10px !important;
583
+ padding: 10px 16px !important;
584
+ transition: all 0.2s ease !important;
585
+ cursor: pointer !important;
586
+ }
587
+ .qs-btn:hover {
588
+ background: #EDE0CE !important;
589
+ border-color: #B8895A !important;
590
+ transform: translateY(-1px) !important;
591
+ box-shadow: 0 4px 12px rgba(184,137,90,0.2) !important;
592
+ }
593
+
594
+ /* ── Primary button (Find & Generate) ────────────────────── */
595
+ .submit-btn {
596
+ background: linear-gradient(135deg, #5C3D1E 0%, #8B6239 100%) !important;
597
+ color: #FAF7F2 !important;
598
+ font-family: 'Inter', sans-serif !important;
599
+ font-size: 1.05rem !important;
600
+ font-weight: 600 !important;
601
+ border: none !important;
602
+ border-radius: 12px !important;
603
+ padding: 14px 28px !important;
604
+ letter-spacing: 0.4px !important;
605
+ box-shadow: 0 4px 16px rgba(61,35,20,0.25) !important;
606
+ transition: all 0.25s ease !important;
607
+ width: 100% !important;
608
+ margin-top: 8px !important;
609
+ }
610
+ .submit-btn:hover {
611
+ background: linear-gradient(135deg, #3D2314 0%, #7A4E2D 100%) !important;
612
+ box-shadow: 0 6px 20px rgba(61,35,20,0.35) !important;
613
+ transform: translateY(-1px) !important;
614
  }
615
+
616
+ /* ── Section headings ────────────────────────────────────── */
617
+ .section-label {
618
+ font-family: 'Playfair Display', serif !important;
619
+ font-size: 1.15rem !important;
620
+ color: #3D2314 !important;
621
+ font-weight: 600 !important;
622
+ margin: 20px 0 8px 0 !important;
623
+ border-bottom: 1px solid #DDD0BE !important;
624
+ padding-bottom: 6px !important;
625
+ }
626
+
627
+ /* ── Result panels ───────────────────────────────────────── */
628
+ .result-box textarea {
629
+ background: #FFFCF8 !important;
630
+ border: 1.5px solid #DDD0BE !important;
631
+ font-family: 'Inter', sans-serif !important;
632
+ font-size: 0.92rem !important;
633
+ line-height: 1.7 !important;
634
+ color: #2C1810 !important;
635
+ }
636
+
637
+ /* ── Markdown output ─────────────────────────────────────── */
638
+ .prose, .markdown-body {
639
+ font-family: 'Inter', sans-serif !important;
640
+ color: #2C1810 !important;
641
+ line-height: 1.7 !important;
642
+ }
643
+ .prose h3 {
644
+ font-family: 'Playfair Display', serif !important;
645
+ color: #5C3D1E !important;
646
+ border-bottom: 1px solid #DDD0BE;
647
+ padding-bottom: 4px;
648
+ }
649
+ .prose strong { color: #3D2314 !important; }
650
+ .prose hr { border-color: #EDE0CE !important; }
651
+ .prose code {
652
+ background: #F5EFE6 !important;
653
+ color: #7A4E2D !important;
654
+ border-radius: 4px !important;
655
+ padding: 1px 5px !important;
656
+ font-size: 0.85rem !important;
657
+ }
658
+
659
+ /* ── Status bar ──────────────────────────────────────────── */
660
+ .status-bar {
661
+ background: #F5EFE6;
662
+ border: 1px solid #DDD0BE;
663
+ border-radius: 8px;
664
+ padding: 8px 14px;
665
+ font-size: 0.82rem;
666
+ color: #7A4E2D;
667
+ margin-bottom: 16px;
668
+ }
669
+
670
+ /* ── Divider ─────────────────────────────────────────────── */
671
+ .ps-divider {
672
+ border: none;
673
+ border-top: 1px solid #DDD0BE;
674
+ margin: 20px 0;
675
+ }
676
+
677
+ /* ── Footer ──────────────────────────────────────────────── */
678
+ .ps-footer {
679
+ text-align: center;
680
+ color: #A68B6A;
681
+ font-size: 0.78rem;
682
+ margin-top: 32px;
683
+ padding-top: 16px;
684
+ border-top: 1px solid #EDE0CE;
685
+ }
686
+ """
687
+
688
+ HEADER_HTML = """
689
+ <div class="ps-header">
690
+ <h1>🎯 ProSync AI</h1>
691
+ <p>The Event Producer's Command Center β€” intelligent vendor matching &amp; automated document generation</p>
692
+ </div>
693
  """
694
 
695
+ _status = (
696
+ f"Vendors: {'βœ… ' + str(len(_df)) + ' loaded' if _df is not None else '❌ not found'} Β· "
697
+ f"Embeddings: {'βœ…' if _vendor_embeddings is not None else '❌'} Β· "
698
+ f"Generation: {_gen_backend}"
699
+ )
700
 
701
+ # ================================================================
702
+ # GRADIO UI
703
+ # ================================================================
 
 
 
704
 
705
+ with gr.Blocks(css=CSS, theme=gr.themes.Base(), title="ProSync AI") as demo:
706
+
707
+ gr.HTML(HEADER_HTML)
708
+ gr.HTML(f'<div class="status-bar">System status Β· {_status}</div>')
709
+
710
+ with gr.Tabs(selected=0) as main_tabs:
711
+
712
+ # ── TAB 1 β€” EVENT BRIEF ────────────────────────────────
713
+ with gr.Tab("πŸ“‹ Step 1 β€” Event Brief", id=0):
714
+
715
+ gr.HTML('<p class="section-label">Quick Starters</p>')
716
+ gr.Markdown(
717
+ "_Click any starter to pre-fill the form and run the full pipeline instantly._",
718
+ elem_classes=["prose"],
719
+ )
720
  with gr.Row():
721
+ qs0_btn = gr.Button(QUICK_STARTERS[0]["label"], elem_classes=["qs-btn"])
722
+ qs1_btn = gr.Button(QUICK_STARTERS[1]["label"], elem_classes=["qs-btn"])
723
+ qs2_btn = gr.Button(QUICK_STARTERS[2]["label"], elem_classes=["qs-btn"])
724
+
725
+ gr.HTML('<hr class="ps-divider">')
726
+ gr.HTML('<p class="section-label">Event Description</p>')
727
 
 
 
728
  brief_input = gr.Textbox(
729
  label="Describe your event",
730
  placeholder=(
731
+ "e.g. Tech summit for 400 guests β€” advanced AV production, "
732
+ "live streaming, kosher catering, VIP executive security…"
733
  ),
734
  lines=4,
735
  )
736
+
737
  with gr.Row():
738
  city_input = gr.Dropdown(label="City", choices=CITIES, value="Tel Aviv")
739
  season_input = gr.Dropdown(label="Season", choices=SEASONS, value="Summer")
740
+
741
  budget_input = gr.Slider(
742
  label="Total Budget (USD)",
743
  minimum=20_000, maximum=600_000, step=5_000, value=200_000,
744
  )
 
 
 
745
 
746
+ gr.HTML('<hr class="ps-divider">')
747
+ gr.HTML('<p class="section-label">Document Settings</p>')
748
+
749
  with gr.Row():
750
  ev_type_input = gr.Dropdown(
751
  label="Event Type", choices=EVENT_TYPES, value="Tech Summit",
 
754
  label="Guest Count", value=300, minimum=10, maximum=5000,
755
  )
756
  with gr.Row():
757
+ date_input = gr.Textbox(label="Event Date", value="October 15, 2025")
758
+ venue_input = gr.Textbox(label="Venue Name", value="Grand Convention Center")
759
+
760
  notes_input = gr.Textbox(
761
+ label="Special Requirements",
762
+ placeholder="e.g. Kosher catering, black-tie dress code, VIP lounge…",
763
  lines=2,
764
  )
765
+
766
+ submit_btn = gr.Button(
767
+ "✨ Find Vendors & Generate Documents",
768
+ elem_classes=["submit-btn"],
769
+ )
770
+
771
+ gr.HTML(
772
+ f'<p style="text-align:center;color:#A68B6A;font-size:0.82rem;margin-top:8px;">'
773
+ f'Generation uses <strong>{_gen_backend}</strong> backend Β· '
774
+ f'Allow 60–120 s for document generation on GPU</p>'
775
  )
776
 
777
+ # ── TAB 2 β€” RESULTS ────────────────────────────────────
778
+ with gr.Tab("✨ Step 2 β€” Matches & Documents", id=1):
779
+
780
  with gr.Tabs():
781
+
782
+ with gr.Tab("πŸͺ Vendor Matches"):
783
+ gr.Markdown(
784
+ "_Complete Step 1 and click **Find Vendors** to see recommendations._",
785
+ elem_classes=["prose"],
786
+ )
787
  vendor_output = gr.Markdown(
788
+ value="_Results will appear here._",
789
+ elem_classes=["prose"],
790
+ )
791
+
792
+ with gr.Tab("πŸ“‹ Run of Show"):
793
+ gr.Markdown(
794
+ "_A timestamped production schedule will be generated here._",
795
+ elem_classes=["prose"],
796
  )
 
797
  ros_output = gr.Textbox(
798
+ label="Generated Run of Show",
799
+ lines=30, interactive=False,
800
+ placeholder="Generated schedule will appear here…",
801
+ elem_classes=["result-box"],
802
+ )
803
+
804
+ with gr.Tab("βœ‰οΈ RFP Emails"):
805
+ gr.Markdown(
806
+ "_Personalised RFP emails for your top vendors will appear here._",
807
+ elem_classes=["prose"],
808
  )
 
809
  rfp_output = gr.Textbox(
810
+ label="Generated RFP Emails (top 3 by spend)",
811
+ lines=30, interactive=False,
812
+ placeholder="Generated emails will appear here…",
813
+ elem_classes=["result-box"],
814
  )
815
 
816
+ gr.HTML(
817
+ '<div class="ps-footer">'
818
+ 'ProSync AI Β· Gradio + HuggingFace Β· '
819
+ 'Embedding: all-MiniLM-L6-v2 Β· Generation: TinyLlama-1.1B-Chat'
820
+ '</div>'
 
 
 
 
821
  )
822
 
823
+ # ── All inputs / outputs ─────────────────────────────────
824
+ _inputs = [brief_input, city_input, season_input, budget_input,
825
+ ev_type_input, date_input, venue_input, guests_input, notes_input]
826
+ _outputs = [vendor_output, ros_output, rfp_output, main_tabs]
827
+
828
+ # Main submit
829
+ submit_btn.click(fn=handle_submit, inputs=_inputs, outputs=_outputs)
830
 
831
+ # Quick starters β€” fill form then auto-run
832
+ _form_fields = [brief_input, city_input, season_input, budget_input,
833
+ ev_type_input, date_input, venue_input, guests_input, notes_input]
834
+
835
+ def _qs_run(idx: int):
836
+ vals = apply_quick_starter(idx)
837
+ brief, city, season, budget, ev_type, date, venue, guests, notes = vals
838
+ vendor_md, ros, rfps, tab_update = handle_submit(
839
+ brief, city, season, budget, ev_type, date, venue, guests, notes,
840
+ )
841
+ return (*vals, vendor_md, ros, rfps, tab_update)
842
+
843
+ qs0_btn.click(
844
+ fn=lambda: _qs_run(0),
845
+ outputs=_form_fields + _outputs,
846
  )
847
+ qs1_btn.click(
848
+ fn=lambda: _qs_run(1),
849
+ outputs=_form_fields + _outputs,
 
 
 
 
850
  )
851
+ qs2_btn.click(
852
+ fn=lambda: _qs_run(2),
853
+ outputs=_form_fields + _outputs,
 
 
 
854
  )
855
 
 
 
 
856
 
857
  if __name__ == "__main__":
858
+ demo.launch()