DetectiveShadow commited on
Commit
b44acec
ยท
verified ยท
1 Parent(s): 42b4d11

Update app.py

Browse files

Updated so it should add a text game

Files changed (1) hide show
  1. app.py +134 -74
app.py CHANGED
@@ -1,87 +1,147 @@
1
  import gradio as gr
 
2
  import pandas as pd
3
- from datasets import load_dataset
4
- from sklearn.model_selection import train_test_split
5
- from sklearn.ensemble import RandomForestClassifier
6
  import joblib
7
- import os
8
-
9
- MODEL_PATH = "model.pkl"
10
-
11
- def train_model():
12
- # Load dataset from Hugging Face Hub
13
- dataset = load_dataset("DetectiveShadow/entrepreneurial_readiness_data")
14
- df = pd.DataFrame(dataset["train"]) # assuming single split
15
-
16
- # Features & target
17
- X = df.drop(columns=["readiness_score", "readiness_level"])
18
- X = pd.get_dummies(X, columns=["confidence"]) # one-hot encode categorical
19
- y = df["readiness_level"]
20
-
21
- # Train/test split
22
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
23
-
24
- # Train model
25
- model = RandomForestClassifier(n_estimators=100, random_state=42)
26
- model.fit(X_train, y_train)
27
-
28
- # Save model for reuse
29
- joblib.dump(model, MODEL_PATH)
30
- return model
31
-
32
- # Load or train model
33
- if os.path.exists(MODEL_PATH):
34
- model = joblib.load(MODEL_PATH)
35
- else:
36
- model = train_model()
37
-
38
- def predict(savings, income, bills, entertainment, assets, sales_skills, confidence, dependents, age, idea_level, entrepreneurial_experience):
39
- # Build input dataframe
40
- df = pd.DataFrame([[
41
- savings, income, bills, entertainment, assets,
42
- sales_skills, confidence, dependents, age,
43
- idea_level, entrepreneurial_experience
 
 
 
 
 
 
 
 
44
  ]], columns=[
45
- "savings", "income", "bills", "entertainment", "assets",
46
- "sales_skills", "confidence", "dependents", "age",
47
- "idea_level", "entrepreneurial_experience"
48
  ])
 
 
 
 
 
 
 
 
49
 
50
- # One-hot encode confidence to match training
51
- df = pd.get_dummies(df)
52
- for col in ["confidence_High", "confidence_Medium", "confidence_Low"]:
53
- if col not in df.columns:
54
- df[col] = 0
 
 
 
 
55
 
56
- # Predict
57
- prediction = model.predict(df)[0]
58
- return prediction
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
  with gr.Blocks() as demo:
61
- gr.Markdown("# ๐Ÿš€ Entrepreneurial Readiness Predictor (ML Model)")
 
 
 
 
 
 
62
 
63
  with gr.Row():
64
- with gr.Column():
65
- savings = gr.Number(label="๐Ÿ’ฐ Savings Amount ($)")
66
- income = gr.Number(label="๐Ÿ’ต Monthly Income ($)")
67
- bills = gr.Number(label="๐Ÿ“‘ Monthly Bills ($)")
68
- entertainment = gr.Number(label="๐ŸŽ‰ Monthly Entertainment ($)")
69
- assets = gr.Number(label="๐Ÿ  Assets ($)")
70
- sales_skills = gr.Slider(1, 5, step=1, label="๐Ÿ—ฃ๏ธ Sales Skills (1โ€“5)")
71
- confidence = gr.Dropdown(["Low", "Medium", "High"], label="๐Ÿ’ก Confidence")
72
- dependents = gr.Slider(0, 6, step=1, label="๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง Dependents")
73
- age = gr.Number(label="๐ŸŽ‚ Age")
74
- idea_level = gr.Slider(1, 10, step=1, label="๐Ÿ’ก Business Idea Level (1โ€“10)")
75
- entrepreneurial_experience = gr.Slider(0, 10, step=1, label="๐Ÿ“ˆ Entrepreneurial Experience (years)")
76
- btn = gr.Button("๐Ÿ”ฎ Predict")
77
-
78
- with gr.Column():
79
- output = gr.Label(label="Prediction (Readiness Level)")
80
-
81
- btn.click(
82
- predict,
83
- inputs=[savings, income, bills, entertainment, assets, sales_skills, confidence, dependents, age, idea_level, entrepreneurial_experience],
84
- outputs=output
85
- )
86
 
87
  demo.launch()
 
1
  import gradio as gr
2
+ import random, json, os
3
  import pandas as pd
 
 
 
4
  import joblib
5
+ from huggingface_hub import hf_hub_download
6
+
7
+ REPO_ID = "DetectiveShadow/Entrepreneurial_predictor"
8
+
9
+ # --- Try loading trained regressor + feature columns from Hub; fall back to heuristic if not available ---
10
+ regressor = None
11
+ FEATURE_COLUMNS = None
12
+ try:
13
+ reg_path = hf_hub_download(REPO_ID, "regressor.pkl")
14
+ feat_path = hf_hub_download(REPO_ID, "feature_columns.json")
15
+ regressor = joblib.load(reg_path)
16
+ with open(feat_path, "r") as f:
17
+ FEATURE_COLUMNS = json.load(f)
18
+ except Exception as e:
19
+ print("โš ๏ธ Could not load regressor from Hub; will use heuristic. Error:", e)
20
+
21
+ def confidence_to_bonus(conf):
22
+ return {"Low": 0, "Medium": 5, "High": 10}.get(conf, 5)
23
+
24
+ def heuristic_score(profile):
25
+ # Matches earlier heuristic logic
26
+ disposable = profile["income"] - profile["bills"] - profile["entertainment"]
27
+ score = (
28
+ (profile["savings"] + profile["assets"]) / 1000
29
+ + disposable / 500
30
+ + profile["sales_skills"] * 2
31
+ + profile["idea_level"] * 3
32
+ + profile["entrepreneurial_experience"] * 2
33
+ + confidence_to_bonus(profile["confidence"])
34
+ - profile["dependents"]
35
+ + (40 - abs(35 - profile["age"])) / 5
36
+ )
37
+ return max(0, min(100, score))
38
+
39
+ def level_from_score(score):
40
+ if score < 30: return "Low"
41
+ if score < 60: return "Moderate"
42
+ return "High"
43
+
44
+ def build_features_df(profile):
45
+ # Build a one-row DataFrame in the same format as training
46
+ base = pd.DataFrame([[
47
+ profile["savings"], profile["income"], profile["bills"], profile["entertainment"],
48
+ profile["assets"], profile["sales_skills"], profile["confidence"], profile["dependents"],
49
+ profile["age"], profile["idea_level"], profile["entrepreneurial_experience"]
50
  ]], columns=[
51
+ "savings","income","bills","entertainment","assets",
52
+ "sales_skills","confidence","dependents","age",
53
+ "idea_level","entrepreneurial_experience"
54
  ])
55
+ df = pd.get_dummies(base, columns=["confidence"])
56
+ if FEATURE_COLUMNS is not None:
57
+ # ensure all training cols present
58
+ for col in FEATURE_COLUMNS:
59
+ if col not in df.columns:
60
+ df[col] = 0
61
+ df = df[FEATURE_COLUMNS]
62
+ return df
63
 
64
+ def compute_score(profile):
65
+ if regressor is not None and FEATURE_COLUMNS is not None:
66
+ X = build_features_df(profile)
67
+ try:
68
+ pred = float(regressor.predict(X)[0])
69
+ return max(0, min(100, pred))
70
+ except Exception as e:
71
+ print("โš ๏ธ Regressor prediction failed, fallback to heuristic:", e)
72
+ return heuristic_score(profile)
73
 
74
+ # --- Scenario generator ---
75
+ def random_profile():
76
+ return {
77
+ "savings": random.randint(0, 20000),
78
+ "income": random.randint(1500, 10000),
79
+ "bills": random.randint(500, 8000),
80
+ "entertainment": random.randint(0, 1500),
81
+ "assets": random.randint(0, 60000),
82
+ "sales_skills": random.randint(1, 5),
83
+ "confidence": random.choice(["Low", "Medium", "High"]),
84
+ "dependents": random.randint(0, 6),
85
+ "age": random.randint(18, 64),
86
+ "idea_level": random.randint(1, 10),
87
+ "entrepreneurial_experience": random.randint(0, 10),
88
+ }
89
+
90
+ def profile_to_story(p):
91
+ # A friendly, human-readable scenario
92
+ parts = []
93
+ parts.append(f"{p['age']}-year-old aspiring founder with {p['dependents']} dependents.")
94
+ parts.append(f"Savings of ${p['savings']:,} and assets totaling ${p['assets']:,}.")
95
+ parts.append(f"Monthly income ${p['income']:,}, bills ${p['bills']:,}, entertainment ${p['entertainment']:,}.")
96
+ parts.append(f"Sales skills rated {p['sales_skills']}/5 and confidence **{p['confidence']}**.")
97
+ parts.append(f"Business idea quality {p['idea_level']}/10 and entrepreneurial experience {p['entrepreneurial_experience']} year(s).")
98
+ return " ".join(parts)
99
+
100
+ # --- Gradio app logic ---
101
+ def new_scenario():
102
+ p = random_profile()
103
+ story = profile_to_story(p)
104
+ true_score = round(compute_score(p), 2)
105
+ true_level = level_from_score(true_score)
106
+ # We keep true values hidden in state; return the story, reset guess, and stash state
107
+ return story, 50, {"profile": p, "score": true_score, "level": true_level}
108
+
109
+ def check_guess(guess, state):
110
+ if not state or "score" not in state:
111
+ return {"error": "No scenario generated yet. Click '๐ŸŽฒ New Scenario' first."}
112
+ true_score = state["score"]
113
+ true_level = state["level"]
114
+ delta = round(abs(true_score - float(guess)), 2)
115
+ verdict = "โœ… Great guess!" if delta <= 5 else ("๐ŸŸก Close!" if delta <= 10 else "โŒ Not quite.")
116
+ return {
117
+ "Your Guess": float(guess),
118
+ "Actual Score": true_score,
119
+ "Readiness Level": true_level,
120
+ "Off by": delta,
121
+ "Verdict": verdict
122
+ }
123
 
124
  with gr.Blocks() as demo:
125
+ gr.Markdown("# ๐ŸŽฏ Guess the Entrepreneurial Readiness")
126
+ gr.Markdown(
127
+ "Iโ€™ll generate a random founder profile. **You guess the readiness score (0โ€“100)**, "
128
+ "then weโ€™ll reveal the actual score and level."
129
+ )
130
+
131
+ state = gr.State() # holds {"profile": ..., "score": ..., "level": ...}
132
 
133
  with gr.Row():
134
+ with gr.Column(scale=3):
135
+ scenario_md = gr.Markdown("Click **New Scenario** to start.")
136
+ with gr.Row():
137
+ new_btn = gr.Button("๐ŸŽฒ New Scenario", variant="primary")
138
+ guess = gr.Slider(0, 100, value=50, step=1, label="Your Guess (0โ€“100)")
139
+ reveal_btn = gr.Button("๐Ÿ” Check My Guess")
140
+ with gr.Column(scale=2):
141
+ result = gr.JSON(label="Result")
142
+
143
+ # Wire events
144
+ new_btn.click(fn=new_scenario, inputs=None, outputs=[scenario_md, guess, state])
145
+ reveal_btn.click(fn=check_guess, inputs=[guess, state], outputs=result)
 
 
 
 
 
 
 
 
 
 
146
 
147
  demo.launch()