Update app.py
Browse files19 unmodified lines20212223242526272810 unmodified lines39404142434447 unmodified lines9293949596974 unmodified lines10210310410510610710834 unmodified lines1431441451461471481491501511521531541551561571582 unmodified lines1611621631641651661671681691701711721731741751761778 unmodified lines1861871881891901911921931 unmodified line195196197198199200201202203204116 unmodified lines3213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553565 unmodified lines36236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653711 unmodified lines54955055155255355455555655755855956056156256356456556656756856957057157257357457557657719 unmodified linesCONDITIONS = ["small mushy beach breaks", "medium clean point breaks","powerful reef breaks", "big open-ocean swell"]CURRENT_STYLE = ["longboard cruiser", "all-around funboard", "fish / groveler","performance shortboard", "step-up / big-wave gun"]GOAL_OPTIONS = {"Get more comfortable on the board I already ride": ("stay_and_improve", "get more comfortable and consistent on the board I already ride"),"Move toward something shorter and more maneuverable": ("transition_to_shortboard", "move from a longer, more stable board toward something shorter and more maneuverable"),"Move toward a longer, more stable board": ("transition_to_longboard", "move toward a longer, more stable board for easier paddling and glide"),10 unmodified lines"step-up / big-wave gun": "step-up gun",}# Same skill -> experience-label ranges used to generate rider_profiles.csv in Part 1,# used here only to turn the UI's single skill slider into an "experience" word for the# Part 4 prompt, which expects one (the real notebook's riders already carry both fields).47 unmodified linesdef compute_style_fit(goal_key, skill_score, current_style):"""Same rule used to build style_fit_truth in Part 1 and to pick a category in Part 3/4."""if goal_key == "transition_to_shortboard":return "performance shortboard" if skill_score >= 55 else "fish / groveler"if goal_key == "transition_to_longboard":4 unmodified linesreturn "performance shortboard" if skill_score >= 60 else "fish / groveler"if goal_key in ("want_easier_paddling", "want_more_stability"):return "longboard cruiser" if skill_score < 40 else "all-around funboard"return current_styledef pct(value, lo, hi):34 unmodified linesreturn pd.DataFrame(picked)def build_query_text(height_cm, weight_kg, skill_score, current_style, conditions, goal_text):"""Mirrors the phrasing of the real profile_text used to train/evaluate the embeddings,so a user's form inputs land in the same region of embedding space as real riders."""return (f"I'm {height_cm}cm tall and {weight_kg}kg, with a skill level of {skill_score}/100. "f"I currently ride a {current_style} and surf {conditions}, and I want to {goal_text}.")def recommend_boards(height_cm, weight_kg, skill_score, current_style, conditions, goal_key, goal_text, k=3):target_category = compute_style_fit(goal_key, skill_score, current_style)weight_pct = pct(weight_kg, W_LO, W_HI)2 unmodified linesvolume_need = 0.5 * weight_pct + 0.5 * forgiveness_pctlength_need = 0.5 * height_pct + 0.5 * forgiveness_pctcandidates = boards_df[boards_df["category"] == target_category].copy()cand_embs = BOARD_EMBS[candidates.index.values]query_text = build_query_text(height_cm, weight_kg, skill_score, current_style, conditions, goal_text)query_emb = embed_model.encode([query_text], normalize_embeddings=True)[0]candidates["similarity"] = cand_embs @ query_embcandidates["volume_score"] = 1 - (volume_need - within_category_pct(candidates["volume_l"])).abs()candidates["length_score"] = 1 - (length_need - within_category_pct(candidates["length_ft"])).abs()candidates["physical_fit"] = 0.5 * candidates["volume_score"] + 0.5 * candidates["length_score"]candidates["combined_score"] = 0.5 * candidates["similarity"] + 0.5 * candidates["physical_fit"]return target_category, pick_diverse(candidates, "combined_score", k=k)8 unmodified lines# the app usable on the ~10% of calls that don't parse.def build_custom_board_prompt(rider, target_category):"""Verbatim from the project notebook's Part 4 (cell 127) - the exact prompt behind thedocumented 90% parse rate and the correlation numbers in the Space README."""r = CATEGORY_RANGES.loc[target_category]weight_pct = pct(rider["weight_kg"], W_LO, W_HI)height_pct = pct(rider["height_cm"], H_LO, H_HI)1 unmodified linefacts = (f"Surfer facts - height {rider['height_cm']}cm, weight {rider['weight_kg']}kg, "f"{rider['experience']} (skill {rider['skill_score']}/100), currently rides "f"a {STYLE_FOR_PROMPT[rider['current_style']]}, surfs {rider['conditions']}, "f"wants to: {rider['goal_text']}. Closest matching standard category: {target_category}.")percentile_hint = (f"Relative to other surfers in our data, this person is heavier than about {weight_pct:.0%} "f"of them, taller than about {height_pct:.0%} of them, and more skilled than about "116 unmodified lines# ββ UI rendering ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef score_badge(score):pct_val = score * 100if pct_val >= 65:cls, label = "badge-great", "Great fit"elif pct_val >= 50:cls, label = "badge-good", "Good fit"else:cls, label = "badge-fair", "Fair fit"return f'<span class="score-badge {cls}">{label} · {pct_val:.0f}%</span>'def board_card(board, rank):return f"""<div class="board-card"><div class="board-card-rank">#{rank}</div><div class="board-card-body"><div class="board-card-title">{board['brand']} {board['model_name']}</div><div class="board-card-category">{board['category'].title()}</div><div class="board-card-stats"><span>{board['length_ft']}ft</span><span>·</span><span>{board['width_in']}in</span><span>·</span><span>{board['thickness_in']}in</span><span>·</span><span>{board['volume_l']}L</span></div><div class="board-card-chips"><span class="chip">{board['tail']}</span><span class="chip">{board['fins']}</span><span class="chip">{board['construction']}</span></div>{score_badge(board['combined_score'])}</div></div>"""5 unmodified linesnote = f'<div class="rationale"><strong>Why:</strong> {spec.get("sizing_reasoning", "")}</div>'return f"""<div class="board-card custom-card"><div class="ai-badge">✨ AI Generated</div><div class="board-card-body"><div class="board-card-title">Your Custom Board</div><div class="board-card-category">{target_category.title()}</div><div class="board-card-stats"><span>{spec['length_ft']}ft</span><span>·</span><span>{spec['width_in']}in</span><span>·</span><span>{spec['thickness_in']}in</span><span>·</span><span>{spec['volume_l']}L</span></div><div class="board-card-chips"><span class="chip chip-accent">{spec['tail']}</span><span class="chip chip-accent">{spec['fins']}</span><span class="chip chip-accent">{spec['construction']}</span></div><div class="rationale">{spec['rationale']}</div>{note}</div></div>"""def find_boards(height_cm, weight_kg, skill_score, goal_label, conditions, current_style):goal_key, goal_text = GOAL_OPTIONS[goal_label]target_category, recs = recommend_boards(height_cm, weight_kg, skill_score, current_style, conditions, goal_key, goal_text,)rider = {"height_cm": height_cm, "weight_kg": weight_kg, "skill_score": skill_score,"experience": experience_for_skill(skill_score), "current_style": current_style,"conditions": conditions, "goal_text": goal_text,}custom = generate_custom_board(rider, target_category)cards_html = '<div class="results-intro">Recommended category: <strong>' + target_category.title() + '</strong></div>'cards_html += '<div class="cards-grid">'for i, (_, board) in enumerate(recs.iterrows(), 1):cards_html += board_card(board, i)cards_html += custom_card(custom, target_category)cards_html += '</div>'return cards_htmlQUICK_STARTERS = {"Beginner wanting stability": (168, 72, 15, "Get more stability and easier paddling", "small mushy beach breaks", "performance shortboard"),"Advanced wanting speed": (178, 75, 78, "Get a faster, more responsive board for sharper turns", "powerful reef breaks", "all-around funboard"),"Longboarder chasing big waves": (182, 85, 60, "Ride a board that can handle bigger, more powerful waves", "big open-ocean swell", "longboard cruiser"),}CSS = """@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@600;700&family=Inter:wght@400;500;600&display=swap');:root {--ocean-deep: #073b4c;--ocean-mid: #0e7c9c;--ocean-light: #4fc4d9;--sand: #fdf6ec;--coral: #ff6b5b;--ink: #1c2b33;--muted: #6b7c85;}.gradio-container { background: var(--sand) !important; font-family: 'Inter', sans-serif !important; }.header-box {background: linear-gradient(135deg, var(--ocean-deep) 0%, var(--ocean-mid) 100%);border-radius: 18px;padding: 32px 36px;margin-bottom: 12px;box-shadow: 0 8px 24px rgba(7, 59, 76, 0.25);}.header-box h1 {font-family: 'Poppins', sans-serif;margin: 0 0 6px 0;font-size: 30px;font-weight: 700;color: white;}.header-box p {margin: 0 0 16px 0;color: rgba(255,255,255,0.88);font-size: 14px;line-height: 1.5;max-width: 560px;}.chips-row { display: flex; gap: 8px; flex-wrap: wrap; }.stat-chip {background: rgba(255,255,255,0.16);color: white;border-radius: 20px;padding: 5px 14px;font-size: 12px;font-weight: 500;}.quick-starters-label { font-weight: 600; color: var(--ink); margin-bottom: 4px; font-size: 13px; }.results-intro {font-size: 15px; color: var(--ink); margin-bottom: 14px; padding: 10px 16px;background: white; border-radius: 10px; border: 1px solid #e5e0d8;}.cards-grid {display: grid;grid-template-columns: repeat(auto-fit, minmax(230px, 1fr));gap: 16px;}.board-card {background: white;border-radius: 14px;padding: 18px;box-shadow: 0 2px 10px rgba(7, 59, 76, 0.08);border: 1px solid #eee6d8;position: relative;}.board-card-rank {position: absolute; top: 14px; right: 14px;background: var(--ocean-light); color: white;border-radius: 50%; width: 24px; height: 24px;display: flex; align-items: center; justify-content: center;font-size: 12px; font-weight: 700;}.board-card-title { font-weight: 700; font-size: 16px; color: var(--ink); margin-bottom: 2px; }.board-card-category { color: var(--ocean-mid); font-size: 12px; font-weight: 600; margin-bottom: 10px; text-transform: uppercase; letter-spacing: 0.03em; }.board-card-stats { display: flex; gap: 6px; color: var(--muted); font-size: 13px; margin-bottom: 10px; }.board-card-chips { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 12px; }.chip { background: #eef6f8; color: var(--ocean-deep); border-radius: 20px; padding: 3px 10px; font-size: 11px; font-weight: 500; }.chip-accent { background: #fff0ee; color: var(--coral); }.score-badge { display: inline-block; border-radius: 20px; padding: 4px 12px; font-size: 12px; font-weight: 600; }.badge-great { background: #e3f9e5; color: #1a7f37; }.badge-good { background: #fff4e0; color: #b06e00; }.badge-fair { background: #f1f1f1; color: #666; }.custom-card { border: 2px solid var(--coral); }.ai-badge {position: absolute; top: -10px; left: 14px;background: var(--coral); color: white;border-radius: 20px; padding: 3px 12px; font-size: 11px; font-weight: 700;}.rationale { font-size: 13px; color: var(--muted); line-height: 1.5; font-style: italic; margin-top: 4px; }.fallback-note { font-size: 11px; color: var(--muted); margin-top: 6px; }.find-btn { background: var(--coral) !important; border: none !important; font-weight: 600 !important; }.qs-btn {background: white !important;border: 1.5px solid #e5e0d8 !important;border-radius: 10px !important;color: var(--ink) !important;font-weight: 500 !important;font-size: 13px !important;transition: all 0.15s ease !important;}.qs-btn:hover {border-color: var(--ocean-mid) !important;background: #eef6f8 !important;}"""HEADER_HTML = """<div class="header-box"><h1>🌊 SurfMatch</h1><p>Tell us about yourself and we'll match you with 3 real boards from our catalog,plus one custom, AI-designed board shaped just for you.</p><div class="chips-row"><span class="stat-chip">150 boards</span><span class="stat-chip">15,000 rider profiles analyzed</span><span class="stat-chip">AI-powered</span></div></div>"""11 unmodified lines"""with gr.Blocks(title="SurfMatch", css=CSS, js=FORCE_LIGHT_JS) as demo:gr.HTML(HEADER_HTML)with gr.Row():with gr.Column(scale=2):gr.Markdown('<div class="quick-starters-label">Quick Starters</div>')with gr.Row():qs_buttons = [gr.Button(label, size="sm", elem_classes="qs-btn") for label in QUICK_STARTERS]height = gr.Slider(140, 210, value=175, step=1, label="Height (cm)")weight = gr.Slider(40, 130, value=72, step=1, label="Weight (kg)")skill = gr.Slider(1, 100, value=50, step=1, label="Skill level")goal = gr.Dropdown(list(GOAL_OPTIONS.keys()), value=list(GOAL_OPTIONS.keys())[0], label="Your goal")conditions = gr.Dropdown(CONDITIONS, value=CONDITIONS[0], label="Typical conditions")current_style = gr.Dropdown(CURRENT_STYLE, value=CURRENT_STYLE[0], label="Current board")submit = gr.Button("Find My Boards", elem_classes="find-btn")with gr.Column(scale=3):output = gr.HTML()submit.click(find_boards, inputs=[height, weight, skill, goal, conditions, current_style], outputs=output)for label, (h, w, s, g, c, cs) in QUICK_STARTERS.items():idx = list(QUICK_STARTERS.keys()).index(label)qs_buttons[idx].click(lambda h=h, w=w, s=s, g=g, c=c, cs=cs: (h, w, s, g, c, cs),outputs=[height, weight, skill, goal, conditions, current_style],).then(find_boards, inputs=[height, weight, skill, goal, conditions, current_style], outputs=output)demo.launch()19 unmodified lines202122232425262728293010 unmodified lines414243444546474849505152535447 unmodified lines1021031041051061071081094 unmodified lines11411511611711811912012112234 unmodified lines1571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871882 unmodified lines1911921931941951961971981992002012022032042052062072082092102112122132142152162178 unmodified lines2262272282292302312322332341 unmodified line236237238239240241242243244245246247116 unmodified lines3643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244255 unmodified lines43143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463511 unmodified lines64764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268319 unmodified linesCONDITIONS = ["small mushy beach breaks", "medium clean point breaks","powerful reef breaks", "big open-ocean swell"]NO_BOARD_YET = "I don't have a board yet"CURRENT_STYLE = [NO_BOARD_YET, "longboard cruiser", "all-around funboard", "fish / groveler","performance shortboard", "step-up / big-wave gun"]GOAL_OPTIONS = {"I'm brand new to surfing and want my first board": ("first_time_beginner", "get my very first surfboard and start learning to surf"),"Get more comfortable on the board I already ride": ("stay_and_improve", "get more comfortable and consistent on the board I already ride"),"Move toward something shorter and more maneuverable": ("transition_to_shortboard", "move from a longer, more stable board toward something shorter and more maneuverable"),"Move toward a longer, more stable board": ("transition_to_longboard", "move toward a longer, more stable board for easier paddling and glide"),10 unmodified lines"step-up / big-wave gun": "step-up gun",}def style_clause(current_style):"""A grammatical clause describing the rider's current board, handling the'no board yet' beginner case separately since it isn't a real board style."""if current_style == NO_BOARD_YET:return "doesn't have a board yet - this will be their first one"return f"currently rides a {STYLE_FOR_PROMPT.get(current_style, current_style)}"# Same skill -> experience-label ranges used to generate rider_profiles.csv in Part 1,# used here only to turn the UI's single skill slider into an "experience" word for the# Part 4 prompt, which expects one (the real notebook's riders already carry both fields).47 unmodified linesdef compute_style_fit(goal_key, skill_score, current_style):"""Same rule used to build style_fit_truth in Part 1 and to pick a category in Part 3/4."""if goal_key == "first_time_beginner":return "longboard cruiser" # the classic, most forgiving starting pointif goal_key == "transition_to_shortboard":return "performance shortboard" if skill_score >= 55 else "fish / groveler"if goal_key == "transition_to_longboard":4 unmodified linesreturn "performance shortboard" if skill_score >= 60 else "fish / groveler"if goal_key in ("want_easier_paddling", "want_more_stability"):return "longboard cruiser" if skill_score < 40 else "all-around funboard"# Fallback: stick with the rider's current style - unless they don't have one yet,# in which case NO_BOARD_YET isn't a real category, so default to the safest starter.return current_style if current_style != NO_BOARD_YET else "longboard cruiser"def pct(value, lo, hi):34 unmodified linesreturn pd.DataFrame(picked)def build_query_text(height_cm, weight_kg, skill_score, current_style, conditions, goal_text, extra_notes=""):"""Mirrors the phrasing of the real profile_text used to train/evaluate the embeddings,so a user's form inputs land in the same region of embedding space as real riders."""text = (f"I'm {height_cm}cm tall and {weight_kg}kg, with a skill level of {skill_score}/100. "f"I {style_clause(current_style)} and surf {conditions}, and I want to {goal_text}.")if extra_notes and extra_notes.strip():text += f" {extra_notes.strip()}"return text# App-only enhancement, layered on top of the notebook's evaluated category-first algorithm# (Part 3, cell ~ the recommend_boards definition): rather than hard-filtering to only the# rule-based target category, every board is scored, with a bonus for matching the target# category. Most results still come from that category (the bonus is large), but a board# from a neighboring category can occasionally surface if its fit/similarity is strong enough# - this is intentionally "sometimes", not a forced quota, per real user feedback that seeing# 3-4 near-identical boards felt repetitive. The notebook's own Part 3 evaluation (hit_rate,# diversity-ceiling stats in the README) was run against the strict same-category version and# is unaffected by this - it documents the core algorithm, this is a UX layer on top of it.CATEGORY_BONUS = 0.18def recommend_boards(height_cm, weight_kg, skill_score, current_style, conditions, goal_key, goal_text,extra_notes="", k=3):target_category = compute_style_fit(goal_key, skill_score, current_style)weight_pct = pct(weight_kg, W_LO, W_HI)2 unmodified linesvolume_need = 0.5 * weight_pct + 0.5 * forgiveness_pctlength_need = 0.5 * height_pct + 0.5 * forgiveness_pctcandidates = boards_df.copy()cand_embs = BOARD_EMBS[candidates.index.values]query_text = build_query_text(height_cm, weight_kg, skill_score, current_style, conditions,goal_text, extra_notes)query_emb = embed_model.encode([query_text], normalize_embeddings=True)[0]candidates["similarity"] = cand_embs @ query_emb# Physical-fit percentiles computed within each board's OWN category (not just the target# one), so boards from every category are on the same comparable 0-1 fit scale.vol_pct = candidates.groupby("category")["volume_l"].transform(within_category_pct)len_pct = candidates.groupby("category")["length_ft"].transform(within_category_pct)candidates["volume_score"] = 1 - (volume_need - vol_pct).abs()candidates["length_score"] = 1 - (length_need - len_pct).abs()candidates["physical_fit"] = 0.5 * candidates["volume_score"] + 0.5 * candidates["length_score"]candidates["category_match"] = (candidates["category"] == target_category).astype(float)candidates["combined_score"] = (0.5 * candidates["similarity"] + 0.5 * candidates["physical_fit"]+ CATEGORY_BONUS * candidates["category_match"])return target_category, pick_diverse(candidates, "combined_score", k=k)8 unmodified lines# the app usable on the ~10% of calls that don't parse.def build_custom_board_prompt(rider, target_category):"""Adapted from the project notebook's Part 4 (cell 127) - the exact prompt behind thedocumented 90% parse rate and the correlation numbers in the Space README, plus anoptional free-text line from the app's UI (not present in the notebook version)."""r = CATEGORY_RANGES.loc[target_category]weight_pct = pct(rider["weight_kg"], W_LO, W_HI)height_pct = pct(rider["height_cm"], H_LO, H_HI)1 unmodified linefacts = (f"Surfer facts - height {rider['height_cm']}cm, weight {rider['weight_kg']}kg, "f"{rider['experience']} (skill {rider['skill_score']}/100), {style_clause(rider['current_style'])}, "f"surfs {rider['conditions']}, wants to: {rider['goal_text']}. "f"Closest matching standard category: {target_category}.")if rider.get("extra_notes") and rider["extra_notes"].strip():facts += f" In their own words, they also said: \"{rider['extra_notes'].strip()}\""percentile_hint = (f"Relative to other surfers in our data, this person is heavier than about {weight_pct:.0%} "f"of them, taller than about {height_pct:.0%} of them, and more skilled than about "116 unmodified lines# ββ UI rendering ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef score_badge(display_pct):"""display_pct is already rescaled (see rescale_display_scores) to a range calibratedagainst the boards actually being shown, so it always reads as a meaningful comparisonrather than an intimidatingly low absolute number. Rendered as a rubber-stamp badge -a rotated circle with the percentage and a short tier word (no bare unqualified lownumber, and no repeated "Match" filling up the small stamp)."""if display_pct >= 85:cls, label = "stamp-great", "GREAT"elif display_pct >= 70:cls, label = "stamp-good", "GOOD"else:cls, label = "stamp-solid", "SOLID"return f'<div class="board-stamp {cls}">{display_pct:.0f}%<br>{label}</div>'def rescale_display_scores(scores):"""Rescales a set of raw combined_score values (which have no inherent 0-100 'quality'meaning on their own) into a 60-98% band relative to the boards actually being shown,so the badge always communicates 'how this one compares to your other results' ratherthan an absolute score that can look unflatteringly low for an otherwise solid match."""lo, hi = scores.min(), scores.max()if hi == lo:return pd.Series(82.0, index=scores.index)return 60 + 38 * (scores - lo) / (hi - lo)def clean_model_name(brand, model_name):"""The catalog's model_name already includes the brand (e.g. 'Al Merrick Puddle Jumper'for brand 'Al Merrick'), so showing both verbatim duplicated the brand - this strips it."""if model_name.lower().startswith(brand.lower()):return model_name[len(brand):].strip()return model_namedef board_card(board, rank, display_pct, target_category):"""A single die-cut, sticker-shaped board card (the "Board Rack" surf-shop poster look).The category line is always shown, since it's the clearest way to flag the occasionalcross-category pick the recommender now allows (see CATEGORY_BONUS above) - when itdiffers from the search's own target category, we mark it "outside category"."""category_label = board['category'].title()if board['category'] != target_category:category_label += ' <span class="outside-tag">· outside category</span>'return f"""<div class="board-card">{score_badge(display_pct)}<div class="board-card-rank">#{rank}</div><div class="board-card-brand">{board['brand']}</div><div class="board-card-title">{clean_model_name(board['brand'], board['model_name'])}</div><div class="board-card-category">{category_label}</div><div class="board-card-spec">{board['length_ft']}ft · {board['width_in']}in · {board['thickness_in']}in · {board['volume_l']}L</div><div class="board-card-tags"><span class="tag-chip">{board['tail']}</span><span class="tag-chip">{board['fins']}</span><span class="tag-chip">{board['construction']}</span></div></div>"""5 unmodified linesnote = f'<div class="rationale"><strong>Why:</strong> {spec.get("sizing_reasoning", "")}</div>'return f"""<div class="board-card custom-card"><div class="board-stamp stamp-ai">AI<br>MADE</div><div class="board-card-brand">AI Generated</div><div class="board-card-title">Your Custom Board</div><div class="board-card-category">{target_category.title()}</div><div class="board-card-spec">{spec['length_ft']}ft · {spec['width_in']}in · {spec['thickness_in']}in · {spec['volume_l']}L</div><div class="board-card-tags"><span class="tag-chip">{spec['tail']}</span><span class="tag-chip">{spec['fins']}</span><span class="tag-chip">{spec['construction']}</span></div><div class="rationale">{spec['rationale']}</div>{note}</div>"""def find_boards(height_cm, weight_kg, skill_score, goal_label, conditions, current_style, extra_notes=""):goal_key, goal_text = GOAL_OPTIONS[goal_label]target_category, recs = recommend_boards(height_cm, weight_kg, skill_score, current_style, conditions, goal_key, goal_text, extra_notes,)rider = {"height_cm": height_cm, "weight_kg": weight_kg, "skill_score": skill_score,"experience": experience_for_skill(skill_score), "current_style": current_style,"conditions": conditions, "goal_text": goal_text, "extra_notes": extra_notes,}custom = generate_custom_board(rider, target_category)display_pcts = rescale_display_scores(recs["combined_score"])cards_html = '<div class="results-head">RECOMMENDED: ' + target_category.upper() + '</div>'cards_html += '<div class="cards-grid">'for i, ((_, board), display_pct) in enumerate(zip(recs.iterrows(), display_pcts), 1):cards_html += board_card(board, i, display_pct, target_category)cards_html += custom_card(custom, target_category)cards_html += '</div>'return cards_htmlQUICK_STARTERS = {"Never surfed before": (163, 65, 5,"I'm brand new to surfing and want my first board", "small mushy beach breaks", NO_BOARD_YET,"I'm a little nervous about duck-diving under waves and want something easy and forgiving."),"Beginner wanting stability": (168, 72, 15,"Get more stability and easier paddling", "small mushy beach breaks", "performance shortboard", ""),"Advanced wanting speed": (178, 75, 78,"Get a faster, more responsive board for sharper turns", "powerful reef breaks", "all-around funboard", ""),"Longboarder chasing big waves": (182, 85, 60,"Ride a board that can handle bigger, more powerful waves", "big open-ocean swell", "longboard cruiser", ""),}CSS = """@import url('https://fonts.googleapis.com/css2?family=Alfa+Slab+One&family=Barlow:wght@400;500;600;700&display=swap');:root {--navy: #0d2b36;--blue: #134a5e;--yellow: #f2b705;--coral: #ff6a3d;--cream: #fdf6e3;--rust: #c1440e;--page-bg: #f3ead9;--muted: #5a6f77;}.gradio-container { background: var(--page-bg) !important; font-family: 'Barlow', sans-serif !important; }.gradio-container * { font-family: 'Barlow', sans-serif; }/* ββ The whole app sits on one big screen-printed poster sheet ββββββββββββββ */.poster-shell {position: relative;overflow: hidden;background: var(--blue);border-radius: 20px;padding: 28px 26px 34px;margin-bottom: 4px;}/* !important on position/z-index guarantees these stay absolute + behind the realcontent no matter what a later broad selector (like the one below, which liftsevery other direct child above them) does - Chromium paints a plain negativez-index behind the shell's own opaque background, which hid these entirely, sothey're pinned to z-index:0 while real content is lifted to z-index:1 instead. */.blob-1, .blob-2 { position: absolute !important; z-index: 0 !important; border-radius: 50%; pointer-events: none; }.blob-1 { width: 300px; height: 300px; background: var(--yellow); top: -140px; right: -100px; opacity: 0.9; }.blob-2 { width: 200px; height: 200px; background: var(--coral); bottom: -110px; left: -80px; opacity: 0.85; }.poster-shell > * { position: relative; z-index: 1; }.brand-row { display: flex; justify-content: space-between; align-items: flex-end; gap: 20px; flex-wrap: wrap; margin-bottom: 18px; }.brand-word {font-family: 'Alfa Slab One', cursive; font-size: 34px; color: #fff;text-shadow: 3px 3px 0 var(--navy); letter-spacing: 0.01em; line-height: 1;}.brand-tag {background: #fff; color: var(--navy); font-weight: 600; font-size: 13px;padding: 10px 14px; border-radius: 10px; border: 2.5px solid var(--navy);max-width: 340px; line-height: 1.4;}.stat-pills { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 14px; }.stat-chip {background: rgba(255,255,255,0.18); color: #fff; border: 1.5px solid rgba(255,255,255,0.5);border-radius: 20px; padding: 4px 12px; font-size: 11.5px; font-weight: 600;}.qs-row { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 4px; }.qs-btn {background: #fff !important;border: 2.5px solid var(--navy) !important;border-radius: 20px !important;color: var(--navy) !important;font-weight: 700 !important;font-size: 12.5px !important;box-shadow: none !important;transition: transform 0.1s ease, background 0.1s ease !important;}.qs-btn:hover { background: var(--yellow) !important; transform: translateY(-1px); }/* ββ Input panel: a thick-bordered card floating on the poster ββββββββββββββ */.input-panel { background: #fff !important; border: 2.5px solid var(--navy) !important;border-radius: 14px !important; padding: 16px !important; }.input-panel label span { color: var(--navy) !important; font-weight: 700 !important;font-size: 12px !important; text-transform: uppercase; letter-spacing: 0.04em; }.input-panel input, .input-panel textarea, .input-panel select {font-family: 'Barlow', sans-serif !important; color: var(--navy) !important;}.input-panel input[type="range"] { accent-color: var(--coral) !important; }.find-btn {background: var(--coral) !important; border: 2.5px solid var(--navy) !important;border-radius: 12px !important; color: #fff !important; font-weight: 700 !important;font-size: 15px !important; text-transform: uppercase; letter-spacing: 0.03em;box-shadow: 4px 4px 0 rgba(13,43,54,0.5) !important;}.find-btn:hover { transform: translate(1px, 1px); box-shadow: 3px 3px 0 rgba(13,43,54,0.5) !important; }/* ββ Results ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */.results-head {font-family: 'Alfa Slab One', cursive; font-size: 16px; color: #fff;text-shadow: 2px 2px 0 var(--navy); margin-bottom: 14px;}.cards-grid {display: grid;grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));gap: 18px;}/* Die-cut, sticker-shaped board card */.board-card {background: var(--cream);border: 3px solid var(--navy);border-radius: 4px 16px 4px 16px;padding: 16px;position: relative;box-shadow: 5px 5px 0 rgba(13,43,54,0.35);}.board-card-rank { position: absolute; top: 10px; left: 14px; font-family: 'Alfa Slab One', cursive;font-size: 12px; color: var(--muted); }.board-stamp {position: absolute; top: -16px; right: 10px;border: 2.5px solid var(--navy); border-radius: 50%;width: 54px; height: 54px; display: flex; align-items: center; justify-content: center;flex-direction: column; text-align: center; line-height: 1.15;font-weight: 700; font-size: 11px; color: #fff; transform: rotate(8deg);}.stamp-great { background: #1a7f37; }.stamp-good { background: var(--coral); }.stamp-solid { background: #b06e00; }.stamp-ai { background: var(--navy); }.board-card-brand { color: var(--rust); font-size: 11px; font-weight: 700; text-transform: uppercase;letter-spacing: 0.05em; margin: 16px 0 2px; }.board-card-title { font-family: 'Alfa Slab One', cursive; font-size: 17px; color: var(--navy);margin: 0 0 8px; line-height: 1.15; }.board-card-category { font-size: 11.5px; font-weight: 700; color: var(--muted); text-transform: uppercase;letter-spacing: 0.03em; margin-bottom: 9px; }.outside-tag { color: var(--rust); font-weight: 600; text-transform: none; letter-spacing: 0; }.board-card-spec { font-weight: 600; font-size: 12.5px; color: #3d5158; margin-bottom: 10px; }.board-card-tags { display: flex; flex-wrap: wrap; gap: 5px; margin-bottom: 4px; }.tag-chip { background: var(--navy); color: #fff; font-size: 10.5px; font-weight: 600; padding: 3px 10px; border-radius: 20px; }.custom-card { background: #fff; border-style: dashed; }.rationale { font-size: 12px; color: var(--muted); line-height: 1.5; font-weight: 500; margin-top: 8px; }.fallback-note { font-size: 11px; color: var(--muted); margin-top: 6px; }"""BLOBS_HTML = '<div class="blob-1"></div><div class="blob-2"></div>'HEADER_HTML = """<div class="brand-row"><div class="brand-word">SurfMatch</div><div class="brand-tag">Tell us about yourself and we'll match you with 3 real boards fromour catalog, plus one custom, AI-designed board shaped just for you.</div></div><div class="stat-pills"><span class="stat-chip">150 boards</span><span class="stat-chip">15,000 rider profiles analyzed</span><span class="stat-chip">AI-powered</span></div>"""11 unmodified lines"""with gr.Blocks(title="SurfMatch", css=CSS, js=FORCE_LIGHT_JS) as demo:with gr.Column(elem_classes="poster-shell"):gr.HTML(BLOBS_HTML)gr.HTML(HEADER_HTML)with gr.Row(elem_classes="qs-row"):qs_buttons = [gr.Button(label, size="sm", elem_classes="qs-btn") for label in QUICK_STARTERS]with gr.Row():with gr.Column(scale=2, elem_classes="input-panel"):height = gr.Slider(140, 210, value=175, step=1, label="Height (cm)")weight = gr.Slider(40, 130, value=72, step=1, label="Weight (kg)")skill = gr.Slider(1, 100, value=50, step=1, label="Skill level")goal = gr.Dropdown(list(GOAL_OPTIONS.keys()), value=list(GOAL_OPTIONS.keys())[0], label="Your goal")conditions = gr.Dropdown(CONDITIONS, value=CONDITIONS[0], label="Typical conditions")current_style = gr.Dropdown(CURRENT_STYLE, value=CURRENT_STYLE[0], label="Current board")extra_notes = gr.Textbox(label="Anything else about you or the board you're picturing? (optional)",placeholder="e.g. I want something colorful, I'm nervous about duck-diving, ""I want a board that turns heads...",lines=2,)submit = gr.Button("Find My Boards", elem_classes="find-btn")with gr.Column(scale=3):output = gr.HTML()all_inputs = [height, weight, skill, goal, conditions, current_style, extra_notes]submit.click(find_boards, inputs=all_inputs, outputs=output)for label, (h, w, s, g, c, cs, notes) in QUICK_STARTERS.items():idx = list(QUICK_STARTERS.keys()).index(label)qs_buttons[idx].click(lambda h=h, w=w, s=s, g=g, c=c, cs=cs, notes=notes: (h, w, s, g, c, cs, notes),outputs=all_inputs,).then(find_boards, inputs=all_inputs, outputs=output)demo.launch()
app.py+290-184