krish-ai-dev commited on
Commit
e36f9bd
·
verified ·
1 Parent(s): 3de95a5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -33
app.py CHANGED
@@ -1,5 +1,7 @@
1
  import os
2
  import time
 
 
3
  from datetime import datetime
4
  import gradio as gr
5
  from google import genai
@@ -34,10 +36,10 @@ def get_greeting():
34
  elif h < 17: return "Good afternoon 👋"
35
  else: return "Good evening 👋"
36
 
37
- # ── Gemini Stream Logic ──
38
  def predict(message, history, subject_id, file_input):
39
  if not client:
40
- yield "⚠️ Please add GEMINI_API_KEY in Space Settings -> Secrets."
41
  return
42
 
43
  subj = next((s["label"] for s in SUBJECTS if s["id"] == subject_id), "General Studies")
@@ -45,12 +47,12 @@ def predict(message, history, subject_id, file_input):
45
 
46
  formatted_contents = []
47
  if history:
48
- for msg in history:
49
- if isinstance(msg, dict) and "role" in msg and "content" in msg:
50
- role = "user" if msg["role"] == "user" else "model"
51
- text = msg["content"]
52
- if text:
53
- formatted_contents.append(types.Content(role=role, parts=[types.Part.from_text(str(text))]))
54
 
55
  current_parts = [types.Part.from_text(message)]
56
 
@@ -89,36 +91,36 @@ def predict(message, history, subject_id, file_input):
89
  except Exception as e:
90
  yield f"An error occurred: {str(e)}"
91
 
92
- # ── Generators ──
93
  def generate_quiz(subject_id):
94
- if not client: return "⚠️ Please add GEMINI_API_KEY in Space Settings."
95
  subj = next((s["label"] for s in SUBJECTS if s["id"] == subject_id), "General Studies")
96
  prompt = f"Generate a 3-question multiple choice quiz about {subj} with answers at the bottom. Format beautifully with markdown."
97
  try:
98
  response = client.models.generate_content(model='gemini-2.5-flash', contents=prompt)
99
  return response.text
100
  except Exception as e:
101
- return f"Error: {str(e)}"
102
 
103
  def generate_notes(history, subject_id):
104
- if not client: return "⚠️ Please add GEMINI_API_KEY in Space Settings."
105
  subj = next((s["label"] for s in SUBJECTS if s["id"] == subject_id), "General Studies")
106
- prompt = f"Based on this study history for {subj}: {str(history)}. Create structured summary revision notes."
107
  try:
108
  response = client.models.generate_content(model='gemini-2.5-flash', contents=prompt)
109
  return response.text
110
  except Exception as e:
111
- return f"Error: {str(e)}"
112
 
113
  def generate_flashcards(history, subject_id):
114
- if not client: return "⚠️ Please add GEMINI_API_KEY in Space Settings."
115
  subj = next((s["label"] for s in SUBJECTS if s["id"] == subject_id), "General Studies")
116
- prompt = f"Based on this study history for {subj}: {str(history)}. Generate 4 interactive flashcards."
117
  try:
118
  response = client.models.generate_content(model='gemini-2.5-flash', contents=prompt)
119
  return response.text
120
  except Exception as e:
121
- return f"Error: {str(e)}"
122
 
123
  # ── Gradio UI Construction ──
124
  with gr.Blocks() as demo:
@@ -128,7 +130,7 @@ with gr.Blocks() as demo:
128
  # SIDEBAR
129
  with gr.Column(scale=1, min_width=280):
130
  gr.Markdown("## ⚡ StudyAI Dashboard")
131
- gr.Markdown(f"*{get_greeting()}*")
132
 
133
  subject_dropdown = gr.Dropdown(
134
  choices=[(s["label"] + " " + s["emoji"], s["id"]) for s in SUBJECTS],
@@ -139,10 +141,10 @@ with gr.Blocks() as demo:
139
 
140
  gr.Markdown("---")
141
  gr.Markdown("⏱️ **Focus Pomodoro Timer**")
142
- pomo_display = gr.HTML("<div style='font-size:24px; font-weight:bold; text-align:center;'>25:00</div>")
143
  with gr.Row():
144
- start_btn = gr.Button("▶️ Start", size="sm")
145
- reset_btn = gr.Button("⏹️ Reset", size="sm")
146
 
147
  gr.Markdown("---")
148
  gr.Markdown("📝 **Todo Checklist**")
@@ -153,7 +155,7 @@ with gr.Blocks() as demo:
153
  new_todo = gr.Textbox(placeholder="+ Add custom task & press Enter", show_label=False)
154
 
155
  def add_todo(task, current_todos):
156
- if task and task.strip():
157
  current_todos.append(task.strip())
158
  return gr.update(choices=current_todos, value=current_todos), ""
159
  new_todo.submit(add_todo, [new_todo, todo_list], [todo_list, new_todo])
@@ -168,15 +170,16 @@ with gr.Blocks() as demo:
168
 
169
  suggestion_box = gr.Radio(
170
  choices=SUGGESTIONS["math"],
171
- label="💡 Instant Suggestions",
172
  interactive=True
173
  )
174
 
175
- file_upload = gr.File(label="📂 Upload Study Material (PDF)", file_types=[".pdf"])
176
- chatbot = gr.Chatbot(height=400, type="messages")
177
 
178
  with gr.Row():
179
  msg_input = gr.Textbox(placeholder="Ask anything...", scale=4, show_label=False)
 
180
  submit_btn = gr.Button("Send 🚀", variant="primary", scale=1)
181
 
182
  def update_subject_view(sub_id):
@@ -191,20 +194,28 @@ with gr.Blocks() as demo:
191
  outputs=[subject_info_banner, suggestion_box, current_subject_id, chatbot]
192
  )
193
 
194
- suggestion_box.select(lambda evt: evt.value, outputs=[msg_input])
 
 
 
 
 
 
195
 
196
  def respond(message, chat_history, sub_id, pdf_file):
197
  if not message or not message.strip():
198
- yield "", chat_history
199
- return
200
 
201
- chat_history = list(chat_history or [])
202
- chat_history.append({"role": "user", "content": message})
203
- chat_history.append({"role": "assistant", "content": ""})
204
 
205
- history_for_api = chat_history[:-2]
 
 
 
206
 
207
- for chunk in predict(message, history_for_api, sub_id, pdf_file):
208
  chat_history[-1]["content"] = chunk
209
  yield "", chat_history
210
 
 
1
  import os
2
  import time
3
+ import json
4
+ import base64
5
  from datetime import datetime
6
  import gradio as gr
7
  from google import genai
 
36
  elif h < 17: return "Good afternoon 👋"
37
  else: return "Good evening 👋"
38
 
39
+ # ── Gemini Stream & Logic Functions ──
40
  def predict(message, history, subject_id, file_input):
41
  if not client:
42
+ yield "⚠️ Please configure GEMINI_API_KEY in your Hugging Face Space secrets."
43
  return
44
 
45
  subj = next((s["label"] for s in SUBJECTS if s["id"] == subject_id), "General Studies")
 
47
 
48
  formatted_contents = []
49
  if history:
50
+ for turn in history:
51
+ if isinstance(turn, dict):
52
+ formatted_contents.append(types.Content(role=turn.get("role", "user"), parts=[types.Part.from_text(str(turn.get("content", "")))]))
53
+ elif isinstance(turn, (list, tuple)) and len(turn) >= 2:
54
+ if turn[0]: formatted_contents.append(types.Content(role="user", parts=[types.Part.from_text(str(turn[0]))]))
55
+ if turn[1]: formatted_contents.append(types.Content(role="model", parts=[types.Part.from_text(str(turn[1]))]))
56
 
57
  current_parts = [types.Part.from_text(message)]
58
 
 
91
  except Exception as e:
92
  yield f"An error occurred: {str(e)}"
93
 
94
+ # ── Dynamic Features Generators ──
95
  def generate_quiz(subject_id):
96
+ if not client: return "API key missing."
97
  subj = next((s["label"] for s in SUBJECTS if s["id"] == subject_id), "General Studies")
98
  prompt = f"Generate a 3-question multiple choice quiz about {subj} with answers at the bottom. Format beautifully with markdown."
99
  try:
100
  response = client.models.generate_content(model='gemini-2.5-flash', contents=prompt)
101
  return response.text
102
  except Exception as e:
103
+ return f"Error generating quiz: {str(e)}"
104
 
105
  def generate_notes(history, subject_id):
106
+ if not client: return "API key missing."
107
  subj = next((s["label"] for s in SUBJECTS if s["id"] == subject_id), "General Studies")
108
+ prompt = f"Based on this study history for {subj}: {str(history)}. Create highly structured, clean summary revision notes with key bullet points."
109
  try:
110
  response = client.models.generate_content(model='gemini-2.5-flash', contents=prompt)
111
  return response.text
112
  except Exception as e:
113
+ return f"Error generating notes: {str(e)}"
114
 
115
  def generate_flashcards(history, subject_id):
116
+ if not client: return "API key missing."
117
  subj = next((s["label"] for s in SUBJECTS if s["id"] == subject_id), "General Studies")
118
+ prompt = f"Based on this study history for {subj}: {str(history)}. Generate 4 interactive flashcards formatted as 'Question: [Text] | Answer: [Text]'."
119
  try:
120
  response = client.models.generate_content(model='gemini-2.5-flash', contents=prompt)
121
  return response.text
122
  except Exception as e:
123
+ return f"Error generating flashcards: {str(e)}"
124
 
125
  # ── Gradio UI Construction ──
126
  with gr.Blocks() as demo:
 
130
  # SIDEBAR
131
  with gr.Column(scale=1, min_width=280):
132
  gr.Markdown("## ⚡ StudyAI Dashboard")
133
+ greeting_md = gr.Markdown(f"*{get_greeting()}*")
134
 
135
  subject_dropdown = gr.Dropdown(
136
  choices=[(s["label"] + " " + s["emoji"], s["id"]) for s in SUBJECTS],
 
141
 
142
  gr.Markdown("---")
143
  gr.Markdown("⏱️ **Focus Pomodoro Timer**")
144
+ gr.HTML("<div style='font-size:24px; font-weight:bold; text-align:center;'>25:00</div>")
145
  with gr.Row():
146
+ gr.Button("▶️ Start", size="sm")
147
+ gr.Button("⏹️ Reset", size="sm")
148
 
149
  gr.Markdown("---")
150
  gr.Markdown("📝 **Todo Checklist**")
 
155
  new_todo = gr.Textbox(placeholder="+ Add custom task & press Enter", show_label=False)
156
 
157
  def add_todo(task, current_todos):
158
+ if task and task.strip():
159
  current_todos.append(task.strip())
160
  return gr.update(choices=current_todos, value=current_todos), ""
161
  new_todo.submit(add_todo, [new_todo, todo_list], [todo_list, new_todo])
 
170
 
171
  suggestion_box = gr.Radio(
172
  choices=SUGGESTIONS["math"],
173
+ label="💡 Instant Suggestions (Click to choose, then type or send)",
174
  interactive=True
175
  )
176
 
177
+ file_upload = gr.File(label="📂 Upload Study Material (PDF up to 50MB)", file_types=[".pdf"])
178
+ chatbot = gr.Chatbot(height=400)
179
 
180
  with gr.Row():
181
  msg_input = gr.Textbox(placeholder="Ask anything...", scale=4, show_label=False)
182
+ audio_input = gr.Audio(sources=["microphone"], type="filepath", label="🎙️ Voice", scale=1)
183
  submit_btn = gr.Button("Send 🚀", variant="primary", scale=1)
184
 
185
  def update_subject_view(sub_id):
 
194
  outputs=[subject_info_banner, suggestion_box, current_subject_id, chatbot]
195
  )
196
 
197
+ suggestion_box.select(lambda x: x.value, inputs=[suggestion_box], outputs=[msg_input])
198
+
199
+ def handle_audio(audio_path):
200
+ if audio_path:
201
+ return "[Voice Note Uploaded: Analyzing audio content]"
202
+ return ""
203
+ audio_input.change(handle_audio, inputs=[audio_input], outputs=[msg_input])
204
 
205
  def respond(message, chat_history, sub_id, pdf_file):
206
  if not message or not message.strip():
207
+ return "", chat_history
 
208
 
209
+ chat_history = chat_history or []
210
+ chat_history.append({"role": "user", "metadata": {"title": ""}, "content": message})
211
+ chat_history.append({"role": "assistant", "metadata": {"title": ""}, "content": ""})
212
 
213
+ raw_history = []
214
+ for i in range(0, len(chat_history)-2, 2):
215
+ if i+1 < len(chat_history):
216
+ raw_history.append((chat_history[i]["content"], chat_history[i+1]["content"]))
217
 
218
+ for chunk in predict(message, raw_history, sub_id, pdf_file):
219
  chat_history[-1]["content"] = chunk
220
  yield "", chat_history
221