DetectiveShadow's picture
Update app.py
b44acec verified
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()