File size: 5,861 Bytes
6e9b35b
b44acec
f58f188
 
b44acec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f58f188
b44acec
 
 
f58f188
b44acec
 
 
 
 
 
 
 
f58f188
b44acec
 
 
 
 
 
 
 
 
f58f188
b44acec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e9b35b
 
b44acec
 
 
 
 
 
 
f58f188
6e9b35b
b44acec
 
 
 
 
 
 
 
 
 
 
 
6e9b35b
 
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
import gradio as gr
import random, json, os
import pandas as pd
import joblib
from huggingface_hub import hf_hub_download

REPO_ID = "DetectiveShadow/Entrepreneurial_predictor"

# --- Try loading trained regressor + feature columns from Hub; fall back to heuristic if not available ---
regressor = None
FEATURE_COLUMNS = None
try:
    reg_path  = hf_hub_download(REPO_ID, "regressor.pkl")
    feat_path = hf_hub_download(REPO_ID, "feature_columns.json")
    regressor = joblib.load(reg_path)
    with open(feat_path, "r") as f:
        FEATURE_COLUMNS = json.load(f)
except Exception as e:
    print("⚠️ Could not load regressor from Hub; will use heuristic. Error:", e)

def confidence_to_bonus(conf):
    return {"Low": 0, "Medium": 5, "High": 10}.get(conf, 5)

def heuristic_score(profile):
    # Matches earlier heuristic logic
    disposable = profile["income"] - profile["bills"] - profile["entertainment"]
    score = (
        (profile["savings"] + profile["assets"]) / 1000
        + disposable / 500
        + profile["sales_skills"] * 2
        + profile["idea_level"] * 3
        + profile["entrepreneurial_experience"] * 2
        + confidence_to_bonus(profile["confidence"])
        - profile["dependents"]
        + (40 - abs(35 - profile["age"])) / 5
    )
    return max(0, min(100, score))

def level_from_score(score):
    if score < 30: return "Low"
    if score < 60: return "Moderate"
    return "High"

def build_features_df(profile):
    # Build a one-row DataFrame in the same format as training
    base = pd.DataFrame([[
        profile["savings"], profile["income"], profile["bills"], profile["entertainment"],
        profile["assets"], profile["sales_skills"], profile["confidence"], profile["dependents"],
        profile["age"], profile["idea_level"], profile["entrepreneurial_experience"]
    ]], columns=[
        "savings","income","bills","entertainment","assets",
        "sales_skills","confidence","dependents","age",
        "idea_level","entrepreneurial_experience"
    ])
    df = pd.get_dummies(base, columns=["confidence"])
    if FEATURE_COLUMNS is not None:
        # ensure all training cols present
        for col in FEATURE_COLUMNS:
            if col not in df.columns:
                df[col] = 0
        df = df[FEATURE_COLUMNS]
    return df

def compute_score(profile):
    if regressor is not None and FEATURE_COLUMNS is not None:
        X = build_features_df(profile)
        try:
            pred = float(regressor.predict(X)[0])
            return max(0, min(100, pred))
        except Exception as e:
            print("⚠️ Regressor prediction failed, fallback to heuristic:", e)
    return heuristic_score(profile)

# --- Scenario generator ---
def random_profile():
    return {
        "savings": random.randint(0, 20000),
        "income": random.randint(1500, 10000),
        "bills": random.randint(500, 8000),
        "entertainment": random.randint(0, 1500),
        "assets": random.randint(0, 60000),
        "sales_skills": random.randint(1, 5),
        "confidence": random.choice(["Low", "Medium", "High"]),
        "dependents": random.randint(0, 6),
        "age": random.randint(18, 64),
        "idea_level": random.randint(1, 10),
        "entrepreneurial_experience": random.randint(0, 10),
    }

def profile_to_story(p):
    # A friendly, human-readable scenario
    parts = []
    parts.append(f"{p['age']}-year-old aspiring founder with {p['dependents']} dependents.")
    parts.append(f"Savings of ${p['savings']:,} and assets totaling ${p['assets']:,}.")
    parts.append(f"Monthly income ${p['income']:,}, bills ${p['bills']:,}, entertainment ${p['entertainment']:,}.")
    parts.append(f"Sales skills rated {p['sales_skills']}/5 and confidence **{p['confidence']}**.")
    parts.append(f"Business idea quality {p['idea_level']}/10 and entrepreneurial experience {p['entrepreneurial_experience']} year(s).")
    return " ".join(parts)

# --- Gradio app logic ---
def new_scenario():
    p = random_profile()
    story = profile_to_story(p)
    true_score = round(compute_score(p), 2)
    true_level = level_from_score(true_score)
    # We keep true values hidden in state; return the story, reset guess, and stash state
    return story, 50, {"profile": p, "score": true_score, "level": true_level}

def check_guess(guess, state):
    if not state or "score" not in state:
        return {"error": "No scenario generated yet. Click '🎲 New Scenario' first."}
    true_score = state["score"]
    true_level = state["level"]
    delta = round(abs(true_score - float(guess)), 2)
    verdict = "✅ Great guess!" if delta <= 5 else ("🟡 Close!" if delta <= 10 else "❌ Not quite.")
    return {
        "Your Guess": float(guess),
        "Actual Score": true_score,
        "Readiness Level": true_level,
        "Off by": delta,
        "Verdict": verdict
    }

with gr.Blocks() as demo:
    gr.Markdown("# 🎯 Guess the Entrepreneurial Readiness")
    gr.Markdown(
        "I’ll generate a random founder profile. **You guess the readiness score (0–100)**, "
        "then we’ll reveal the actual score and level."
    )

    state = gr.State()  # holds {"profile": ..., "score": ..., "level": ...}

    with gr.Row():
        with gr.Column(scale=3):
            scenario_md = gr.Markdown("Click **New Scenario** to start.")
            with gr.Row():
                new_btn = gr.Button("🎲 New Scenario", variant="primary")
                guess = gr.Slider(0, 100, value=50, step=1, label="Your Guess (0–100)")
                reveal_btn = gr.Button("🔍 Check My Guess")
        with gr.Column(scale=2):
            result = gr.JSON(label="Result")

    # Wire events
    new_btn.click(fn=new_scenario, inputs=None, outputs=[scenario_md, guess, state])
    reveal_btn.click(fn=check_guess, inputs=[guess, state], outputs=result)

demo.launch()