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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 os
|
| 16 |
+
import json
|
| 17 |
+
import warnings
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import pandas as pd
|
| 21 |
+
import gradio as gr
|
| 22 |
+
|
| 23 |
+
warnings.filterwarnings("ignore")
|
| 24 |
+
|
| 25 |
+
# ββ Config from Space Secrets ββββββββββββββββββββββββββββββββββ
|
| 26 |
+
HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
| 27 |
+
EMBED_MODEL_ID = "sentence-transformers/all-MiniLM-L6-v2"
|
| 28 |
+
GEN_MODEL_LOCAL = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
|
| 29 |
+
GEN_MODEL_API = "mistralai/Mistral-7B-Instruct-v0.2"
|
| 30 |
+
|
| 31 |
+
VENDOR_CATEGORIES = [
|
| 32 |
+
"Catering", "AV_Technology", "Venue", "Security",
|
| 33 |
+
"Photography_Video", "Entertainment", "Logistics",
|
| 34 |
+
]
|
| 35 |
+
CATEGORY_EMOJI = {
|
| 36 |
+
"Catering": "π½οΈ", "AV_Technology": "π¬", "Venue": "ποΈ",
|
| 37 |
+
"Security": "π‘οΈ", "Photography_Video": "π·",
|
| 38 |
+
"Entertainment": "π", "Logistics": "π",
|
| 39 |
+
}
|
| 40 |
+
ALLOC_RATIOS = {
|
| 41 |
+
"Catering": 0.304, "Venue": 0.228, "AV_Technology": 0.175,
|
| 42 |
+
"Entertainment": 0.104, "Photography_Video": 0.076,
|
| 43 |
+
"Logistics": 0.057, "Security": 0.057,
|
| 44 |
+
}
|
| 45 |
+
CITIES = ["Beer Sheva", "Haifa", "Herzliya", "Jerusalem",
|
| 46 |
+
"Netanya", "Petah Tikva", "Ramat Gan", "Tel Aviv"]
|
| 47 |
+
SEASONS = ["Winter", "Spring", "Summer", "Fall"]
|
| 48 |
+
EVENT_TYPES = [
|
| 49 |
+
"Annual Conference", "Award Ceremony", "Brand Activation",
|
| 50 |
+
"Corporate Gala", "Investor Day", "Product Launch",
|
| 51 |
+
"Team Building", "Tech Summit", "Trade Show", "Workshop Series",
|
| 52 |
+
]
|
| 53 |
+
QUICK_STARTERS = [
|
| 54 |
+
[
|
| 55 |
+
"Large-scale tech summit with advanced AV production, LED walls, "
|
| 56 |
+
"live streaming, kosher catering for 400 guests, VIP executive security.",
|
| 57 |
+
"Tel Aviv", "Summer", 250_000,
|
| 58 |
+
],
|
| 59 |
+
[
|
| 60 |
+
"Elegant corporate gala for 200 guests β plated fine dining, "
|
| 61 |
+
"live band entertainment, professional photography and videography.",
|
| 62 |
+
"Jerusalem", "Winter", 140_000,
|
| 63 |
+
],
|
| 64 |
+
[
|
| 65 |
+
"Outdoor team building day for 150 employees β interactive entertainment, "
|
| 66 |
+
"DJ, logistics coordination, casual catering.",
|
| 67 |
+
"Haifa", "Spring", 65_000,
|
| 68 |
+
],
|
| 69 |
+
]
|
| 70 |
+
|
| 71 |
+
# ββ Module-level singletons ββββββββββββββββββββββββββββββββββββ
|
| 72 |
+
_df_vendors = None
|
| 73 |
+
_embed_model = None
|
| 74 |
+
_vendor_embeddings = None
|
| 75 |
+
_vcities = _vseasons = _vcats = _vrates = _vcomp = _vidx = None
|
| 76 |
+
_gen_backend = _gen_model = _gen_tokenizer = _gen_client = None
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _safe_to_list(val) -> list:
|
| 80 |
+
if isinstance(val, list):
|
| 81 |
+
return val
|
| 82 |
+
if isinstance(val, str):
|
| 83 |
+
try:
|
| 84 |
+
r = json.loads(val)
|
| 85 |
+
return r if isinstance(r, list) else []
|
| 86 |
+
except Exception:
|
| 87 |
+
return []
|
| 88 |
+
return []
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# ============================================================
|
| 92 |
+
# DEFERRED STARTUP (called via demo.load β models load after Gradio starts)
|
| 93 |
+
# ============================================================
|
| 94 |
+
|
| 95 |
+
def load_all():
|
| 96 |
+
global _df_vendors, _embed_model, _vendor_embeddings
|
| 97 |
+
global _vcities, _vseasons, _vcats, _vrates, _vcomp, _vidx
|
| 98 |
+
global _gen_backend, _gen_model, _gen_tokenizer, _gen_client
|
| 99 |
+
|
| 100 |
+
# 1. Dataset β read directly from the Space directory
|
| 101 |
+
try:
|
| 102 |
+
_df_vendors = pd.read_csv("dataset_b_vendors.csv")
|
| 103 |
+
print(f"β
Dataset: {len(_df_vendors):,} vendors")
|
| 104 |
+
except FileNotFoundError:
|
| 105 |
+
print("β dataset_b_vendors.csv not found. "
|
| 106 |
+
"Make sure it is uploaded to the Space Files tab.")
|
| 107 |
+
return
|
| 108 |
+
except Exception as e:
|
| 109 |
+
print(f"β Dataset failed: {e}")
|
| 110 |
+
return
|
| 111 |
+
|
| 112 |
+
for col in ["coverage_cities", "seasonal_availability",
|
| 113 |
+
"specializations", "certifications"]:
|
| 114 |
+
_df_vendors[col] = _df_vendors[col].apply(_safe_to_list)
|
| 115 |
+
|
| 116 |
+
_df_vendors["day_rate_mid"] = (
|
| 117 |
+
(_df_vendors["day_rate_min_usd"] + _df_vendors["day_rate_max_usd"]) / 2
|
| 118 |
+
)
|
| 119 |
+
rmin = _df_vendors["avg_rating"].min()
|
| 120 |
+
rmax = _df_vendors["avg_rating"].max()
|
| 121 |
+
_df_vendors["rating_norm"] = (_df_vendors["avg_rating"] - rmin) / (rmax - rmin + 1e-9)
|
| 122 |
+
_df_vendors["value_score"] = 1 - (_df_vendors["price_tier"] - 1) / 4
|
| 123 |
+
_df_vendors["composite_score"] = (
|
| 124 |
+
0.4 * _df_vendors["rating_norm"]
|
| 125 |
+
+ 0.4 * _df_vendors["sla_compliance_rate"]
|
| 126 |
+
+ 0.2 * _df_vendors["value_score"]
|
| 127 |
+
)
|
| 128 |
+
_vcities = _df_vendors["coverage_cities"].tolist()
|
| 129 |
+
_vseasons = _df_vendors["seasonal_availability"].tolist()
|
| 130 |
+
_vcats = _df_vendors["category"].values
|
| 131 |
+
_vrates = _df_vendors["day_rate_mid"].values
|
| 132 |
+
_vcomp = _df_vendors["composite_score"].values
|
| 133 |
+
_vidx = np.arange(len(_df_vendors))
|
| 134 |
+
|
| 135 |
+
# 2. Embedding model β torch imported inside function, not at module level
|
| 136 |
+
try:
|
| 137 |
+
import torch
|
| 138 |
+
from sentence_transformers import SentenceTransformer
|
| 139 |
+
_embed_model = SentenceTransformer(EMBED_MODEL_ID)
|
| 140 |
+
texts = _df_vendors["vendor_profile_text"].tolist()
|
| 141 |
+
_vendor_embeddings = _embed_model.encode(
|
| 142 |
+
texts, batch_size=64, show_progress_bar=False,
|
| 143 |
+
convert_to_tensor=True, normalize_embeddings=True,
|
| 144 |
+
)
|
| 145 |
+
print(f"β
Embeddings: {_vendor_embeddings.shape}")
|
| 146 |
+
except Exception as e:
|
| 147 |
+
print(f"β Embedding model failed: {e}")
|
| 148 |
+
|
| 149 |
+
# 3. Generation model
|
| 150 |
+
if HF_TOKEN:
|
| 151 |
+
try:
|
| 152 |
+
from huggingface_hub import InferenceClient
|
| 153 |
+
_gen_client = InferenceClient(model=GEN_MODEL_API, token=HF_TOKEN)
|
| 154 |
+
_gen_backend = "api"
|
| 155 |
+
print(f"β
Generation: HF API ({GEN_MODEL_API})")
|
| 156 |
+
return
|
| 157 |
+
except Exception:
|
| 158 |
+
pass
|
| 159 |
+
|
| 160 |
+
try:
|
| 161 |
+
import torch
|
| 162 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
|
| 163 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 164 |
+
dtype = torch.float16 if torch.cuda.is_available() else torch.float32
|
| 165 |
+
_gen_tokenizer = AutoTokenizer.from_pretrained(GEN_MODEL_LOCAL)
|
| 166 |
+
_gen_raw = AutoModelForCausalLM.from_pretrained(
|
| 167 |
+
GEN_MODEL_LOCAL, torch_dtype=dtype, device_map="auto",
|
| 168 |
+
)
|
| 169 |
+
_gen_model = pipeline(
|
| 170 |
+
"text-generation", model=_gen_raw,
|
| 171 |
+
tokenizer=_gen_tokenizer, device_map="auto",
|
| 172 |
+
)
|
| 173 |
+
_gen_backend = "local"
|
| 174 |
+
print(f"β
Generation: local ({GEN_MODEL_LOCAL}, {device.upper()})")
|
| 175 |
+
except Exception as e:
|
| 176 |
+
_gen_backend = "none"
|
| 177 |
+
print(f"β οΈ Generation unavailable: {e}")
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
# ============================================================
|
| 181 |
+
# CORE ENGINE
|
| 182 |
+
# ============================================================
|
| 183 |
+
|
| 184 |
+
def _call_llm(prompt: str, max_new_tokens: int = 450) -> str:
|
| 185 |
+
if _gen_backend == "api":
|
| 186 |
+
return _gen_client.text_generation(
|
| 187 |
+
prompt, max_new_tokens=max_new_tokens,
|
| 188 |
+
temperature=0.7, repetition_penalty=1.1, do_sample=True,
|
| 189 |
+
).strip()
|
| 190 |
+
elif _gen_backend == "local":
|
| 191 |
+
out = _gen_model(
|
| 192 |
+
prompt, max_new_tokens=max_new_tokens, do_sample=True,
|
| 193 |
+
temperature=0.7, repetition_penalty=1.15,
|
| 194 |
+
pad_token_id=_gen_tokenizer.eos_token_id,
|
| 195 |
+
return_full_text=False,
|
| 196 |
+
)
|
| 197 |
+
return out[0]["generated_text"].strip()
|
| 198 |
+
return "[Generation unavailable β add HF_TOKEN as a Space Secret to enable Mistral.]"
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def _build_prompt(system_msg: str, user_msg: str) -> str:
|
| 202 |
+
if _gen_backend == "api":
|
| 203 |
+
return f"<s>[INST] {system_msg}\n\n{user_msg} [/INST]"
|
| 204 |
+
return (
|
| 205 |
+
f"<|system|>\n{system_msg}</s>\n"
|
| 206 |
+
f"<|user|>\n{user_msg}</s>\n"
|
| 207 |
+
f"<|assistant|>\n"
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def recommend_vendors(
|
| 212 |
+
event_brief: str, event_city: str,
|
| 213 |
+
event_season: str, total_budget_usd: float, top_n: int = 3,
|
| 214 |
+
) -> dict:
|
| 215 |
+
from sentence_transformers import util as st_util
|
| 216 |
+
if _embed_model is None or _vendor_embeddings is None:
|
| 217 |
+
return {"error": "Models still loading β please wait a moment and try again."}
|
| 218 |
+
if not event_brief.strip():
|
| 219 |
+
return {"error": "Please enter an event description."}
|
| 220 |
+
|
| 221 |
+
city_ok = np.array([event_city in c for c in _vcities], dtype=bool)
|
| 222 |
+
season_ok = np.array([event_season in s for s in _vseasons], dtype=bool)
|
| 223 |
+
alloc_vec = np.array(
|
| 224 |
+
[total_budget_usd * ALLOC_RATIOS.get(cat, 0.10) for cat in _vcats],
|
| 225 |
+
dtype=float,
|
| 226 |
+
)
|
| 227 |
+
budget_ok = _vrates <= alloc_vec
|
| 228 |
+
combined = city_ok & season_ok & budget_ok
|
| 229 |
+
pool_idx = _vidx[combined].tolist()
|
| 230 |
+
|
| 231 |
+
if not pool_idx:
|
| 232 |
+
return {"error": (
|
| 233 |
+
f"No vendors matched all filters "
|
| 234 |
+
f"(city: {int(city_ok.sum())}, season: {int(season_ok.sum())}, "
|
| 235 |
+
f"budget: {int(budget_ok.sum())}, combined: 0). "
|
| 236 |
+
f"Try a larger budget or a different city."
|
| 237 |
+
)}
|
| 238 |
+
|
| 239 |
+
q_vec = _embed_model.encode(
|
| 240 |
+
event_brief, convert_to_tensor=True, normalize_embeddings=True,
|
| 241 |
+
)
|
| 242 |
+
pool_embeds = _vendor_embeddings[pool_idx]
|
| 243 |
+
sims = st_util.cos_sim(q_vec, pool_embeds)[0].cpu().numpy()
|
| 244 |
+
|
| 245 |
+
pool_df = _df_vendors.iloc[pool_idx].copy().reset_index(drop=True)
|
| 246 |
+
pool_df["semantic_similarity"] = sims
|
| 247 |
+
pool_df["final_score"] = 0.8 * sims + 0.2 * _vcomp[pool_idx]
|
| 248 |
+
|
| 249 |
+
results = {}
|
| 250 |
+
for cat in VENDOR_CATEGORIES:
|
| 251 |
+
sub = pool_df[pool_df["category"] == cat].nlargest(top_n, "final_score")
|
| 252 |
+
if len(sub):
|
| 253 |
+
results[cat] = sub[[
|
| 254 |
+
"vendor_name", "category", "price_tier",
|
| 255 |
+
"avg_rating", "sla_compliance_rate", "day_rate_mid",
|
| 256 |
+
"specializations", "semantic_similarity",
|
| 257 |
+
"composite_score", "final_score",
|
| 258 |
+
]].to_dict("records")
|
| 259 |
+
return results
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def generate_run_of_show(
|
| 263 |
+
event_type, event_date, venue_name, city,
|
| 264 |
+
guest_count, selected_vendors, special_notes="",
|
| 265 |
+
) -> str:
|
| 266 |
+
vendor_lines = "\n".join(
|
| 267 |
+
f" - {cat.replace('_', ' ')}: {name}"
|
| 268 |
+
for cat, name in selected_vendors.items()
|
| 269 |
+
)
|
| 270 |
+
system_msg = (
|
| 271 |
+
"You are a senior event production manager. "
|
| 272 |
+
"Write detailed professional Run of Show documents "
|
| 273 |
+
"using format HH:MM β Task. Be specific about timings."
|
| 274 |
+
)
|
| 275 |
+
user_msg = (
|
| 276 |
+
f"Write a complete Run of Show for:\n\n"
|
| 277 |
+
f"Event Type : {event_type}\n"
|
| 278 |
+
f"Date : {event_date}\n"
|
| 279 |
+
f"Venue : {venue_name}, {city}\n"
|
| 280 |
+
f"Guests : {guest_count:,}\n"
|
| 281 |
+
f"Special Notes: {special_notes or 'None'}\n\n"
|
| 282 |
+
f"Confirmed Vendors:\n{vendor_lines}\n\n"
|
| 283 |
+
f"Cover: vendor arrivals, setup, guest arrival, programme, breakdown."
|
| 284 |
+
)
|
| 285 |
+
return _call_llm(_build_prompt(system_msg, user_msg), max_new_tokens=500)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def generate_rfp(
|
| 289 |
+
vendor_name, vendor_category, specializations,
|
| 290 |
+
event_type, event_date, city, guest_count,
|
| 291 |
+
allocated_budget_usd, special_requirements="",
|
| 292 |
+
) -> str:
|
| 293 |
+
specs_str = ", ".join(specializations[:3]) if specializations else "general services"
|
| 294 |
+
cat_label = vendor_category.replace("_", " ")
|
| 295 |
+
system_msg = (
|
| 296 |
+
"You are a professional event producer writing formal B2B emails. "
|
| 297 |
+
"Be specific and professional. End with a clear call to action."
|
| 298 |
+
)
|
| 299 |
+
user_msg = (
|
| 300 |
+
f"Write a formal RFP email to:\n\n"
|
| 301 |
+
f"Company : {vendor_name}\n"
|
| 302 |
+
f"Category : {cat_label}\n"
|
| 303 |
+
f"Specialisms : {specs_str}\n\n"
|
| 304 |
+
f"Event:\n"
|
| 305 |
+
f" Type : {event_type}\n"
|
| 306 |
+
f" Date : {event_date}\n"
|
| 307 |
+
f" Location : {city}\n"
|
| 308 |
+
f" Guests : {guest_count:,}\n"
|
| 309 |
+
f" Budget : ${allocated_budget_usd:,.0f} for {cat_label}\n"
|
| 310 |
+
f" Requirements: {special_requirements or 'Standard service'}\n\n"
|
| 311 |
+
f"Request availability and a quote within 48 hours."
|
| 312 |
+
)
|
| 313 |
+
return _call_llm(_build_prompt(system_msg, user_msg), max_new_tokens=350)
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
# ============================================================
|
| 317 |
+
# GRADIO HANDLERS
|
| 318 |
+
# ============================================================
|
| 319 |
+
|
| 320 |
+
def _stars(rating: float) -> str:
|
| 321 |
+
n = int(round(float(rating)))
|
| 322 |
+
return "β" * n + "β" * (5 - n)
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def _format_recommendations(recs: dict, total_budget: float) -> str:
|
| 326 |
+
if "error" in recs:
|
| 327 |
+
return f"### β οΈ No Results\n\n{recs['error']}"
|
| 328 |
+
lines = ["## πͺ Recommended Vendors\n"]
|
| 329 |
+
for cat in VENDOR_CATEGORIES:
|
| 330 |
+
if cat not in recs:
|
| 331 |
+
continue
|
| 332 |
+
alloc = total_budget * ALLOC_RATIOS[cat]
|
| 333 |
+
lines.append(
|
| 334 |
+
f"### {CATEGORY_EMOJI[cat]} {cat.replace('_', ' ')} "
|
| 335 |
+
f"Β· Budget: ${alloc:,.0f}"
|
| 336 |
+
)
|
| 337 |
+
for rank, v in enumerate(recs[cat], 1):
|
| 338 |
+
specs = v.get("specializations", [])
|
| 339 |
+
if isinstance(specs, str):
|
| 340 |
+
try:
|
| 341 |
+
specs = json.loads(specs)
|
| 342 |
+
except Exception:
|
| 343 |
+
specs = []
|
| 344 |
+
score = v.get("final_score", v.get("semantic_similarity", 0))
|
| 345 |
+
lines.append(
|
| 346 |
+
f"**#{rank} {v['vendor_name']}** \n"
|
| 347 |
+
f"{_stars(v.get('avg_rating', 0))} Β· "
|
| 348 |
+
f"{v.get('sla_compliance_rate', 0):.0%} SLA Β· "
|
| 349 |
+
f"${v.get('day_rate_mid', 0):,.0f}/day \n"
|
| 350 |
+
f"*{', '.join(specs[:2]) if specs else 'β'}* Β· "
|
| 351 |
+
f"Match: `{score:.3f}`\n"
|
| 352 |
+
)
|
| 353 |
+
lines.append("---")
|
| 354 |
+
return "\n".join(lines)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def handle_recommend(brief: str, city: str, season: str, budget: float) -> str:
|
| 358 |
+
if _df_vendors is None:
|
| 359 |
+
return "β³ Still loading β please wait a moment and try again."
|
| 360 |
+
recs = recommend_vendors(brief, city, season, budget)
|
| 361 |
+
return _format_recommendations(recs, budget)
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def handle_generate(
|
| 365 |
+
brief, city, season, budget,
|
| 366 |
+
ev_type, ev_date, ev_venue, guests, notes,
|
| 367 |
+
progress=gr.Progress(),
|
| 368 |
+
) -> tuple:
|
| 369 |
+
if _gen_backend in ("none", None):
|
| 370 |
+
msg = "β οΈ Generation unavailable. Add HF_TOKEN as a Space Secret."
|
| 371 |
+
return msg, msg
|
| 372 |
+
|
| 373 |
+
progress(0, desc="Finding vendors...")
|
| 374 |
+
recs = recommend_vendors(brief, city, season, float(budget))
|
| 375 |
+
if "error" in recs:
|
| 376 |
+
return f"β οΈ {recs['error']}", f"β οΈ {recs['error']}"
|
| 377 |
+
|
| 378 |
+
selected_vendors = {}
|
| 379 |
+
rfp_targets = []
|
| 380 |
+
for cat in VENDOR_CATEGORIES:
|
| 381 |
+
if cat not in recs or not recs[cat]:
|
| 382 |
+
continue
|
| 383 |
+
top = recs[cat][0]
|
| 384 |
+
name = top.get("vendor_name", "Unknown")
|
| 385 |
+
specs = top.get("specializations", [])
|
| 386 |
+
if isinstance(specs, str):
|
| 387 |
+
try:
|
| 388 |
+
specs = json.loads(specs)
|
| 389 |
+
except Exception:
|
| 390 |
+
specs = []
|
| 391 |
+
selected_vendors[cat] = name
|
| 392 |
+
rfp_targets.append({
|
| 393 |
+
"vendor_name": name, "category": cat,
|
| 394 |
+
"specializations": specs,
|
| 395 |
+
"allocated_usd": float(budget) * ALLOC_RATIOS[cat],
|
| 396 |
+
})
|
| 397 |
+
|
| 398 |
+
progress(0.2, desc="Generating Run of Show...")
|
| 399 |
+
ros = generate_run_of_show(
|
| 400 |
+
event_type=ev_type, event_date=ev_date, venue_name=ev_venue,
|
| 401 |
+
city=city, guest_count=int(guests),
|
| 402 |
+
selected_vendors=selected_vendors, special_notes=notes,
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
top3 = sorted(rfp_targets, key=lambda x: -x["allocated_usd"])[:3]
|
| 406 |
+
rfp_blocks = []
|
| 407 |
+
for j, t in enumerate(top3, 1):
|
| 408 |
+
progress(0.2 + 0.25 * j, desc=f"Generating RFP {j}/3...")
|
| 409 |
+
rfp_text = generate_rfp(
|
| 410 |
+
vendor_name=t["vendor_name"], vendor_category=t["category"],
|
| 411 |
+
specializations=t["specializations"], event_type=ev_type,
|
| 412 |
+
event_date=ev_date, city=city, guest_count=int(guests),
|
| 413 |
+
allocated_budget_usd=t["allocated_usd"], special_requirements=notes,
|
| 414 |
+
)
|
| 415 |
+
cat_label = t["category"].replace("_", " ")
|
| 416 |
+
rfp_blocks.append(
|
| 417 |
+
f"{'='*58}\n RFP β {cat_label.upper()}\n"
|
| 418 |
+
f" TO: {t['vendor_name']}\n"
|
| 419 |
+
f" BUDGET: ${t['allocated_usd']:,.0f}\n"
|
| 420 |
+
f"{'='*58}\n\n" + rfp_text + "\n"
|
| 421 |
+
)
|
| 422 |
+
return ros, "\n\n".join(rfp_blocks)
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def _qs_and_find(idx: int):
|
| 426 |
+
brief, city, season, budget = QUICK_STARTERS[idx]
|
| 427 |
+
md = handle_recommend(brief, city, season, budget)
|
| 428 |
+
return brief, city, season, budget, md
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
# ============================================================
|
| 432 |
+
# GRADIO UI
|
| 433 |
+
# ============================================================
|
| 434 |
+
|
| 435 |
+
CSS = """
|
| 436 |
+
.prosync-header {
|
| 437 |
+
background: linear-gradient(135deg, #2C3E50 0%, #1a6ea8 100%);
|
| 438 |
+
border-radius: 12px; padding: 28px 32px; margin-bottom: 8px;
|
| 439 |
+
}
|
| 440 |
+
.prosync-header h1 { margin: 0; font-size: 2rem; font-weight: 700; color: white; }
|
| 441 |
+
.prosync-header p { margin: 6px 0 0; opacity: 0.85; color: white; font-size: 1rem; }
|
| 442 |
+
.qs-btn {
|
| 443 |
+
background: #EBF5FB !important; border: 1px solid #3498DB !important;
|
| 444 |
+
color: #1a6ea8 !important; font-weight: 600 !important; border-radius: 8px !important;
|
| 445 |
+
}
|
| 446 |
+
.qs-btn:hover { background: #D6EAF8 !important; }
|
| 447 |
+
.find-btn {
|
| 448 |
+
background: #2C3E50 !important; color: white !important;
|
| 449 |
+
font-size: 1rem !important; font-weight: 700 !important;
|
| 450 |
+
border-radius: 8px !important; padding: 12px !important;
|
| 451 |
+
}
|
| 452 |
+
.gen-btn {
|
| 453 |
+
background: #1a6ea8 !important; color: white !important;
|
| 454 |
+
font-size: 0.95rem !important; font-weight: 600 !important;
|
| 455 |
+
border-radius: 8px !important;
|
| 456 |
+
}
|
| 457 |
+
"""
|
| 458 |
+
|
| 459 |
+
with gr.Blocks(theme=gr.themes.Soft(), css=CSS, title="ProSync AI") as demo:
|
| 460 |
+
|
| 461 |
+
gr.HTML("""
|
| 462 |
+
<div class="prosync-header">
|
| 463 |
+
<h1>π― ProSync AI</h1>
|
| 464 |
+
<p>The Event Producer's Command Center β intelligent vendor matching & document generation</p>
|
| 465 |
+
</div>
|
| 466 |
+
""")
|
| 467 |
+
|
| 468 |
+
with gr.Row():
|
| 469 |
+
with gr.Column(scale=1, min_width=320):
|
| 470 |
+
gr.Markdown("### β‘ Quick Starters")
|
| 471 |
+
gr.Markdown("Click to auto-fill and search instantly.")
|
| 472 |
+
with gr.Row():
|
| 473 |
+
qs0 = gr.Button("ποΈ Tech Summit Β· Tel Aviv", elem_classes=["qs-btn"])
|
| 474 |
+
qs1 = gr.Button("π½οΈ Gala Dinner Β· Jerusalem", elem_classes=["qs-btn"])
|
| 475 |
+
with gr.Row():
|
| 476 |
+
qs2 = gr.Button("πΏ Team Building Β· Haifa", elem_classes=["qs-btn"])
|
| 477 |
+
|
| 478 |
+
gr.Markdown("---")
|
| 479 |
+
gr.Markdown("### π Event Brief")
|
| 480 |
+
brief_input = gr.Textbox(
|
| 481 |
+
label="Describe your event",
|
| 482 |
+
placeholder=(
|
| 483 |
+
"e.g. Tech summit for 400 guests β advanced AV, live streaming, "
|
| 484 |
+
"kosher catering, VIP security..."
|
| 485 |
+
),
|
| 486 |
+
lines=4,
|
| 487 |
+
)
|
| 488 |
+
with gr.Row():
|
| 489 |
+
city_input = gr.Dropdown(label="City", choices=CITIES, value="Tel Aviv")
|
| 490 |
+
season_input = gr.Dropdown(label="Season", choices=SEASONS, value="Summer")
|
| 491 |
+
budget_input = gr.Slider(
|
| 492 |
+
label="Total Budget (USD)",
|
| 493 |
+
minimum=20_000, maximum=600_000, step=5_000, value=200_000,
|
| 494 |
+
)
|
| 495 |
+
find_btn = gr.Button(
|
| 496 |
+
"π Find Vendors", variant="primary", elem_classes=["find-btn"],
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
gr.Markdown("---")
|
| 500 |
+
gr.Markdown("### π Document Settings")
|
| 501 |
+
with gr.Row():
|
| 502 |
+
ev_type_input = gr.Dropdown(
|
| 503 |
+
label="Event Type", choices=EVENT_TYPES, value="Tech Summit",
|
| 504 |
+
)
|
| 505 |
+
guests_input = gr.Number(
|
| 506 |
+
label="Guest Count", value=300, minimum=10, maximum=5000,
|
| 507 |
+
)
|
| 508 |
+
with gr.Row():
|
| 509 |
+
date_input = gr.Textbox(label="Event Date", value="October 15, 2025")
|
| 510 |
+
venue_input = gr.Textbox(label="Venue Name", value="Grand Convention Center")
|
| 511 |
+
notes_input = gr.Textbox(
|
| 512 |
+
label="Special Requirements (optional)",
|
| 513 |
+
placeholder="e.g. Kosher catering, VIP lounge for 20 guests...",
|
| 514 |
+
lines=2,
|
| 515 |
+
)
|
| 516 |
+
gen_btn = gr.Button(
|
| 517 |
+
"π Generate Run of Show + RFP Emails",
|
| 518 |
+
variant="secondary", elem_classes=["gen-btn"],
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
with gr.Column(scale=2, min_width=480):
|
| 522 |
+
with gr.Tabs():
|
| 523 |
+
with gr.Tab("πͺ Vendor Matches"):
|
| 524 |
+
vendor_output = gr.Markdown(
|
| 525 |
+
value="_Click **Find Vendors** or a Quick Starter to see results._",
|
| 526 |
+
)
|
| 527 |
+
with gr.Tab("π Run of Show"):
|
| 528 |
+
ros_output = gr.Textbox(
|
| 529 |
+
label="Generated Run of Show", lines=28,
|
| 530 |
+
interactive=False,
|
| 531 |
+
placeholder="Click 'Generate Documents' to produce a schedule...",
|
| 532 |
+
)
|
| 533 |
+
with gr.Tab("βοΈ RFP Emails"):
|
| 534 |
+
rfp_output = gr.Textbox(
|
| 535 |
+
label="Generated RFP Emails (top 3 by spend)", lines=28,
|
| 536 |
+
interactive=False,
|
| 537 |
+
placeholder="Click 'Generate Documents' to produce RFP emails...",
|
| 538 |
+
)
|
| 539 |
+
|
| 540 |
+
gr.Markdown("---")
|
| 541 |
+
gr.Markdown("#### π Example Inputs")
|
| 542 |
+
gr.Examples(
|
| 543 |
+
examples=[[q[0], q[1], q[2], q[3]] for q in QUICK_STARTERS],
|
| 544 |
+
inputs=[brief_input, city_input, season_input, budget_input],
|
| 545 |
+
outputs=[vendor_output],
|
| 546 |
+
fn=handle_recommend,
|
| 547 |
+
cache_examples=False,
|
| 548 |
+
label="Quick Start Examples",
|
| 549 |
+
)
|
| 550 |
+
|
| 551 |
+
# ββ Event wiring ββββββββββββββββββββββββββββββββββββββββββ
|
| 552 |
+
_qs_outs = [brief_input, city_input, season_input, budget_input, vendor_output]
|
| 553 |
+
qs0.click(fn=lambda: _qs_and_find(0), outputs=_qs_outs)
|
| 554 |
+
qs1.click(fn=lambda: _qs_and_find(1), outputs=_qs_outs)
|
| 555 |
+
qs2.click(fn=lambda: _qs_and_find(2), outputs=_qs_outs)
|
| 556 |
+
|
| 557 |
+
find_btn.click(
|
| 558 |
+
fn=handle_recommend,
|
| 559 |
+
inputs=[brief_input, city_input, season_input, budget_input],
|
| 560 |
+
outputs=[vendor_output],
|
| 561 |
+
)
|
| 562 |
+
gen_btn.click(
|
| 563 |
+
fn=handle_generate,
|
| 564 |
+
inputs=[
|
| 565 |
+
brief_input, city_input, season_input, budget_input,
|
| 566 |
+
ev_type_input, date_input, venue_input, guests_input, notes_input,
|
| 567 |
+
],
|
| 568 |
+
outputs=[ros_output, rfp_output],
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
gr.Markdown(
|
| 572 |
+
"<br><center style='color:#95A5A6; font-size:0.8rem;'>"
|
| 573 |
+
"ProSync AI Β· Gradio + HuggingFace Β· "
|
| 574 |
+
"Embedding: all-MiniLM-L6-v2 Β· Generation: TinyLlama-1.1B"
|
| 575 |
+
"</center>"
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
# ββ Deferred startup β runs after Gradio initialises ββ
|
| 579 |
+
demo.load(fn=load_all, inputs=[], outputs=[])
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
if __name__ == "__main__":
|
| 583 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=4.0.0
|
| 2 |
+
pandas
|
| 3 |
+
numpy
|
| 4 |
+
sentence-transformers
|
| 5 |
+
transformers>=4.36.0
|
| 6 |
+
torch
|
| 7 |
+
huggingface_hub>=0.20.0
|
| 8 |
+
datasets
|
| 9 |
+
scipy
|
| 10 |
+
accelerate
|