Spaces:
Sleeping
Sleeping
File size: 17,286 Bytes
1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 a3ebc4b 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 a3ebc4b 1eeb708 a3ebc4b 1eeb708 a3ebc4b 1eeb708 ad03a6c 1eeb708 ad03a6c a3ebc4b ad03a6c 1eeb708 ad03a6c a3ebc4b 1eeb708 ad03a6c a3ebc4b 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c a3ebc4b ad03a6c a3ebc4b ad03a6c a3ebc4b 1eeb708 a3ebc4b 1eeb708 a3ebc4b 1eeb708 a3ebc4b 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 a3ebc4b 1eeb708 a3ebc4b ad03a6c 1eeb708 a3ebc4b ad03a6c a3ebc4b ad03a6c a3ebc4b ad03a6c a3ebc4b ad03a6c a3ebc4b ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c 1eeb708 ad03a6c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 | import os
import json
import requests
import pandas as pd
import gradio as gr
APP_NAME = "StayWise AI"
DATA_FILE = "synthetic_airbnb_project_data.csv"
N8N_WEBHOOK_URL = os.getenv("N8N_WEBHOOK_URL", "").strip()
def load_data():
return pd.read_csv(DATA_FILE)
df = load_data()
def safe_mean(series, default=0):
series = pd.to_numeric(series, errors="coerce").dropna()
if len(series) == 0:
return default
return float(series.mean())
def get_choices(column):
return sorted(df[column].dropna().astype(str).unique().tolist())
neighbourhood_groups = get_choices("neighbourhood_group")
neighbourhoods = get_choices("neighbourhood")
room_types = get_choices("room_type")
seasons = get_choices("season") if "season" in df.columns else ["Low Season", "Medium Season", "High Season"]
def call_n8n(payload):
if not N8N_WEBHOOK_URL:
return {
"status": "not_configured",
"insight": "n8n webhook is not configured yet.",
"next_step": "Add N8N_WEBHOOK_URL in Hugging Face Space secrets.",
"log": "Pipeline ran locally only."
}
try:
response = requests.post(N8N_WEBHOOK_URL, json=payload, timeout=15)
if response.status_code >= 200 and response.status_code < 300:
try:
data = response.json()
return {
"status": data.get("status", "success"),
"insight": data.get("insight", "n8n processed the recommendation."),
"next_step": data.get("next_step", "Review the generated automation output."),
"log": data.get("log", "Automation completed.")
}
except Exception:
return {
"status": "success",
"insight": "n8n received the data.",
"next_step": "Check your n8n workflow output.",
"log": response.text[:500]
}
return {
"status": "error",
"insight": f"n8n returned status code {response.status_code}.",
"next_step": "Check your webhook and Respond to Webhook node.",
"log": response.text[:500]
}
except Exception as e:
return {
"status": "error",
"insight": "The app could not reach n8n.",
"next_step": "Check that the n8n production webhook is active.",
"log": str(e)
}
def run_pipeline(
neighbourhood_group,
neighbourhood,
room_type,
price,
availability_365,
season,
local_event_score,
rating,
sentiment_score,
send_to_n8n
):
price = float(price)
availability_365 = float(availability_365)
local_event_score = float(local_event_score)
rating = float(rating)
sentiment_score = float(sentiment_score)
comparable = df.copy()
comparable = comparable[
(comparable["neighbourhood_group"].astype(str) == str(neighbourhood_group)) &
(comparable["room_type"].astype(str) == str(room_type))
]
local_comparable = comparable[comparable["neighbourhood"].astype(str) == str(neighbourhood)]
if len(local_comparable) >= 5:
comparable = local_comparable
if len(comparable) < 5:
comparable = df[df["room_type"].astype(str) == str(room_type)]
competitor_avg_price = safe_mean(comparable["price"], price)
avg_occupancy = safe_mean(comparable["occupancy_rate"], 0.5)
avg_demand = safe_mean(comparable["demand_score"], 50)
price_gap_pct = ((price - competitor_avg_price) / competitor_avg_price) * 100 if competitor_avg_price else 0
season_boost = {
"Low Season": -0.08,
"Medium Season": 0.00,
"High Season": 0.08,
"Low": -0.08,
"Medium": 0.00,
"High": 0.08,
"Peak": 0.12,
"Spring": 0.03,
"Summer": 0.08,
"Autumn": 0.00,
"Winter": -0.05
}.get(str(season), 0.00)
price_penalty = max(min(price_gap_pct / 100, 0.35), -0.35) * 0.30
event_boost = (local_event_score / 100) * 0.12
rating_boost = (rating - 4.0) * 0.06
sentiment_boost = sentiment_score * 0.08
occupancy = avg_occupancy + season_boost + event_boost + rating_boost + sentiment_boost - price_penalty
occupancy = max(0.05, min(0.95, occupancy))
booked_nights = round(occupancy * 30)
monthly_revenue = round(price * booked_nights, 2)
demand_score = (
0.45 * avg_demand +
0.25 * (occupancy * 100) +
0.15 * local_event_score +
0.10 * ((rating / 5) * 100) +
0.05 * ((sentiment_score + 1) / 2 * 100)
)
demand_score = round(max(0, min(100, demand_score)), 1)
if demand_score >= 70:
demand_level = "High"
demand_badge = "π’ High"
elif demand_score >= 45:
demand_level = "Medium"
demand_badge = "π‘ Medium"
else:
demand_level = "Low"
demand_badge = "π΄ Low"
if price_gap_pct > 15 and demand_level != "High":
pricing_recommendation = "Consider lowering price"
suggested_price = round(competitor_avg_price * 1.05, 2)
insight = "The listing appears overpriced compared with similar properties."
next_step = f"Test a lower price around ${suggested_price} to improve occupancy."
recommendation_badge = "π» Price Reduction Suggested"
elif price_gap_pct < -10 and demand_level in ["Medium", "High"]:
pricing_recommendation = "Consider raising price"
suggested_price = round(min(competitor_avg_price * 0.98, price * 1.12), 2)
insight = "The listing appears underpriced relative to comparable demand."
next_step = f"Consider increasing the price toward ${suggested_price}."
recommendation_badge = "π Revenue Opportunity"
else:
pricing_recommendation = "Keep price stable"
suggested_price = round(price, 2)
insight = "The current price is aligned with comparable listings."
next_step = "Keep price stable and focus on visibility, reviews, and conversion."
recommendation_badge = "β
Stable Positioning"
opportunity_score = round(
demand_score * 0.45 +
occupancy * 100 * 0.25 +
rating / 5 * 100 * 0.15 +
((sentiment_score + 1) / 2 * 100) * 0.15,
2
)
payload = {
"app_name": APP_NAME,
"neighbourhood_group": neighbourhood_group,
"neighbourhood": neighbourhood,
"room_type": room_type,
"current_price": price,
"suggested_price": suggested_price,
"competitor_avg_price": round(competitor_avg_price, 2),
"price_vs_competitor_pct": round(price_gap_pct, 2),
"occupancy_estimate": round(occupancy, 3),
"booked_nights_month": booked_nights,
"monthly_revenue": monthly_revenue,
"demand_score": demand_score,
"demand_level": demand_level,
"opportunity_score": opportunity_score,
"pricing_recommendation": pricing_recommendation,
"insight": insight,
"next_step": next_step
}
if send_to_n8n:
n8n_response = call_n8n(payload)
else:
n8n_response = {
"status": "not_sent",
"insight": "n8n automation was not triggered.",
"next_step": "Tick the n8n checkbox to send this result to the workflow.",
"log": "Local pipeline only."
}
result_text = f"""
<div class="result-card">
<div class="section-label">Pipeline Result</div>
<h2>{recommendation_badge}</h2>
<div class="kpi-grid">
<div class="kpi-card">
<div class="kpi-title">Current Price</div>
<div class="kpi-value">${price:,.0f}</div>
</div>
<div class="kpi-card">
<div class="kpi-title">Suggested Price</div>
<div class="kpi-value">${suggested_price:,.0f}</div>
</div>
<div class="kpi-card">
<div class="kpi-title">Monthly Revenue</div>
<div class="kpi-value">${monthly_revenue:,.0f}</div>
</div>
<div class="kpi-card">
<div class="kpi-title">Demand</div>
<div class="kpi-value">{demand_badge}</div>
</div>
</div>
<h3>Key Metrics</h3>
<table class="metric-table">
<tr><td>Competitor average price</td><td>${competitor_avg_price:,.2f}</td></tr>
<tr><td>Price vs competitors</td><td>{price_gap_pct:.2f}%</td></tr>
<tr><td>Estimated occupancy</td><td>{occupancy * 100:.1f}%</td></tr>
<tr><td>Estimated booked nights / month</td><td>{booked_nights}</td></tr>
<tr><td>Demand score</td><td>{demand_score}/100</td></tr>
<tr><td>Opportunity score</td><td>{opportunity_score}/100</td></tr>
</table>
<h3>Business Insight</h3>
<p>{insight}</p>
<h3>Next Step</h3>
<p>{next_step}</p>
</div>
"""
automation_text = f"""
<div class="automation-card">
<div class="section-label">n8n Automation Output</div>
<h2>Automation Status: {n8n_response.get("status", "unknown")}</h2>
<table class="metric-table">
<tr><td>Insight</td><td>{n8n_response.get("insight", "No insight returned.")}</td></tr>
<tr><td>Next step</td><td>{n8n_response.get("next_step", "No next step returned.")}</td></tr>
<tr><td>Log</td><td>{n8n_response.get("log", "No log returned.")}</td></tr>
</table>
</div>
"""
cols = [
"id",
"name",
"neighbourhood_group",
"neighbourhood",
"room_type",
"price",
"occupancy_rate",
"monthly_revenue",
"demand_score",
"demand_level",
"pricing_recommendation"
]
available_cols = [c for c in cols if c in comparable.columns]
comparable_table = comparable[available_cols].head(10)
json_output = json.dumps(payload, indent=2)
return result_text, automation_text, comparable_table, json_output
custom_css = """
/* Main background */
body {
background: radial-gradient(circle at top left, #1e3a8a 0%, #0f172a 35%, #020617 100%) !important;
color: #f8fafc !important;
}
/* Main container */
.gradio-container {
max-width: 1250px !important;
margin: auto !important;
font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, sans-serif !important;
}
/* Header */
#hero {
background: linear-gradient(135deg, rgba(37, 99, 235, 0.95), rgba(14, 165, 233, 0.85));
border-radius: 28px;
padding: 38px 42px;
margin-bottom: 26px;
box-shadow: 0 25px 60px rgba(0, 0, 0, 0.35);
border: 1px solid rgba(255,255,255,0.16);
}
#hero h1 {
font-size: 48px;
margin: 0 0 8px 0;
color: white;
letter-spacing: -1px;
}
#hero p {
font-size: 18px;
margin: 6px 0 0 0;
color: #e0f2fe;
}
.hero-badge {
display: inline-block;
padding: 6px 12px;
background: rgba(255,255,255,0.16);
border: 1px solid rgba(255,255,255,0.22);
border-radius: 999px;
font-size: 13px;
margin-bottom: 14px;
color: white;
}
/* Panels */
.gr-block, .gr-form, .gr-box, .gr-panel {
border-radius: 20px !important;
}
.input-panel {
background: rgba(15, 23, 42, 0.82);
border: 1px solid rgba(148, 163, 184, 0.25);
border-radius: 24px;
padding: 20px;
box-shadow: 0 15px 45px rgba(0,0,0,0.25);
}
/* Buttons */
button.primary, .gr-button {
border-radius: 14px !important;
font-weight: 700 !important;
background: linear-gradient(90deg, #2563eb, #06b6d4) !important;
border: none !important;
color: white !important;
box-shadow: 0 10px 25px rgba(37, 99, 235, 0.32) !important;
}
button.primary:hover, .gr-button:hover {
transform: translateY(-1px);
filter: brightness(1.08);
}
/* Labels */
label, .wrap label {
color: #dbeafe !important;
font-weight: 600 !important;
}
/* Inputs */
input, textarea, select {
border-radius: 12px !important;
}
/* Slider */
input[type="range"] {
accent-color: #38bdf8 !important;
}
/* Output cards */
.result-card, .automation-card {
background: rgba(15, 23, 42, 0.88);
border: 1px solid rgba(148, 163, 184, 0.25);
border-radius: 26px;
padding: 26px;
margin-bottom: 22px;
box-shadow: 0 18px 50px rgba(0,0,0,0.28);
}
.result-card h2, .automation-card h2 {
margin-top: 8px;
color: #f8fafc;
font-size: 26px;
}
.result-card h3, .automation-card h3 {
margin-top: 24px;
color: #bae6fd;
font-size: 20px;
}
.result-card p, .automation-card p {
color: #e5e7eb;
line-height: 1.6;
}
.section-label {
display: inline-block;
background: rgba(56, 189, 248, 0.13);
border: 1px solid rgba(56, 189, 248, 0.35);
color: #7dd3fc;
padding: 7px 13px;
border-radius: 999px;
font-size: 13px;
font-weight: 700;
letter-spacing: 0.4px;
text-transform: uppercase;
}
/* KPI Cards */
.kpi-grid {
display: grid;
grid-template-columns: repeat(4, minmax(120px, 1fr));
gap: 14px;
margin: 22px 0;
}
.kpi-card {
background: linear-gradient(180deg, rgba(30, 41, 59, 0.95), rgba(15, 23, 42, 0.95));
border: 1px solid rgba(148, 163, 184, 0.25);
border-radius: 18px;
padding: 18px;
}
.kpi-title {
color: #94a3b8;
font-size: 13px;
margin-bottom: 8px;
}
.kpi-value {
color: #f8fafc;
font-size: 22px;
font-weight: 800;
}
/* Tables */
.metric-table {
width: 100%;
border-collapse: collapse;
overflow: hidden;
border-radius: 14px;
margin-top: 12px;
}
.metric-table td {
padding: 12px 14px;
border-bottom: 1px solid rgba(148, 163, 184, 0.18);
color: #e5e7eb;
}
.metric-table td:first-child {
color: #93c5fd;
font-weight: 650;
width: 45%;
}
.metric-table tr:last-child td {
border-bottom: none;
}
/* Dataframe and code areas */
.dataframe, .wrap, .contain {
border-radius: 18px !important;
}
/* Footer text */
.small-note {
color: #94a3b8;
font-size: 13px;
margin-top: -8px;
margin-bottom: 18px;
}
@media (max-width: 900px) {
.kpi-grid {
grid-template-columns: repeat(2, minmax(120px, 1fr));
}
#hero h1 {
font-size: 36px;
}
}
"""
with gr.Blocks(css=custom_css) as demo:
gr.HTML(
"""
<div id="hero">
<div class="hero-badge">Short-Term Rental Pricing Assistant</div>
<h1>π StayWise AI</h1>
<p>AI-powered pricing and performance optimization for short-term rentals.</p>
<p class="small-note">Run the full pipeline, benchmark a listing against comparable properties, and return automation insights from n8n.</p>
</div>
"""
)
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("## π Property Inputs")
neighbourhood_group = gr.Dropdown(
choices=neighbourhood_groups,
label="Neighbourhood Group",
value=neighbourhood_groups[0]
)
neighbourhood = gr.Dropdown(
choices=neighbourhoods,
label="Neighbourhood",
value=neighbourhoods[0]
)
room_type = gr.Dropdown(
choices=room_types,
label="Room Type",
value=room_types[0]
)
price = gr.Slider(
minimum=20,
maximum=1000,
value=150,
step=5,
label="Current Nightly Price ($)"
)
availability_365 = gr.Slider(
minimum=0,
maximum=365,
value=180,
step=1,
label="Availability per Year"
)
season = gr.Dropdown(
choices=seasons,
label="Season",
value=seasons[0]
)
local_event_score = gr.Slider(
minimum=0,
maximum=100,
value=50,
step=1,
label="Local Event Demand Score"
)
rating = gr.Slider(
minimum=1,
maximum=5,
value=4.4,
step=0.1,
label="Guest Rating"
)
sentiment_score = gr.Slider(
minimum=-1,
maximum=1,
value=0.2,
step=0.05,
label="Customer Sentiment Score"
)
send_to_n8n = gr.Checkbox(
label="Send output to n8n",
value=False
)
run_button = gr.Button("π Run Full Pipeline", variant="primary")
with gr.Column(scale=2):
result_output = gr.HTML()
automation_output = gr.HTML()
gr.Markdown("## π Comparable Listings")
comparable_output = gr.Dataframe()
gr.Markdown("## π§Ύ Pipeline Data Output")
json_output = gr.Code(language="json")
run_button.click(
fn=run_pipeline,
inputs=[
neighbourhood_group,
neighbourhood,
room_type,
price,
availability_365,
season,
local_event_score,
rating,
sentiment_score,
send_to_n8n
],
outputs=[
result_output,
automation_output,
comparable_output,
json_output
]
)
demo.launch() |