shivakumar2005 commited on
Commit
91b6baa
Β·
verified Β·
1 Parent(s): 5f71292

Update app1.py

Browse files
Files changed (1) hide show
  1. app1.py +608 -0
app1.py CHANGED
@@ -0,0 +1,608 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py β€” paste into your Hugging Face Space (Python Gradio runtime)
2
+ import os, json, html, random
3
+ from datetime import datetime
4
+ import gradio as gr
5
+ import plotly.graph_objects as go
6
+
7
+ # ---------------- Files ----------------
8
+ LEADERBOARD_FILE = "road2success_leaderboard.json"
9
+ PROGRESS_FILE = "student_progress.json"
10
+ OPPORTUNITIES_FILE = "student_opportunities.json"
11
+
12
+ # Default data factories
13
+ def default_progress_data():
14
+ return {
15
+ "current_level": "Class 10",
16
+ "quizzes_completed": {},
17
+ "study_sessions_completed": {},
18
+ "total_hours_studied": 0,
19
+ "last_study_date": datetime.now().isoformat(),
20
+ "daily_goals": {},
21
+ "achievements": []
22
+ }
23
+
24
+ def default_opportunities_data():
25
+ return {
26
+ "hackathons": [],
27
+ "internships": [],
28
+ "scholarships": [],
29
+ "reminders": []
30
+ }
31
+
32
+ # Initialize files if missing
33
+ if not os.path.exists(PROGRESS_FILE):
34
+ with open(PROGRESS_FILE, "w") as f:
35
+ json.dump(default_progress_data(), f, indent=2)
36
+
37
+ if not os.path.exists(OPPORTUNITIES_FILE):
38
+ with open(OPPORTUNITIES_FILE, "w") as f:
39
+ json.dump(default_opportunities_data(), f, indent=2)
40
+
41
+ if not os.path.exists(LEADERBOARD_FILE):
42
+ with open(LEADERBOARD_FILE, "w") as f:
43
+ json.dump({"scores": []}, f, indent=2)
44
+
45
+ def load_progress():
46
+ try:
47
+ with open(PROGRESS_FILE, "r") as f:
48
+ return json.load(f)
49
+ except:
50
+ return default_progress_data()
51
+
52
+ def save_progress(p):
53
+ with open(PROGRESS_FILE, "w") as f:
54
+ json.dump(p, f, indent=2)
55
+
56
+ def load_opportunities():
57
+ try:
58
+ with open(OPPORTUNITIES_FILE, "r") as f:
59
+ return json.load(f)
60
+ except:
61
+ return default_opportunities_data()
62
+
63
+ def save_opportunities(d):
64
+ with open(OPPORTUNITIES_FILE, "w") as f:
65
+ json.dump(d, f, indent=2)
66
+
67
+ def reset_leaderboard():
68
+ with open(LEADERBOARD_FILE, "w") as f:
69
+ json.dump({"scores": []}, f, indent=2)
70
+
71
+ # ---------------- Roadmaps & Data ----------------
72
+ # (includes Class 6..10, JEE Main, NEET, B.Tech 1st..Final Year)
73
+ ROADMAPS = {
74
+ "Class 6": {
75
+ "objective": "Build curiosity, logical thinking, basic problem-solving and gentle programming.",
76
+ "subjects": ["Fractions, Decimals, Basic Geometry", "Basics of Physics, Chemistry, Biology", "Scratch / Python Turtle basics"],
77
+ "study_sessions": [
78
+ {"title": "Basic Mathematics Fundamentals", "duration": "2 hours", "topics": ["Number System", "Basic Operations", "Fractions"]},
79
+ {"title": "Introduction to Science", "duration": "1.5 hours", "topics": ["Living Organisms", "Matter", "Energy"]},
80
+ {"title": "Scratch Programming Basics", "duration": "2 hours", "topics": ["Blocks", "Sprites", "Simple Games"]}
81
+ ],
82
+ "projects": ["Simple games in Scratch", "Science fair volcano or plant growth"],
83
+ "weekly_hours": 18,
84
+ "difficulty": "Beginner"
85
+ },
86
+ "Class 7": {
87
+ "objective": "Strengthen reasoning, begin structured coding and deeper science.",
88
+ "subjects": ["Integers, Fractions, Probability", "Forces, Motion, Biology", "Python basics - loops & conditionals"],
89
+ "study_sessions": [
90
+ {"title": "Algebra Fundamentals", "duration": "2.5 hours", "topics": ["Variables", "Equations", "Expressions"]},
91
+ {"title": "Physics Basics", "duration": "2 hours", "topics": ["Motion", "Forces", "Energy"]},
92
+ {"title": "Python Introduction", "duration": "3 hours", "topics": ["Syntax", "Variables", "Basic Programs"]}
93
+ ],
94
+ "projects": ["Python guessing game", "Science experiments logbook"],
95
+ "weekly_hours": 20,
96
+ "difficulty": "Beginner"
97
+ },
98
+ "Class 8": {
99
+ "objective": "Structured thinking, algebra foundation, and applied coding.",
100
+ "subjects": ["Algebra, Linear equations, Geometry", "Electricity basics, Chemistry", "Python lists & functions"],
101
+ "study_sessions": [
102
+ {"title": "Algebra and Equations", "duration": "3 hours", "topics": ["Linear Equations", "Polynomials", "Factorization"]},
103
+ {"title": "Science Concepts", "duration": "2.5 hours", "topics": ["Electricity", "Chemical Reactions", "Light"]},
104
+ {"title": "Python Functions", "duration": "3 hours", "topics": ["Functions", "Lists", "Basic Algorithms"]}
105
+ ],
106
+ "projects": ["Calculator in Python", "Science project presentation"],
107
+ "weekly_hours": 22,
108
+ "difficulty": "Intermediate"
109
+ },
110
+ "Class 9": {
111
+ "objective": "Prepare foundations for high-school STEM and beginner coding competitions.",
112
+ "subjects": ["Geometry, Trigonometry basics, Probability", "Motion, Energy, Chemistry basics", "Python data structures"],
113
+ "study_sessions": [
114
+ {"title": "Geometry and Trigonometry", "duration": "3 hours", "topics": ["Triangles", "Circles", "Trigonometric Ratios"]},
115
+ {"title": "Physics Fundamentals", "duration": "3 hours", "topics": ["Motion", "Force", "Energy", "Work"]},
116
+ {"title": "Python Data Structures", "duration": "3 hours", "topics": ["Lists", "Dictionaries", "Tuples", "Sets"]}
117
+ ],
118
+ "projects": ["Math problem solver", "Physics simulation"],
119
+ "weekly_hours": 25,
120
+ "difficulty": "Intermediate"
121
+ },
122
+ "Class 10": {
123
+ "objective": "Prepare for board exams and build strong coding fundamentals.",
124
+ "subjects": ["Algebra, Quadratics, Coordinate Geometry", "Physics/Chem/Biology fundamentals", "Python algorithms"],
125
+ "study_sessions": [
126
+ {"title": "Advanced Mathematics", "duration": "4 hours", "topics": ["Quadratic Equations", "Arithmetic Progressions", "Coordinate Geometry"]},
127
+ {"title": "Science Comprehensive", "duration": "4 hours", "topics": ["Light", "Electricity", "Chemical Reactions", "Life Processes"]},
128
+ {"title": "Python Algorithms", "duration": "3 hours", "topics": ["Sorting", "Searching", "Problem Solving"]}
129
+ ],
130
+ "projects": ["Board exam preparation", "Mini coding projects"],
131
+ "weekly_hours": 30,
132
+ "difficulty": "Intermediate"
133
+ },
134
+ "JEE Main": {
135
+ "objective": "Crack JEE Main with focused PCM practice and time management.",
136
+ "subjects": ["Physics: Mechanics, Optics, Modern Physics", "Chemistry: Physical, Organic, Inorganic", "Mathematics: Algebra, Calculus, Coordinate Geometry"],
137
+ "study_sessions": [
138
+ {"title": "Physics Advanced", "duration": "5 hours", "topics": ["Mechanics", "Optics", "Electromagnetism", "Modern Physics"]},
139
+ {"title": "Chemistry Comprehensive", "duration": "5 hours", "topics": ["Physical Chemistry", "Organic Chemistry", "Inorganic Chemistry"]},
140
+ {"title": "Mathematics Intensive", "duration": "5 hours", "topics": ["Calculus", "Algebra", "Coordinate Geometry", "Probability"]}
141
+ ],
142
+ "projects": ["Mock test series", "Previous year papers"],
143
+ "weekly_hours": 45,
144
+ "difficulty": "Advanced"
145
+ },
146
+ "NEET": {
147
+ "objective": "Crack NEET with strong Biology focus and NCERT mastery.",
148
+ "subjects": ["Biology: Botany, Zoology", "Chemistry: Physical, Organic, Inorganic", "Physics: Basics for Medical"],
149
+ "study_sessions": [
150
+ {"title": "Biology Intensive", "duration": "6 hours", "topics": ["Human Physiology", "Genetics", "Plant Physiology", "Ecology"]},
151
+ {"title": "Chemistry for NEET", "duration": "4 hours", "topics": ["Organic Chemistry", "Physical Chemistry", "Inorganic Chemistry"]},
152
+ {"title": "Physics Medical", "duration": "4 hours", "topics": ["Mechanics", "Optics", "Thermodynamics", "Modern Physics"]}
153
+ ],
154
+ "projects": ["NCERT revision", "Medical entrance mock tests"],
155
+ "weekly_hours": 48,
156
+ "difficulty": "Advanced"
157
+ },
158
+ "B.Tech 1st Year": {
159
+ "objective": "Build strong foundation in programming, mathematics, and basic engineering.",
160
+ "subjects": ["Programming Fundamentals", "Engineering Mathematics", "Physics & Chemistry", "Basic Electronics"],
161
+ "study_sessions": [
162
+ {"title": "C Programming", "duration": "4 hours", "topics": ["Data Types", "Control Structures", "Functions", "Arrays"]},
163
+ {"title": "Engineering Mathematics", "duration": "4 hours", "topics": ["Calculus", "Matrices", "Differential Equations"]},
164
+ {"title": "Engineering Physics", "duration": "3 hours", "topics": ["Mechanics", "Waves", "Optics", "Thermodynamics"]}
165
+ ],
166
+ "projects": ["Simple Calculator", "Basic Circuit Design"],
167
+ "weekly_hours": 35,
168
+ "difficulty": "Intermediate"
169
+ },
170
+ "B.Tech 2nd Year": {
171
+ "objective": "Develop core engineering skills and branch specialization.",
172
+ "subjects": ["Data Structures", "Object-Oriented Programming", "Database Management", "Discrete Mathematics"],
173
+ "study_sessions": [
174
+ {"title": "Data Structures", "duration": "5 hours", "topics": ["Arrays", "Linked Lists", "Stacks", "Queues", "Trees"]},
175
+ {"title": "OOP Concepts", "duration": "4 hours", "topics": ["Classes", "Inheritance", "Polymorphism", "Abstraction"]},
176
+ {"title": "Database Systems", "duration": "4 hours", "topics": ["SQL", "Normalization", "ER Diagrams"]}
177
+ ],
178
+ "projects": ["Library Management System", "Student Database"],
179
+ "weekly_hours": 38,
180
+ "difficulty": "Intermediate"
181
+ },
182
+ "B.Tech 3rd Year": {
183
+ "objective": "Advanced specialization and industry-ready skills development.",
184
+ "subjects": ["Operating Systems", "Computer Networks", "Software Engineering", "Machine Learning"],
185
+ "study_sessions": [
186
+ {"title": "Operating Systems", "duration": "5 hours", "topics": ["Process Management", "Memory Management", "File Systems"]},
187
+ {"title": "Computer Networks", "duration": "5 hours", "topics": ["TCP/IP", "Routing", "Network Security"]},
188
+ {"title": "Machine Learning", "duration": "5 hours", "topics": ["Supervised Learning", "Unsupervised Learning", "Neural Networks"]}
189
+ ],
190
+ "projects": ["Web Application", "ML Project", "Network Simulation"],
191
+ "weekly_hours": 42,
192
+ "difficulty": "Advanced"
193
+ },
194
+ "B.Tech Final Year": {
195
+ "objective": "Capstone projects, placement preparation, and research orientation.",
196
+ "subjects": ["System Design", "Cloud Computing", "Big Data Analytics", "AI & Deep Learning"],
197
+ "study_sessions": [
198
+ {"title": "System Design", "duration": "6 hours", "topics": ["Microservices", "Load Balancing", "Scalability"]},
199
+ {"title": "Cloud Computing", "duration": "5 hours", "topics": ["AWS/Azure", "Virtualization", "Containerization"]},
200
+ {"title": "AI & Deep Learning", "duration": "6 hours", "topics": ["CNN", "RNN", "Transformers", "Computer Vision"]}
201
+ ],
202
+ "projects": ["Major Project", "Research Paper", "Portfolio Website"],
203
+ "weekly_hours": 45,
204
+ "difficulty": "Expert"
205
+ }
206
+ }
207
+
208
+ # ---------------- Opportunities (H/I/S) ----------------
209
+ HACKATHONS = [
210
+ {"name":"Smart India Hackathon 2024","deadline":"2024-03-15","eligibility":"College Students (All Years)","prizes":"β‚Ή5 Lakhs + Incubation","skills":["Programming","Problem Solving"],"url":"https://sih.gov.in","category":"National","level":"B.Tech All Years"},
211
+ {"name":"NASA Space Apps Challenge","deadline":"2024-10-01","eligibility":"All Students","prizes":"NASA Recognition + Prizes","skills":["Data Science","Space Tech"],"url":"https://www.spaceappschallenge.org","category":"International","level":"All Levels"}
212
+ ]
213
+ INTERNSHIPS = [
214
+ {"name":"Microsoft High School Internship","deadline":"2024-04-30","duration":"8 weeks","stipend":"β‚Ή30,000/month","skills":["Python"],"url":"https://careers.microsoft.com","type":"Tech","level":"Class 11-12"},
215
+ {"name":"Google Summer of Code","deadline":"2024-05-01","duration":"12 weeks","stipend":"$3000","skills":["Open Source"],"url":"https://summerofcode.withgoogle.com","type":"Open Source","level":"B.Tech 2nd-4th Year"}
216
+ ]
217
+ SCHOLARSHIPS = [
218
+ {"name":"NTSE","deadline":"2024-11-30","amount":"β‚Ή1250/month","eligibility":"Class 10 Students","url":"https://ncert.nic.in","type":"Merit-based","level":"Class 10"}
219
+ ]
220
+
221
+ # ---------------- AI Mentor (lightweight) ----------------
222
+ def ai_mentor_query(prompt, short_answer=True, eli5=False):
223
+ if not prompt or not prompt.strip():
224
+ return "Ask a clear question about study plans, hackathons, or projects."
225
+ fallback_responses = [
226
+ "Try splitting study into focused 25-minute sessions with 5-minute breaks.",
227
+ "For hackathons, build the smallest working prototype first, then polish.",
228
+ "Practice coding by building small projects; review and refactor them.",
229
+ "Create a weekly schedule and stick to short daily study blocks for steady progress."
230
+ ]
231
+ return random.choice(fallback_responses)
232
+
233
+ # ---------------- Dashboard helpers ----------------
234
+ def create_progress_chart(level, sessions_completed, total_sessions):
235
+ progress = 0
236
+ if total_sessions > 0:
237
+ progress = min((sessions_completed / total_sessions) * 100, 100)
238
+ fig = go.Figure(go.Indicator(mode="gauge+number", value=progress, domain={'x':[0,1],'y':[0,1]}, title={'text':f"Study Progress - {level}"}, gauge={'axis':{'range':[None,100]}}))
239
+ return fig
240
+
241
+ def get_study_materials_interface(level):
242
+ sessions = ROADMAPS.get(level, {}).get("study_sessions", [])
243
+ progress_data = load_progress()
244
+ materials_html = "<div style='max-height:520px;overflow-y:auto;'>"
245
+ materials_html += "<h3>πŸ“š Study Sessions</h3>"
246
+ for i, session in enumerate(sessions):
247
+ session_key = f"{level}_{session['title']}"
248
+ is_completed = progress_data.get("study_sessions_completed", {}).get(session_key, False)
249
+ status_icon = "βœ…" if is_completed else "⏳"
250
+ status_color = "#28a745" if is_completed else "#007bff"
251
+ materials_html += f"""
252
+ <div style='padding:12px;margin:8px 0;background:{'#d4edda' if is_completed else '#f8f9fa'};border-radius:8px;border-left:4px solid {status_color};'>
253
+ <h4 style="color:#0b3d91">{status_icon} Session {i+1}: {html.escape(session['title'])}</h4>
254
+ <p>⏰ {session['duration']}</p>
255
+ <p>πŸ“š {', '.join(session['topics'])}</p>
256
+ </div>
257
+ """
258
+ materials_html += "</div>"
259
+ return materials_html
260
+
261
+ def mark_session_completed(level, session_title):
262
+ if not level or not session_title:
263
+ return "❌ Level and session required."
264
+ p = load_progress()
265
+ key = f"{level}_{session_title}"
266
+ p.setdefault("study_sessions_completed", {})
267
+ current = p["study_sessions_completed"].get(key, False)
268
+ p["study_sessions_completed"][key] = not current
269
+ # update hours
270
+ s = next((x for x in ROADMAPS.get(level, {}).get("study_sessions", []) if x['title'] == session_title), None)
271
+ if s:
272
+ try:
273
+ hours = float(s['duration'].split()[0])
274
+ except:
275
+ hours = 0.0
276
+ if not current:
277
+ p["total_hours_studied"] = p.get("total_hours_studied", 0) + hours
278
+ else:
279
+ p["total_hours_studied"] = max(0, p.get("total_hours_studied", 0) - hours)
280
+ p["last_study_date"] = datetime.now().isoformat()
281
+ save_progress(p)
282
+ action = "completed" if not current else "unmarked"
283
+ return f"βœ… Session '{session_title}' {action}! Progress updated."
284
+
285
+ def create_dashboard_stats(level):
286
+ p = load_progress()
287
+ sessions = ROADMAPS.get(level, {}).get("study_sessions", [])
288
+ completed_sessions = sum(1 for s in sessions if p.get("study_sessions_completed", {}).get(f"{level}_{s['title']}", False))
289
+ total_sessions = len(sessions)
290
+ percent = (completed_sessions / total_sessions * 100) if total_sessions > 0 else 0
291
+ last = p.get("last_study_date", datetime.now().isoformat())[:10]
292
+ html_block = f"""
293
+ <div style='background:linear-gradient(135deg,#dbeafe,#bde4ff);color:#0b3d91;padding:16px;border-radius:10px;'>
294
+ <h3>🎯 {level} Learning Dashboard</h3>
295
+ <div style='display:flex;justify-content:space-around;flex-wrap:wrap;margin-top:10px;'>
296
+ <div><h4>πŸ“š {completed_sessions}/{total_sessions}</h4><small>Sessions</small></div>
297
+ <div><h4>⏰ {p.get('total_hours_studied',0):.1f}</h4><small>Total Hours</small></div>
298
+ <div><h4>πŸ“… {last}</h4><small>Last Study</small></div>
299
+ </div>
300
+ <p style='margin-top:12px;'>Overall Progress: <strong>{percent:.1f}%</strong></p>
301
+ <div style='background:#ddd;border-radius:8px;height:10px;'><div style='background:#28a745;height:100%;width:{percent}%;border-radius:8px;'></div></div>
302
+ </div>
303
+ """
304
+ return html_block
305
+
306
+ # ---------------- Opportunities & Reminders ----------------
307
+ def get_upcoming_deadlines_html():
308
+ today = datetime.now().date()
309
+ items = HACKATHONS + INTERNSHIPS + SCHOLARSHIPS
310
+ deadlines = []
311
+ for it in items:
312
+ dl = it.get("deadline")
313
+ try:
314
+ d = datetime.strptime(dl, "%Y-%m-%d").date()
315
+ days = (d - today).days
316
+ except:
317
+ days = None
318
+ deadlines.append({"name":it.get("name"), "deadline":dl, "days_left":days, "url":it.get("url","#")})
319
+ deadlines = sorted([d for d in deadlines if d['days_left'] is None or d['days_left']>=0], key=lambda x: (x['days_left'] if x['days_left'] is not None else 999))
320
+ if not deadlines:
321
+ return "<div style='padding:12px;text-align:center;'><h4>No upcoming deadlines</h4></div>"
322
+ html_block = "<div style='max-height:420px;overflow-y:auto;'>"
323
+ for d in deadlines[:12]:
324
+ left = f"{d['days_left']} days left" if d['days_left'] is not None else "N/A"
325
+ html_block += f"<div style='padding:10px;margin:8px 0;background:white;border-radius:8px;'><h4>{html.escape(d['name'])}</h4><p>πŸ“… {d['deadline']} | {left}</p><a href='{d['url']}' target='_blank'>More</a></div>"
326
+ html_block += "</div>"
327
+ return html_block
328
+
329
+ def create_hackathon_interface_html():
330
+ html_block = "<div style='max-height:420px;overflow-y:auto;'>"
331
+ for h in HACKATHONS:
332
+ try:
333
+ days = (datetime.strptime(h['deadline'],'%Y-%m-%d').date() - datetime.now().date()).days
334
+ except:
335
+ days = "N/A"
336
+ html_block += f"<div style='padding:12px;margin:8px 0;background:linear-gradient(135deg,#dbeafe,#bde4ff);color:#0b3d91;border-radius:8px;'><h4>πŸ† {h['name']}</h4><p>πŸ“… {h['deadline']} | {days} days left</p><p>Eligibility: {h['eligibility']}</p><a href='{h['url']}' style='color:#0b3d91' target='_blank'>Apply</a></div>"
337
+ html_block += "</div>"
338
+ return html_block
339
+
340
+ def create_internship_interface_html():
341
+ html_block = "<div style='max-height:420px;overflow-y:auto;'>"
342
+ for it in INTERNSHIPS:
343
+ try:
344
+ days = (datetime.strptime(it['deadline'],'%Y-%m-%d').date() - datetime.now().date()).days
345
+ except:
346
+ days = "N/A"
347
+ html_block += f"<div style='padding:12px;margin:8px 0;background:linear-gradient(135deg,#e6f4ff,#cfeeff);color:#0b3d91;border-radius:8px;'><h4>πŸ’Ό {it['name']}</h4><p>πŸ“… {it['deadline']} | {days} days left</p><p>Duration: {it.get('duration')}</p><a href='{it['url']}' style='color:#0b3d91' target='_blank'>Apply</a></div>"
348
+ html_block += "</div>"
349
+ return html_block
350
+
351
+ def create_scholarship_interface_html():
352
+ html_block = "<div style='max-height:420px;overflow-y:auto;'>"
353
+ for s in SCHOLARSHIPS:
354
+ try:
355
+ days = (datetime.strptime(s['deadline'],'%Y-%m-%d').date() - datetime.now().date()).days
356
+ except:
357
+ days = "N/A"
358
+ html_block += f"<div style='padding:12px;margin:8px 0;background:linear-gradient(135deg,#e0f7ff,#cdeeff);color:#0b3d91;border-radius:8px;'><h4>πŸŽ“ {s['name']}</h4><p>πŸ“… {s['deadline']} | {days} days left</p><p>Amount: {s.get('amount')}</p><a href='{s['url']}' style='color:#0b3d91' target='_blank'>Apply</a></div>"
359
+ html_block += "</div>"
360
+ return html_block
361
+
362
+ def set_custom_reminder(reminder_type, reminder_name, reminder_date, reminder_notes):
363
+ if not reminder_name or not reminder_date:
364
+ return "❌ Name and date required."
365
+ try:
366
+ datetime.strptime(reminder_date, "%Y-%m-%d")
367
+ except ValueError:
368
+ return "❌ Invalid date format. Use YYYY-MM-DD."
369
+ data = load_opportunities()
370
+ data.setdefault("reminders", [])
371
+ new = {
372
+ "type": reminder_type or "Personal",
373
+ "name": reminder_name,
374
+ "date": reminder_date,
375
+ "notes": reminder_notes or "",
376
+ "set_date": datetime.now().isoformat(),
377
+ "completed": False
378
+ }
379
+ data["reminders"].append(new)
380
+ save_opportunities(data)
381
+ return f"βœ… Reminder set for {reminder_date}: {reminder_name}"
382
+
383
+ def get_custom_reminders_html():
384
+ data = load_opportunities()
385
+ rems = data.get("reminders", [])
386
+ if not rems:
387
+ return "<div style='text-align:center;padding:12px;'><h4>No custom reminders.</h4></div>"
388
+ html_block = "<div style='max-height:420px;overflow-y:auto;'>"
389
+ for idx, r in enumerate(rems):
390
+ try:
391
+ d = datetime.strptime(r['date'], "%Y-%m-%d").date()
392
+ days_left = (d - datetime.now().date()).days
393
+ left_text = f"{days_left} days left"
394
+ except:
395
+ left_text = "N/A"
396
+ color = "#28a745" if r.get("completed") else "#ff6b6b"
397
+ status = "βœ…" if r.get("completed") else "⏳"
398
+ html_block += f"""
399
+ <div style='padding:10px;margin:8px 0;background:white;border-left:6px solid {color};border-radius:8px;'>
400
+ <h4>{status} [{idx}] {html.escape(r['type'])}: {html.escape(r['name'])}</h4>
401
+ <p>πŸ“… {r['date']} | {left_text}</p>
402
+ <p>πŸ“ {html.escape(r.get('notes',''))}</p>
403
+ <p style='font-size:12px;color:#666;'>Set on: {r['set_date'][:10]}</p>
404
+ </div>
405
+ """
406
+ html_block += "</div>"
407
+ return html_block
408
+
409
+ def mark_reminder_completed(index):
410
+ data = load_opportunities()
411
+ rems = data.get("reminders", [])
412
+ try:
413
+ idx = int(index)
414
+ if idx < 0 or idx >= len(rems):
415
+ return "❌ Invalid index"
416
+ except:
417
+ return "❌ Invalid index"
418
+ rems[idx]['completed'] = True
419
+ save_opportunities(data)
420
+ return "βœ… Reminder marked completed."
421
+
422
+ def delete_reminder(index):
423
+ data = load_opportunities()
424
+ rems = data.get("reminders", [])
425
+ try:
426
+ idx = int(index)
427
+ if idx < 0 or idx >= len(rems):
428
+ return "❌ Invalid index"
429
+ except:
430
+ return "❌ Invalid index"
431
+ name = rems[idx].get("name","")
432
+ rems.pop(idx)
433
+ save_opportunities(data)
434
+ return f"πŸ—‘οΈ Reminder '{name}' deleted."
435
+
436
+ # ---------------- GRADIO UI ----------------
437
+ custom_css = """
438
+ /* Light blue background gradient for the whole app */
439
+ .gradio-container {
440
+ background: linear-gradient(135deg, #eaf6ff 0%, #d5efff 100%);
441
+ min-height: 100vh;
442
+ padding: 24px;
443
+ color: #0b3d91;
444
+ }
445
+ /* Slightly transparent panels so the light-blue shows through */
446
+ .gradio-container .container {
447
+ background: rgba(255,255,255,0.04);
448
+ border-radius: 12px;
449
+ padding: 16px;
450
+ }
451
+ """
452
+
453
+ with gr.Blocks(title="Road2Success β€” Learning Dashboard (light blue)", theme=gr.themes.Soft(), css=custom_css) as app:
454
+ gr.Markdown("# πŸš€ Road2Success β€” Learning Dashboard")
455
+ gr.Markdown("*Background: light blue. Includes Reset Dashboard button.*")
456
+
457
+ with gr.Tabs():
458
+ # Learning Dashboard
459
+ with gr.TabItem("🏠 Learning Dashboard"):
460
+ with gr.Row():
461
+ with gr.Column(scale=2):
462
+ gr.Markdown("### Select Level")
463
+ level_choice = gr.Radio(choices=list(ROADMAPS.keys()), value=list(ROADMAPS.keys())[0], label="Level")
464
+ refresh_btn = gr.Button("πŸ”„ Refresh")
465
+ stats_display = gr.HTML()
466
+ with gr.Column(scale=3):
467
+ progress_plot = gr.Plot()
468
+ gr.Markdown("### Study Materials")
469
+ with gr.Row():
470
+ with gr.Column(scale=2):
471
+ materials_html = gr.HTML()
472
+ with gr.Column(scale=1):
473
+ gr.Markdown("### Quick Actions")
474
+ session_dropdown = gr.Dropdown(label="Session", choices=[])
475
+ mark_session_btn = gr.Button("Mark Session Complete")
476
+ action_status = gr.Textbox(interactive=False, label="Action status")
477
+ schedule_html = gr.HTML()
478
+ # Reset button
479
+ reset_status = gr.Textbox(interactive=False, label="Reset status")
480
+ reset_btn = gr.Button("⚠️ Reset Dashboard", variant="danger")
481
+
482
+ # Study Roadmaps
483
+ with gr.TabItem("πŸ“š Study Roadmaps"):
484
+ gr.Markdown("## πŸ—ΊοΈ Study Roadmaps")
485
+ roadmap_level = gr.Dropdown(choices=list(ROADMAPS.keys()), value=list(ROADMAPS.keys())[0], label="Select Level")
486
+ show_roadmap_btn = gr.Button("Show Roadmap")
487
+ roadmap_html = gr.HTML()
488
+
489
+ # Opportunities & Reminders
490
+ with gr.TabItem("πŸš€ Opportunities & Reminders"):
491
+ gr.Markdown("## 🌟 Opportunities Hub")
492
+ with gr.Row():
493
+ with gr.Column(scale=2):
494
+ opp_overview = gr.HTML()
495
+ gr.Markdown("### Hackathons")
496
+ hack_html = gr.HTML()
497
+ gr.Markdown("### Internships")
498
+ intern_html = gr.HTML()
499
+ gr.Markdown("### Scholarships")
500
+ schol_html = gr.HTML()
501
+ with gr.Column(scale=1):
502
+ gr.Markdown("### Set Custom Reminder")
503
+ r_type = gr.Dropdown(["Hackathon","Internship","Scholarship","Exam","Project","Personal"], label="Type")
504
+ r_name = gr.Textbox(label="Name")
505
+ r_date = gr.Textbox(label="Date (YYYY-MM-DD)")
506
+ r_notes = gr.Textbox(label="Notes", lines=2)
507
+ set_reminder_btn = gr.Button("Set Reminder")
508
+ set_out = gr.Textbox(interactive=False, label="Set status")
509
+ gr.Markdown("### Your Reminders (0-based index shown)")
510
+ reminders_html = gr.HTML()
511
+ rem_index = gr.Textbox(label="Reminder index (0-based)")
512
+ mark_done_btn = gr.Button("Mark Done")
513
+ del_btn = gr.Button("Delete Reminder")
514
+ rem_action_status = gr.Textbox(interactive=False, label="Reminder action status")
515
+
516
+ # AI Mentor
517
+ with gr.TabItem("πŸ€– AI Mentor"):
518
+ gr.Markdown("## πŸ’¬ AI Mentor (simple fallback)")
519
+ prompt = gr.Textbox(label="Ask a question", lines=3)
520
+ short_toggle = gr.Checkbox(label="Short answer", value=True)
521
+ eli5_toggle = gr.Checkbox(label="Explain simply", value=False)
522
+ ask_btn = gr.Button("Ask Mentor")
523
+ mentor_out = gr.Textbox(lines=6, label="Mentor output")
524
+
525
+ # -- Core update function used by several handlers
526
+ def update_dashboard(level):
527
+ sessions = ROADMAPS.get(level, {}).get("study_sessions", [])
528
+ session_titles = [s['title'] for s in sessions]
529
+ stats = create_dashboard_stats(level)
530
+ completed_sessions = sum(1 for s in sessions if load_progress().get("study_sessions_completed", {}).get(f"{level}_{s['title']}", False))
531
+ fig = create_progress_chart(level, completed_sessions, len(sessions))
532
+ schedule = "<div style='padding:12px;background:rgba(255,255,255,0.04);border-radius:8px;'><h4>Weekly Plan</h4>"
533
+ schedule += f"<p>Target: {ROADMAPS.get(level,{}).get('weekly_hours', 'N/A')} hours per week</p>"
534
+ schedule += f"<p>Focus: {', '.join(ROADMAPS.get(level,{}).get('subjects', []))}</p></div>"
535
+ materials = get_study_materials_interface(level)
536
+ opps = get_upcoming_deadlines_html()
537
+ return gr.update(choices=session_titles, value=(session_titles[0] if session_titles else None)), stats, fig, schedule, materials, opps
538
+
539
+ # Helper to refresh multiple UI parts (used after reset)
540
+ def refresh_all(level):
541
+ session_update, stats, fig, schedule, materials, opps = update_dashboard(level)
542
+ reminders = get_custom_reminders_html()
543
+ hack = create_hackathon_interface_html()
544
+ intern = create_internship_interface_html()
545
+ schol = create_scholarship_interface_html()
546
+ return session_update, stats, fig, schedule, materials, opps, reminders, hack, intern, schol
547
+
548
+ # Reset handler
549
+ def reset_dashboard():
550
+ save_progress(default_progress_data())
551
+ save_opportunities(default_opportunities_data())
552
+ reset_leaderboard()
553
+ return "βœ… Dashboard reset to defaults."
554
+
555
+ # Wire events (use inputs rather than .value)
556
+ level_choice.change(update_dashboard, inputs=[level_choice], outputs=[session_dropdown, stats_display, progress_plot, schedule_html, materials_html, opp_overview])
557
+ refresh_btn.click(update_dashboard, inputs=[level_choice], outputs=[session_dropdown, stats_display, progress_plot, schedule_html, materials_html, opp_overview])
558
+ app.load(lambda: update_dashboard(list(ROADMAPS.keys())[0]), outputs=[session_dropdown, stats_display, progress_plot, schedule_html, materials_html, opp_overview])
559
+
560
+ mark_session_btn.click(mark_session_completed, inputs=[level_choice, session_dropdown], outputs=[action_status]).then(
561
+ update_dashboard, inputs=[level_choice], outputs=[session_dropdown, stats_display, progress_plot, schedule_html, materials_html, opp_overview]
562
+ )
563
+
564
+ # Reset button wiring: run reset_dashboard then refresh entire UI
565
+ reset_btn.click(reset_dashboard, outputs=[reset_status]).then(
566
+ refresh_all, inputs=[level_choice], outputs=[session_dropdown, stats_display, progress_plot, schedule_html, materials_html, opp_overview, reminders_html, hack_html, intern_html, schol_html]
567
+ )
568
+
569
+ # Study roadmap
570
+ def show_roadmap(level):
571
+ r = ROADMAPS.get(level, {})
572
+ html_block = f"<div style='padding:16px;background:linear-gradient(135deg,#dbeafe,#bde4ff);color:#0b3d91;border-radius:10px;'><h2>{level} - Learning Path</h2>"
573
+ html_block += f"<h4>Objective</h4><p>{r.get('objective','')}</p>"
574
+ html_block += "<h4>Subjects</h4><ul>"
575
+ for sub in r.get('subjects', []):
576
+ html_block += f"<li>{sub}</li>"
577
+ html_block += "</ul><h4>Projects</h4><ul>"
578
+ for proj in r.get('projects', []):
579
+ html_block += f"<li>{proj}</li>"
580
+ html_block += "</ul>"
581
+ html_block += f"<p><strong>Weekly hours:</strong> {r.get('weekly_hours','N/A')}</p></div>"
582
+ return html_block
583
+
584
+ show_roadmap_btn.click(show_roadmap, inputs=[roadmap_level], outputs=[roadmap_html])
585
+
586
+ # Opportunities and reminders initial loads
587
+ app.load(lambda: get_upcoming_deadlines_html(), outputs=[opp_overview])
588
+ app.load(lambda: create_hackathon_interface_html(), outputs=[hack_html])
589
+ app.load(lambda: create_internship_interface_html(), outputs=[intern_html])
590
+ app.load(lambda: create_scholarship_interface_html(), outputs=[schol_html])
591
+ app.load(lambda: get_custom_reminders_html(), outputs=[reminders_html])
592
+
593
+ set_reminder_btn.click(set_custom_reminder, inputs=[r_type, r_name, r_date, r_notes], outputs=[set_out]).then(
594
+ lambda: get_custom_reminders_html(), outputs=[reminders_html]
595
+ ).then(lambda: get_upcoming_deadlines_html(), outputs=[opp_overview])
596
+
597
+ mark_done_btn.click(mark_reminder_completed, inputs=[rem_index], outputs=[rem_action_status]).then(
598
+ lambda: get_custom_reminders_html(), outputs=[reminders_html]
599
+ ).then(lambda: get_upcoming_deadlines_html(), outputs=[opp_overview])
600
+
601
+ del_btn.click(delete_reminder, inputs=[rem_index], outputs=[rem_action_status]).then(
602
+ lambda: get_custom_reminders_html(), outputs=[reminders_html]
603
+ ).then(lambda: get_upcoming_deadlines_html(), outputs=[opp_overview])
604
+
605
+ ask_btn.click(ai_mentor_query, inputs=[prompt, short_toggle, eli5_toggle], outputs=[mentor_out])
606
+
607
+ # Launch Gradio app
608
+ app.launch()