shivakumar2005 commited on
Commit
c802a06
·
verified ·
1 Parent(s): 35ef221

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +204 -42
app.py CHANGED
@@ -4,33 +4,22 @@ import requests, json, datetime
4
  from bs4 import BeautifulSoup
5
  from transformers import pipeline
6
 
 
7
  # Store the leaderboard file in the current working directory
8
  LEADERBOARD_FILE = "road2success_leaderboard.json"
9
 
10
- # Create the file if it doesn't exist
11
  if not os.path.exists(LEADERBOARD_FILE):
12
  with open(LEADERBOARD_FILE, "w") as f:
13
- f.write(json.dumps({"scores": []}, indent=2)) # Proper JSON dict
14
 
15
- # Safe read leaderboard
16
- def safe_read_leaderboard():
17
- try:
18
- with open(LEADERBOARD_FILE, "r") as f:
19
- return json.load(f)
20
- except:
21
- return {"scores": []}
22
-
23
- # Safe write leaderboard
24
- def safe_write_leaderboard(data):
25
- with open(LEADERBOARD_FILE, "w") as f:
26
- json.dump(data, f, indent=2)
27
 
28
  _gen = None
29
  def get_generator():
30
  global _gen
31
  if _gen is None:
32
  try:
33
- _gen = pipeline("text-generation", model="distilgpt2", device=-1) # CPU Colab
34
  except Exception as e:
35
  _gen = None
36
  print("Failed to load generator:", e)
@@ -41,7 +30,7 @@ def ai_mentor_query(prompt, short_answer=True, eli5=False):
41
  return "Ask a clear question about study plans, hackathons, or projects."
42
  gen = get_generator()
43
  if gen is None:
44
- return "AI model failed to load. Try restarting the Colab runtime."
45
  modifier = ""
46
  if short_answer:
47
  modifier += " Provide a concise answer in <= 3 sentences."
@@ -49,12 +38,139 @@ def ai_mentor_query(prompt, short_answer=True, eli5=False):
49
  modifier += " Explain like I'm 5 (simple, clear language)."
50
  request = prompt.strip() + modifier
51
  out = gen(request, max_length=120, num_return_sequences=1)[0]["generated_text"]
52
- out = out.replace("\n", " ").strip()
53
- return out[:900]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
- # (ROADMAPS dict and other functions remain unchanged...)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
- # ---- QUIZ + LEADERBOARD FIXED ----
58
  SAMPLE_QUIZ = [
59
  ("What is the time complexity of binary search?", ["O(1)","O(n)","O(log n)","O(n log n)"], "O(log n)"),
60
  ("Which Python library is used for machine learning?", ["NumPy","scikit-learn","Pandas","Matplotlib"], "scikit-learn"),
@@ -65,20 +181,21 @@ def grade_and_record(name, a1, a2, a3):
65
  answers = [a1, a2, a3]
66
  correct = sum(1 for i, a in enumerate(answers) if a == SAMPLE_QUIZ[i][2])
67
  score = int(correct)
68
-
69
- data = safe_read_leaderboard()
70
- if "scores" not in data:
 
71
  data = {"scores": []}
72
-
73
  entry = {"name": name or "Anonymous", "score": score, "time": datetime.datetime.now().isoformat()}
74
  data["scores"].append(entry)
75
  data["scores"] = sorted(data["scores"], key=lambda x: (-x["score"], x["time"]))[:40]
76
- safe_write_leaderboard(data)
77
-
78
- return f"Score: {score}/{len(SAMPLE_QUIZ)} — recorded. Good job!"
79
 
80
  def show_leaderboard():
81
- data = safe_read_leaderboard()
 
82
  rows = data.get("scores", [])[:10]
83
  if not rows:
84
  return "No scores yet."
@@ -87,7 +204,8 @@ def show_leaderboard():
87
  md += f"{i}. **{r['name']}** — {r['score']}/3 ({r['time'].split('T')[0]})\n\n"
88
  return md
89
 
90
- # ---- UI SETUP ----
 
91
  GLASS_CSS = """
92
  :root{
93
  --glass-bg: rgba(255,255,255,0.06);
@@ -95,31 +213,75 @@ GLASS_CSS = """
95
  --accent: #00aaff;
96
  }
97
  body { background: linear-gradient(135deg,#071028 0%, #0b1f3a 100%); color: #e6f0ff; }
98
- .gradio-container { font-family: 'Segoe UI', Roboto, Arial; }
99
- .card { background: var(--glass-bg); border: 1px solid var(--glass-border); box-shadow: 0 8px 30px rgba(2,6,23,0.6); border-radius: 12px; padding: 12px; }
100
- h1 { color: var(--accent); text-shadow: 0 3px 12px rgba(0,170,255,0.08); }
101
- a { color: #bfefff; text-decoration: none; }
102
- a:hover { text-decoration: underline; }
103
- .gr-button { background: linear-gradient(90deg,#00b4ff,#00ffa3)!important; color: #022 !important; font-weight:700; }
104
  """
105
 
106
  with gr.Blocks(css=GLASS_CSS, title="Road2Success —Dashboard") as app:
107
  gr.Markdown("<h1 style='text-align:center'>🚀 Road2Success — Dashboard</h1>")
108
- gr.Markdown("<p style='text-align:center;color:#1e81b0'>Professional roadmap, AI mentor, hackathon prep & leaderboard — Colab-ready</p>")
109
 
110
  with gr.Tabs():
111
- # (Other tabs unchanged...)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
- with gr.TabItem("🧠 Quiz Arena & Leaderboard"):
114
- gr.Markdown("Quick quiz — records score to leaderboard.")
115
- name_in = gr.Textbox(label="Your name for leaderboard", placeholder="e.g. Shiva Kumar")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  q1 = gr.Radio(SAMPLE_QUIZ[0][1], label=SAMPLE_QUIZ[0][0])
117
  q2 = gr.Radio(SAMPLE_QUIZ[1][1], label=SAMPLE_QUIZ[1][0])
118
  q3 = gr.Radio(SAMPLE_QUIZ[2][1], label=SAMPLE_QUIZ[2][0])
119
- submit_quiz = gr.Button("Submit Quiz & Save Score")
120
  result_box = gr.Textbox(label="Result")
121
  leaderboard_md = gr.Markdown(show_leaderboard())
122
  submit_quiz.click(fn=grade_and_record, inputs=[name_in, q1, q2, q3], outputs=result_box)
123
  submit_quiz.click(fn=lambda: gr.update(value=show_leaderboard()), outputs=leaderboard_md)
124
 
125
- app.launch(share=True)
 
 
 
 
 
 
 
4
  from bs4 import BeautifulSoup
5
  from transformers import pipeline
6
 
7
+
8
  # Store the leaderboard file in the current working directory
9
  LEADERBOARD_FILE = "road2success_leaderboard.json"
10
 
11
+ # Create the file if it doesn't exist (proper dict structure, not just list)
12
  if not os.path.exists(LEADERBOARD_FILE):
13
  with open(LEADERBOARD_FILE, "w") as f:
14
+ json.dump({"scores": []}, f)
15
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  _gen = None
18
  def get_generator():
19
  global _gen
20
  if _gen is None:
21
  try:
22
+ _gen = pipeline("text-generation", model="distilgpt2", device=-1) # CPU only
23
  except Exception as e:
24
  _gen = None
25
  print("Failed to load generator:", e)
 
30
  return "Ask a clear question about study plans, hackathons, or projects."
31
  gen = get_generator()
32
  if gen is None:
33
+ return "AI model failed to load. Try again later."
34
  modifier = ""
35
  if short_answer:
36
  modifier += " Provide a concise answer in <= 3 sentences."
 
38
  modifier += " Explain like I'm 5 (simple, clear language)."
39
  request = prompt.strip() + modifier
40
  out = gen(request, max_length=120, num_return_sequences=1)[0]["generated_text"]
41
+ return out.replace("\n", " ").strip()[:900]
42
+
43
+
44
+ # ------------------ ROADMAP DATA ------------------
45
+ ROADMAPS = {
46
+ "Class 5": {
47
+ "objective": "Spark curiosity, build number sense, foundations of reading, and light coding exposure.",
48
+ "subjects": [
49
+ "Math: number sense, addition/subtraction, basic fractions, time & money",
50
+ "Science: living things, plants, simple experiments",
51
+ "Language: reading, small essays, comprehension",
52
+ "Coding: block-based (Scratch) — basics of sequence & loops"
53
+ ],
54
+ "projects": ["Plant growth journal (measure & graph)", "Scratch storytelling animation"],
55
+ "resources": [("Khan Academy - Kids", "https://www.khanacademy.org/"), ("Code.org - Learn", "https://code.org/learn")],
56
+ "videos": [("Fun Science for Kids", "https://www.youtube.com/")],
57
+ "coding_questions": []
58
+ },
59
+ "Class 6": {
60
+ "objective": "Build curiosity, logical thinking, basic problem-solving and gentle programming.",
61
+ "subjects": ["Fractions, Decimals, Basic Geometry, Intro to Algebra", "Basics of Physics, Chemistry, Biology", "Scratch / Python Turtle basics"],
62
+ "projects": ["Simple games in Scratch", "Science fair volcano or plant growth"],
63
+ "resources": [("Khan Academy Math", "https://www.khanacademy.org/"), ("Scratch", "https://scratch.mit.edu/")],
64
+ "videos": [("Scratch for Beginners", "https://www.youtube.com/watch?v=jXUZaf5D12E")],
65
+ "coding_questions": []
66
+ },
67
+ # ... keep all other ROADMAPS (Class 7 → NEET) unchanged ...
68
+ }
69
+ # --------------------------------------------------
70
+
71
+ def render_roadmap(level):
72
+ info = ROADMAPS.get(level, None)
73
+ if not info:
74
+ return "<b>No roadmap available.</b>"
75
+ html = f"<div style='backdrop-filter: blur(6px); padding:16px; border-radius:12px;'>"
76
+ html += f"<h2 style='color:#00aaff'>{level} Roadmap</h2>"
77
+ html += f"<p><b>Objective:</b> {info.get('objective','-')}</p>"
78
+ html += "<b>Subjects:</b><ul>" + "".join(f"<li>{s}</li>" for s in info.get('subjects',[])) + "</ul>"
79
+ html += "<b>Projects:</b><ul>" + "".join(f"<li>{p}</li>" for p in info.get('projects',[])) + "</ul>"
80
+ if info.get("resources"):
81
+ html += "<b>Resources:</b><ul>" + "".join(f"<li><a href='{r[1]}' target='_blank'>{r[0]}</a></li>" for r in info.get('resources',[])) + "</ul>"
82
+ if info.get("videos"):
83
+ html += "<b>Videos:</b><ul>" + "".join(f"<li><a href='{v[1]}' target='_blank'>{v[0]}</a></li>" for v in info.get('videos',[])) + "</ul>"
84
+ if info.get("coding_questions"):
85
+ html += "<b>Coding Practice:</b><ul>" + "".join(f"<li><a href='{c[1]}' target='_blank'>{c[0]}</a></li>" for c in info.get('coding_questions',[])) + "</ul>"
86
+ html += "</div>"
87
+ return html
88
+
89
+ def generate_quick_plan(level, days=30):
90
+ base = ROADMAPS.get(level, None)
91
+ if not base:
92
+ return "No roadmap available."
93
+ subjects = base.get("subjects", [])
94
+ if not subjects:
95
+ return "No subjects found for this level."
96
+ weeks = max(1, days // 7)
97
+ plan = []
98
+ for w in range(weeks):
99
+ subj = subjects[w % len(subjects)]
100
+ plan.append(f"Week {w+1}: Focus on — {subj}. Practice exercises + 3 problems.")
101
+ return "<br>".join(plan)
102
+
103
+ def fetch_internships_remotive(query="intern"):
104
+ try:
105
+ r = requests.get(f"https://remotive.com/api/remote-jobs?search={query}&limit=20", timeout=6)
106
+ r.raise_for_status()
107
+ data = r.json().get("jobs", [])
108
+ out = ""
109
+ for j in data[:8]:
110
+ title = j.get("title","")
111
+ company = j.get("company_name","")
112
+ url = j.get("url","#")
113
+ out += f"• {title} at {company}\n{url}\n\n"
114
+ return out if out else "No internships found for this query."
115
+ except Exception as e:
116
+ return f"Internship fetch error: {e}"
117
+
118
+ def fetch_hackathons_devpost(keyword=""):
119
+ try:
120
+ r = requests.get("https://devpost.com/hackathons", timeout=6)
121
+ r.raise_for_status()
122
+ soup = BeautifulSoup(r.text, "html.parser")
123
+ titles = soup.select("h3.title") or soup.select("h5.title") or soup.find_all("h3")
124
+ results = []
125
+ for t in titles[:12]:
126
+ text = t.get_text(strip=True)
127
+ if not keyword or keyword.lower() in text.lower():
128
+ results.append("• " + text)
129
+ return "\n".join(results) if results else "No hackathons found."
130
+ except Exception as e:
131
+ return f"Hackathon fetch error: {e}"
132
+
133
+ def generate_pitch_pro(idea, team, impact_one_line):
134
+ if not idea:
135
+ return "Please provide a one-line idea."
136
+ team = team or "Team Road2Success"
137
+ impact = impact_one_line or "Solves user pain / high impact"
138
+ pitch = (
139
+ f"🔹 {team} — 60s Pitch\n\n"
140
+ f"**Idea:** {idea}\n\n"
141
+ f"**Problem:** {impact}\n\n"
142
+ f"**Solution (MVP):** One-sentence summary of the product.\n\n"
143
+ f"**Tech Stack:** Frontend (React/Gradio), Backend (FastAPI/Flask), ML (HuggingFace), DB (Firebase/Postgres)\n\n"
144
+ f"**Demo Flow:** Landing → Core feature → Impact screen\n\n"
145
+ f"**Why it wins:** Novel + demo-ready + measurable impact\n\n"
146
+ )
147
+ return pitch
148
 
149
+ def quick_checklist():
150
+ items = [
151
+ "✅ Finalize MVP scope (1 core feature)",
152
+ "✅ Repo + README + Start script",
153
+ "✅ Roles assigned",
154
+ "✅ Demo script + 1-minute pitch",
155
+ "✅ Deploy: HuggingFace/Colab",
156
+ "✅ Slides (3-5) + fallback video"
157
+ ]
158
+ return "\n".join(items)
159
+
160
+ def countdown_to(date_iso):
161
+ try:
162
+ t = datetime.datetime.fromisoformat(date_iso)
163
+ now = datetime.datetime.now()
164
+ diff = t - now
165
+ if diff.total_seconds() <= 0:
166
+ return "Date is in the past. Pick a future ISO date like 2025-10-01T18:00"
167
+ days = diff.days
168
+ hrs = diff.seconds // 3600
169
+ mins = (diff.seconds % 3600) // 60
170
+ return f"{days} days, {hrs} hours, {mins} minutes remaining"
171
+ except Exception:
172
+ return "Invalid date. Use ISO format: YYYY-MM-DDTHH:MM"
173
 
 
174
  SAMPLE_QUIZ = [
175
  ("What is the time complexity of binary search?", ["O(1)","O(n)","O(log n)","O(n log n)"], "O(log n)"),
176
  ("Which Python library is used for machine learning?", ["NumPy","scikit-learn","Pandas","Matplotlib"], "scikit-learn"),
 
181
  answers = [a1, a2, a3]
182
  correct = sum(1 for i, a in enumerate(answers) if a == SAMPLE_QUIZ[i][2])
183
  score = int(correct)
184
+ try:
185
+ with open(LEADERBOARD_FILE, "r") as f:
186
+ data = json.load(f)
187
+ except:
188
  data = {"scores": []}
 
189
  entry = {"name": name or "Anonymous", "score": score, "time": datetime.datetime.now().isoformat()}
190
  data["scores"].append(entry)
191
  data["scores"] = sorted(data["scores"], key=lambda x: (-x["score"], x["time"]))[:40]
192
+ with open(LEADERBOARD_FILE, "w") as f:
193
+ json.dump(data, f, indent=2)
194
+ return f"Score: {score}/{len(SAMPLE_QUIZ)} — recorded!"
195
 
196
  def show_leaderboard():
197
+ with open(LEADERBOARD_FILE, "r") as f:
198
+ data = json.load(f)
199
  rows = data.get("scores", [])[:10]
200
  if not rows:
201
  return "No scores yet."
 
204
  md += f"{i}. **{r['name']}** — {r['score']}/3 ({r['time'].split('T')[0]})\n\n"
205
  return md
206
 
207
+
208
+ # -------- UI --------
209
  GLASS_CSS = """
210
  :root{
211
  --glass-bg: rgba(255,255,255,0.06);
 
213
  --accent: #00aaff;
214
  }
215
  body { background: linear-gradient(135deg,#071028 0%, #0b1f3a 100%); color: #e6f0ff; }
 
 
 
 
 
 
216
  """
217
 
218
  with gr.Blocks(css=GLASS_CSS, title="Road2Success —Dashboard") as app:
219
  gr.Markdown("<h1 style='text-align:center'>🚀 Road2Success — Dashboard</h1>")
220
+ gr.Markdown("<p style='text-align:center;color:#1e81b0'>Professional roadmap, AI mentor, hackathon prep & leaderboard</p>")
221
 
222
  with gr.Tabs():
223
+ with gr.TabItem("📚 Roadmap"):
224
+ with gr.Row():
225
+ col1, col2 = gr.Column(scale=1), gr.Column(scale=2)
226
+ with col1:
227
+ level = gr.Dropdown(choices=list(ROADMAPS.keys()), value="Class 5", label="Select level")
228
+ quick_days = gr.Radio(choices=["30","60","90"], value="30", label="Days plan")
229
+ show_btn = gr.Button("Show Roadmap & Plan")
230
+ with col2:
231
+ roadmap_html = gr.HTML()
232
+ plan_html = gr.HTML()
233
+ show_btn.click(lambda l,d: (render_roadmap(l), generate_quick_plan(l, int(d))), inputs=[level, quick_days], outputs=[roadmap_html, plan_html])
234
+
235
+ with gr.TabItem("🤖 AI Mentor"):
236
+ prompt = gr.Textbox(label="Ask mentor", lines=3)
237
+ short_toggle = gr.Checkbox(label="Short answer", value=True)
238
+ eli5_toggle = gr.Checkbox(label="Explain simply (ELI5)", value=False)
239
+ ask_btn = gr.Button("Ask Mentor")
240
+ mentor_out = gr.Textbox(lines=6, label="Answer")
241
+ ask_btn.click(ai_mentor_query, inputs=[prompt, short_toggle, eli5_toggle], outputs=mentor_out)
242
 
243
+ with gr.TabItem("🏆 Hackathon Prep"):
244
+ idea_in = gr.Textbox(label="One-line idea")
245
+ team_in = gr.Textbox(label="Team name")
246
+ impact_in = gr.Textbox(label="Impact")
247
+ pitch_btn = gr.Button("Generate Pitch")
248
+ pitch_out = gr.Markdown()
249
+ pitch_btn.click(generate_pitch_pro, inputs=[idea_in, team_in, impact_in], outputs=pitch_out)
250
+
251
+ checklist_box = gr.Textbox(value=quick_checklist(), interactive=False, lines=6)
252
+ iso_date = gr.Textbox(label="Submission ISO date", value=(datetime.datetime.now()+datetime.timedelta(days=7)).isoformat(timespec='minutes'))
253
+ countdown_btn = gr.Button("Countdown")
254
+ countdown_out = gr.Textbox()
255
+ countdown_btn.click(countdown_to, inputs=iso_date, outputs=countdown_out)
256
+
257
+ with gr.TabItem("💼 Internships & Hackathons"):
258
+ with gr.Row():
259
+ with gr.Column():
260
+ intern_query = gr.Textbox(label="Internship search", value="intern")
261
+ intern_btn = gr.Button("Fetch Internships")
262
+ intern_out = gr.Textbox(lines=8)
263
+ with gr.Column():
264
+ hack_kw = gr.Textbox(label="Hackathon keyword", value="")
265
+ hack_btn = gr.Button("Fetch Hackathons")
266
+ hack_out = gr.Textbox(lines=8)
267
+ intern_btn.click(fetch_internships_remotive, inputs=intern_query, outputs=intern_out)
268
+ hack_btn.click(fetch_hackathons_devpost, inputs=hack_kw, outputs=hack_out)
269
+
270
+ with gr.TabItem("🧠 Quiz & Leaderboard"):
271
+ name_in = gr.Textbox(label="Your name")
272
  q1 = gr.Radio(SAMPLE_QUIZ[0][1], label=SAMPLE_QUIZ[0][0])
273
  q2 = gr.Radio(SAMPLE_QUIZ[1][1], label=SAMPLE_QUIZ[1][0])
274
  q3 = gr.Radio(SAMPLE_QUIZ[2][1], label=SAMPLE_QUIZ[2][0])
275
+ submit_quiz = gr.Button("Submit Quiz")
276
  result_box = gr.Textbox(label="Result")
277
  leaderboard_md = gr.Markdown(show_leaderboard())
278
  submit_quiz.click(fn=grade_and_record, inputs=[name_in, q1, q2, q3], outputs=result_box)
279
  submit_quiz.click(fn=lambda: gr.update(value=show_leaderboard()), outputs=leaderboard_md)
280
 
281
+
282
+ if __name__ == "__main__":
283
+ app.launch(
284
+ server_name="0.0.0.0",
285
+ server_port=int(os.environ.get("PORT", 7860)),
286
+ debug=True
287
+ )