Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,5 @@
|
|
| 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,10 +34,10 @@ def get_greeting():
|
|
| 36 |
elif h < 17: return "Good afternoon 👋"
|
| 37 |
else: return "Good evening 👋"
|
| 38 |
|
| 39 |
-
# ── Gemini Stream
|
| 40 |
def predict(message, history, subject_id, file_input):
|
| 41 |
if not client:
|
| 42 |
-
yield "⚠️ Please
|
| 43 |
return
|
| 44 |
|
| 45 |
subj = next((s["label"] for s in SUBJECTS if s["id"] == subject_id), "General Studies")
|
|
@@ -47,12 +45,12 @@ def predict(message, history, subject_id, file_input):
|
|
| 47 |
|
| 48 |
formatted_contents = []
|
| 49 |
if history:
|
| 50 |
-
for
|
| 51 |
-
if isinstance(
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
if
|
| 55 |
-
|
| 56 |
|
| 57 |
current_parts = [types.Part.from_text(message)]
|
| 58 |
|
|
@@ -91,36 +89,36 @@ def predict(message, history, subject_id, file_input):
|
|
| 91 |
except Exception as e:
|
| 92 |
yield f"An error occurred: {str(e)}"
|
| 93 |
|
| 94 |
-
# ──
|
| 95 |
def generate_quiz(subject_id):
|
| 96 |
-
if not client: return "
|
| 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
|
| 104 |
|
| 105 |
def generate_notes(history, subject_id):
|
| 106 |
-
if not client: return "
|
| 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
|
| 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
|
| 114 |
|
| 115 |
def generate_flashcards(history, subject_id):
|
| 116 |
-
if not client: return "
|
| 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
|
| 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
|
| 124 |
|
| 125 |
# ── Gradio UI Construction ──
|
| 126 |
with gr.Blocks() as demo:
|
|
@@ -130,7 +128,7 @@ with gr.Blocks() as demo:
|
|
| 130 |
# SIDEBAR
|
| 131 |
with gr.Column(scale=1, min_width=280):
|
| 132 |
gr.Markdown("## ⚡ StudyAI Dashboard")
|
| 133 |
-
|
| 134 |
|
| 135 |
subject_dropdown = gr.Dropdown(
|
| 136 |
choices=[(s["label"] + " " + s["emoji"], s["id"]) for s in SUBJECTS],
|
|
@@ -141,10 +139,10 @@ with gr.Blocks() as demo:
|
|
| 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,7 +153,7 @@ with gr.Blocks() as demo:
|
|
| 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,16 +168,15 @@ with gr.Blocks() as demo:
|
|
| 170 |
|
| 171 |
suggestion_box = gr.Radio(
|
| 172 |
choices=SUGGESTIONS["math"],
|
| 173 |
-
label="💡 Instant Suggestions
|
| 174 |
interactive=True
|
| 175 |
)
|
| 176 |
|
| 177 |
-
file_upload = gr.File(label="📂 Upload Study Material (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,28 +191,20 @@ with gr.Blocks() as demo:
|
|
| 194 |
outputs=[subject_info_banner, suggestion_box, current_subject_id, chatbot]
|
| 195 |
)
|
| 196 |
|
| 197 |
-
suggestion_box.select(lambda
|
| 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 |
-
|
|
|
|
| 208 |
|
| 209 |
-
chat_history = chat_history or []
|
| 210 |
-
chat_history.append({"role": "user", "
|
| 211 |
-
chat_history.append({"role": "assistant", "
|
| 212 |
|
| 213 |
-
|
| 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,
|
| 219 |
chat_history[-1]["content"] = chunk
|
| 220 |
yield "", chat_history
|
| 221 |
|
|
|
|
| 1 |
import os
|
| 2 |
import time
|
|
|
|
|
|
|
| 3 |
from datetime import datetime
|
| 4 |
import gradio as gr
|
| 5 |
from google import genai
|
|
|
|
| 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 |
|
| 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 |
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 |
# 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 |
|
| 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 |
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 |
|
| 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 |
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 |
|