Spaces:
Running
Running
File size: 12,169 Bytes
e020bec c26c1e6 767c971 e020bec 767c971 c26c1e6 e020bec c26c1e6 e020bec c26c1e6 e020bec c26c1e6 e020bec c26c1e6 e020bec c26c1e6 e020bec c26c1e6 e020bec c26c1e6 e020bec c26c1e6 e020bec c26c1e6 e020bec c26c1e6 e020bec c26c1e6 e020bec c26c1e6 e020bec c26c1e6 e020bec c26c1e6 |
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 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 |
from datetime import datetime
from time import sleep
from typing import Dict, List, Tuple
from openai import OpenAI
import gradio as gr
import pandas as pd
import numpy as np
import dotenv
import json
import os
dotenv.load_dotenv()
openai = OpenAI(
base_url="https://openrouter.ai/api/v1", api_key=os.environ.get("API_KEY")
)
MBTI_TYPES = [
"ISTJ",
"ISFJ",
"INFJ",
"INTJ",
"ISTP",
"ISFP",
"INFP",
"INTP",
"ESTP",
"ESFP",
"ENFP",
"ENTP",
"ESTJ",
"ESFJ",
"ENFJ",
"ENTJ",
]
class User:
def __init__(self, username: str, name: str):
self.username = username
self.name = name
self.scores_history: List[Dict] = []
self.recommendations_history: List[Dict] = []
def add_scores(self, scores: "UTBKScores", mbti: str):
score_entry = {
"timestamp": datetime.now().isoformat(),
"scores": scores.__dict__,
"mbti": mbti,
}
self.scores_history.append(score_entry)
def add_recommendations(self, recommendations: pd.DataFrame):
rec_entry = {
"timestamp": datetime.now().isoformat(),
"recommendations": recommendations.to_dict("records"),
}
self.recommendations_history.append(rec_entry)
class UserManager:
def __init__(self):
self.users: Dict[str, User] = {}
def get_or_create_user(self, oauth_profile: gr.OAuthProfile) -> User:
if oauth_profile.username not in self.users:
self.users[oauth_profile.username] = User(
username=oauth_profile.username, name=oauth_profile.name
)
return self.users[oauth_profile.username]
def save_user_interaction(
self,
oauth_profile: gr.OAuthProfile,
scores: "UTBKScores",
mbti: str,
recommendations: pd.DataFrame,
):
user = self.get_or_create_user(oauth_profile)
user.add_scores(scores, mbti)
user.add_recommendations(recommendations)
class UTBKScores:
def __init__(self, scores_dict: Dict):
self.penalaran_umum = scores_dict["penalaran_umum"]
self.pengetahuan_umum = scores_dict["pengetahuan_umum"]
self.pemahaman_bacaan = scores_dict["pemahaman_bacaan"]
self.pengetahuan_kuantitatif = scores_dict["pengetahuan_kuantitatif"]
self.literasi_indonesia = scores_dict["literasi_indonesia"]
self.literasi_inggris = scores_dict["literasi_inggris"]
self.penalaran_matematika = scores_dict["penalaran_matematika"]
class UniversityRecommender:
def get_initial_recommendations(self, scores: UTBKScores, mbti: str) -> Dict:
prompt = f"""Based on the following UTBK scores and MBTI personality type, suggest 10 suitable study programs
and Indonesian universities. Return the response in the following JSON format:
{{
"recommendations": [
{{
"program": "program_name",
"university": "university_name",
"acceptance_rate": "estimated_acceptance_rate_as_decimal",
"required_scores": {{
"penalaran_umum": minimum_score,
... (other scores)
}},
"ideal_mbti_types": ["TYPE1", "TYPE2", "TYPE3"],
"program_description": "brief_description"
}}
]
}}
UTBK Scores:
{scores.__dict__}
MBTI: {mbti}
RETURN ***JUST*** THE JSON. DO NOT WRAP IT IN A CODE BLOCK. PROVIDE THE JSON AS-IS, NOTHING ELSE.
"""
response = openai.chat.completions.create(
model="meta-llama/llama-4-scout",
messages=[
{
"role": "system",
"content": "You are a knowledgeable educational consultant who specializes in Indonesian universities.",
},
{"role": "user", "content": prompt},
],
)
try:
return json.loads(response.choices[0].message.content)
except json.JSONDecodeError:
print("Failed to get a pred (malformation), retrying...")
sleep(0.1)
return self.get_initial_recommendations(scores, mbti)
def calculate_compatibility(
self, recommendation: Dict, scores: UTBKScores, mbti: str
) -> float:
score_diffs = []
for score_type, required_score in recommendation["required_scores"].items():
actual_score = getattr(scores, score_type)
score_diffs.append(max(0, (actual_score - required_score) / 100))
score_compatibility = np.mean(score_diffs)
mbti_compatibility = 1.0 if mbti in recommendation["ideal_mbti_types"] else 0.5
acceptance_rate = float(recommendation["acceptance_rate"])
final_compatibility = (
0.4 * score_compatibility + 0.3 * mbti_compatibility + 0.3 * acceptance_rate
)
return final_compatibility
def process_recommendations(
self, raw_recommendations: Dict, scores: UTBKScores, mbti: str
) -> pd.DataFrame:
results = []
for rec in raw_recommendations["recommendations"]:
compatibility = self.calculate_compatibility(rec, scores, mbti)
results.append(
{
"Program": rec["program"],
"University": rec["university"],
"Compatibility": f"{compatibility*100:.1f}%",
"Acceptance Rate": f"{float(rec['acceptance_rate'])*100:.1f}%",
"Description": rec["program_description"],
}
)
return pd.DataFrame(results).sort_values("Compatibility", ascending=False)
def create_input_interface():
with gr.Row():
with gr.Column():
gr.Markdown("## UTBK Scores")
scores = {
"penalaran_umum": gr.Slider(0, 100, value=50, label="Penalaran Umum"),
"pengetahuan_umum": gr.Slider(
0, 100, value=50, label="Pengetahuan Umum"
),
"pemahaman_bacaan": gr.Slider(
0, 100, value=50, label="Pemahaman Bacaan"
),
"pengetahuan_kuantitatif": gr.Slider(
0, 100, value=50, label="Pengetahuan Kuantitatif"
),
"literasi_indonesia": gr.Slider(
0, 100, value=50, label="Literasi Indonesia"
),
"literasi_inggris": gr.Slider(
0, 100, value=50, label="Literasi Inggris"
),
"penalaran_matematika": gr.Slider(
0, 100, value=50, label="Penalaran Matematika"
),
}
with gr.Column():
gr.Markdown("## Personality")
mbti = gr.Dropdown(choices=MBTI_TYPES, label="MBTI Type")
return scores, mbti
def create_output_interface():
with gr.Row():
results_df = gr.Dataframe(
headers=[
"Program",
"University",
"Compatibility",
"Acceptance Rate",
"Description",
],
label="Recommended Programs",
)
return results_df
def process_input(*args):
recommender = UniversityRecommender()
scores_dict = {
"penalaran_umum": args[0],
"pengetahuan_umum": args[1],
"pemahaman_bacaan": args[2],
"pengetahuan_kuantitatif": args[3],
"literasi_indonesia": args[4],
"literasi_inggris": args[5],
"penalaran_matematika": args[6],
}
mbti = args[7]
scores = UTBKScores(scores_dict)
raw_recommendations = recommender.get_initial_recommendations(scores, mbti)
return recommender.process_recommendations(raw_recommendations, scores, mbti)
def create_recommendations_from_dict(
self, recommendations_dict: List[Dict], oauth_profile: gr.OAuthProfile | None
) -> pd.DataFrame:
return pd.DataFrame(recommendations_dict)
def create_interface():
user_manager = UserManager()
with gr.Blocks(title="University Program Recommender") as interface:
gr.LoginButton()
gr.Markdown("# Indonesian University Program Recommender")
# User info section
user_info = gr.Markdown()
# Input Section
scores, mbti = create_input_interface()
# Add Load Last Recommendation button
load_last_btn = gr.Button("Load Last Recommendation")
# Submit Button
submit_btn = gr.Button("Get New Recommendations")
# Output Section
results_df = create_output_interface()
# History Tab
with gr.Tab("History"):
history_df = gr.Dataframe(
headers=["Timestamp", "MBTI", "Scores", "Recommendations"],
label="Your Previous Recommendations",
)
def load_last_recommendation(
oauth_profile: gr.OAuthProfile | None,
) -> pd.DataFrame:
if oauth_profile is None:
return pd.DataFrame()
user = user_manager.get_or_create_user(oauth_profile)
if user.recommendations_history:
last_recommendation = user.recommendations_history[-1]
return pd.DataFrame(last_recommendation["recommendations"])
return pd.DataFrame()
def process_with_user(oauth_profile: gr.OAuthProfile | None, *args):
if oauth_profile is None:
return pd.DataFrame()
results = process_input(*args)
scores_dict = {
"penalaran_umum": args[0],
"pengetahuan_umum": args[1],
"pemahaman_bacaan": args[2],
"pengetahuan_kuantitatif": args[3],
"literasi_indonesia": args[4],
"literasi_inggris": args[5],
"penalaran_matematika": args[6],
}
scores = UTBKScores(scores_dict)
mbti = args[7]
user_manager.save_user_interaction(oauth_profile, scores, mbti, results)
return results
def update_user_info(
oauth_profile: gr.OAuthProfile | None,
) -> Tuple[str, pd.DataFrame]:
if oauth_profile is None:
return (
"Not logged in. Please login to use the recommender.",
pd.DataFrame(),
)
# Load last recommendation on login
last_rec = load_last_recommendation(oauth_profile)
return (
f"Logged in as: {oauth_profile.username} ({oauth_profile.name})",
last_rec,
)
def show_history(oauth_profile: gr.OAuthProfile | None) -> pd.DataFrame:
if oauth_profile is None:
return pd.DataFrame()
user = user_manager.get_or_create_user(oauth_profile)
history_data = []
for score_entry, rec_entry in zip(
user.scores_history, user.recommendations_history
):
history_data.append(
{
"Timestamp": score_entry["timestamp"],
"MBTI": score_entry["mbti"],
"Scores": str(score_entry["scores"]),
"Recommendations": str(rec_entry["recommendations"]),
}
)
return pd.DataFrame(history_data)
input_components = list(scores.values()) + [mbti]
submit_btn.click(
fn=process_with_user,
inputs=input_components,
outputs=[results_df],
)
load_last_btn.click(
fn=load_last_recommendation,
outputs=[results_df],
)
interface.load(update_user_info, outputs=[user_info, results_df])
interface.load(show_history, outputs=[history_df])
return interface
if __name__ == "__main__":
interface = create_interface()
interface.launch() |