eliel2003 commited on
Commit
3373cdb
Β·
verified Β·
1 Parent(s): c8460b1

Upload app.py

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