Update app.py
Browse filesUpdated so it should add a text game
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687import gradio as grimport pandas as pdfrom datasets import load_datasetfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestClassifierimport joblibimport osMODEL_PATH = "model.pkl"def train_model():# Load dataset from Hugging Face Hubdataset = load_dataset("DetectiveShadow/entrepreneurial_readiness_data")df = pd.DataFrame(dataset["train"]) # assuming single split# Features & targetX = df.drop(columns=["readiness_score", "readiness_level"])X = pd.get_dummies(X, columns=["confidence"]) # one-hot encode categoricaly = df["readiness_level"]# Train/test splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# Train modelmodel = RandomForestClassifier(n_estimators=100, random_state=42)model.fit(X_train, y_train)# Save model for reusejoblib.dump(model, MODEL_PATH)return model# Load or train modelif os.path.exists(MODEL_PATH):model = joblib.load(MODEL_PATH)else:model = train_model()def predict(savings, income, bills, entertainment, assets, sales_skills, confidence, dependents, age, idea_level, entrepreneurial_experience):# Build input dataframedf = pd.DataFrame([[savings, income, bills, entertainment, assets,sales_skills, confidence, dependents, age,idea_level, entrepreneurial_experience]], columns=["savings", "income", "bills", "entertainment", "assets","sales_skills", "confidence", "dependents", "age","idea_level", "entrepreneurial_experience"])# One-hot encode confidence to match trainingdf = pd.get_dummies(df)for col in ["confidence_High", "confidence_Medium", "confidence_Low"]:if col not in df.columns:df[col] = 0# Predictprediction = model.predict(df)[0]return predictionwith gr.Blocks() as demo:gr.Markdown("# 🚀 Entrepreneurial Readiness Predictor (ML Model)")with gr.Row():with gr.Column():savings = gr.Number(label="💰 Savings Amount ($)")income = gr.Number(label="💵 Monthly Income ($)")bills = gr.Number(label="📑 Monthly Bills ($)")entertainment = gr.Number(label="🎉 Monthly Entertainment ($)")assets = gr.Number(label="🏠 Assets ($)")sales_skills = gr.Slider(1, 5, step=1, label="🗣️ Sales Skills (1–5)")confidence = gr.Dropdown(["Low", "Medium", "High"], label="💡 Confidence")dependents = gr.Slider(0, 6, step=1, label="👨👩👧 Dependents")age = gr.Number(label="🎂 Age")idea_level = gr.Slider(1, 10, step=1, label="💡 Business Idea Level (1–10)")entrepreneurial_experience = gr.Slider(0, 10, step=1, label="📈 Entrepreneurial Experience (years)")btn = gr.Button("🔮 Predict")with gr.Column():output = gr.Label(label="Prediction (Readiness Level)")btn.click(predict,inputs=[savings, income, bills, entertainment, assets, sales_skills, confidence, dependents, age, idea_level, entrepreneurial_experience],outputs=output)demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147import gradio as grimport random, json, osimport pandas as pdimport joblibfrom huggingface_hub import hf_hub_downloadREPO_ID = "DetectiveShadow/Entrepreneurial_predictor"# --- Try loading trained regressor + feature columns from Hub; fall back to heuristic if not available ---regressor = NoneFEATURE_COLUMNS = Nonetry: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 logicdisposable = 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 trainingbase = 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 presentfor col in FEATURE_COLUMNS:if col not in df.columns:df[col] = 0df = df[FEATURE_COLUMNS]return dfdef 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 scenarioparts = []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 statereturn 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 eventsnew_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()
app.py+134-74