Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,14 +1,14 @@
|
|
| 1 |
-
import os, json,
|
| 2 |
import gradio as gr
|
| 3 |
from openai import OpenAI
|
| 4 |
|
| 5 |
# ==================== LLM config ====================
|
| 6 |
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
|
| 7 |
DEEPSEEK_BASE_URL = os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com/v1")
|
| 8 |
-
DEEPSEEK_MODEL = os.getenv("DEEPSEEK_MODEL", "
|
| 9 |
|
| 10 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 11 |
-
OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-
|
| 12 |
|
| 13 |
# ==================== Google Sheets config ====================
|
| 14 |
SVC_JSON = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON") # whole JSON as a single string
|
|
@@ -74,41 +74,46 @@ Return ONLY valid JSON with this EXACT structure:
|
|
| 74 |
"""
|
| 75 |
|
| 76 |
# ==================== LLM Bridge (DeepSeek β OpenAI) ====================
|
| 77 |
-
def llm_chat(messages
|
| 78 |
"""
|
| 79 |
Try DeepSeek first; on error, fallback to OpenAI.
|
| 80 |
Returns (content, model_used_str).
|
|
|
|
| 81 |
"""
|
| 82 |
-
|
| 83 |
-
if
|
| 84 |
try:
|
| 85 |
ds = OpenAI(api_key=DEEPSEEK_API_KEY, base_url=DEEPSEEK_BASE_URL)
|
| 86 |
resp = ds.chat.completions.create(model=DEEPSEEK_MODEL, messages=messages)
|
| 87 |
return resp.choices[0].message.content, f"DeepSeek ({DEEPSEEK_MODEL})"
|
| 88 |
except Exception as e:
|
| 89 |
-
|
|
|
|
| 90 |
|
|
|
|
| 91 |
if OPENAI_API_KEY:
|
| 92 |
try:
|
| 93 |
oa = OpenAI(api_key=OPENAI_API_KEY)
|
| 94 |
resp = oa.chat.completions.create(model=OPENAI_MODEL, messages=messages)
|
| 95 |
return resp.choices[0].message.content, f"OpenAI ({OPENAI_MODEL})"
|
| 96 |
except Exception as e:
|
| 97 |
-
|
| 98 |
|
| 99 |
-
|
| 100 |
-
raise RuntimeError("No API key found. Set DEEPSEEK_API_KEY and/or OPENAI_API_KEY as Secrets.")
|
| 101 |
-
raise RuntimeError(f"Both DeepSeek and OpenAI calls failed. Last error: {last_err}")
|
| 102 |
|
| 103 |
# ==================== Helpers ====================
|
| 104 |
def salvage_json(s: str) -> dict:
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
try:
|
| 107 |
return json.loads(s)
|
| 108 |
except json.JSONDecodeError:
|
| 109 |
m = re.search(r"\{.*\}\s*$", s, flags=re.S)
|
| 110 |
if not m:
|
| 111 |
-
raise ValueError("Model did not return valid JSON
|
| 112 |
return json.loads(m.group(0))
|
| 113 |
|
| 114 |
def stars_bar(value: float | int | None, max_stars: int = 5) -> str:
|
|
@@ -172,16 +177,8 @@ def apply_corrections_by_offsets(text: str, issues: list[dict]) -> str:
|
|
| 172 |
|
| 173 |
# ==================== Google Sheets writer ====================
|
| 174 |
def append_to_sheet(row: list) -> str:
|
| 175 |
-
"""
|
| 176 |
-
Appends a row to the configured worksheet.
|
| 177 |
-
Row order:
|
| 178 |
-
[timestamp, name, class, title, word_count, knows_story,
|
| 179 |
-
comprehension, expression, reflection, length_stars,
|
| 180 |
-
grammar_mistakes, grammar_stars, average_stars, model_used, remarks]
|
| 181 |
-
"""
|
| 182 |
if not (SVC_JSON and SHEET_ID and WS_ID):
|
| 183 |
return "Sheets not configured (missing GOOGLE_SERVICE_ACCOUNT_JSON / SHEETS_SPREADSHEET_ID / SHEETS_WORKSHEET_ID)."
|
| 184 |
-
|
| 185 |
try:
|
| 186 |
import gspread
|
| 187 |
from google.oauth2.service_account import Credentials
|
|
@@ -207,42 +204,30 @@ Welcome to the **Summary Grader** π
|
|
| 207 |
Hereβs how Iβll read and mark your story:
|
| 208 |
|
| 209 |
1. **Comprehension** β Did you really understand the story or movie?
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
βοΈ *Tip:* Use short sentences, correct punctuation, and connect ideas.
|
| 214 |
-
|
| 215 |
-
3. **Reflection / Moral** β What lesson or idea did you take away?
|
| 216 |
-
βοΈ *Tip:* Write one or two sentences about what it means to you.
|
| 217 |
-
|
| 218 |
-
4. **Grammar & Neatness** β Spelling, punctuation, and correctness.
|
| 219 |
-
βοΈ *Tip:* Read aloud once to catch small mistakes.
|
| 220 |
-
|
| 221 |
5. **Length** β Iβll count your words:
|
| 222 |
-
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
- **200β250 β 4β**
|
| 226 |
-
- **250+ β 5β**
|
| 227 |
-
|
| 228 |
-
π Try your best: write neatly, think deeply, and explain clearly.
|
| 229 |
-
When youβre ready, paste your story below and press **Grade & Save!**
|
| 230 |
"""
|
| 231 |
|
| 232 |
# ==================== Core grading ====================
|
| 233 |
def grade_summary(student_name: str, student_class: str, title: str, student_summary: str):
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
|
|
|
| 246 |
TITLE: {title}
|
| 247 |
|
| 248 |
STUDENT SUMMARY (ORIGINAL TEXT BELOW):
|
|
@@ -252,106 +237,113 @@ STUDENT SUMMARY (ORIGINAL TEXT BELOW):
|
|
| 252 |
|
| 253 |
{JSON_SCHEMA_HINT}
|
| 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 |
-
vals
|
| 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 |
# ==================== UI ====================
|
| 353 |
-
with gr.Blocks(title="Summary Grader
|
| 354 |
-
gr.Markdown("## Summary Grader
|
| 355 |
|
| 356 |
with gr.Row():
|
| 357 |
student_name = gr.Textbox(label="Student Name", placeholder="Riya Sen")
|
|
@@ -377,6 +369,5 @@ with gr.Blocks(title="Summary Grader (DeepSeek β OpenAI) + Google Sheets") as
|
|
| 377 |
inputs=[student_name, student_class, title_in, summary_in],
|
| 378 |
outputs=[report_out, corrected_out, status_out])
|
| 379 |
|
| 380 |
-
# Entrypoint for Spaces
|
| 381 |
if __name__ == "__main__":
|
| 382 |
demo.launch()
|
|
|
|
| 1 |
+
import os, json, re, time
|
| 2 |
import gradio as gr
|
| 3 |
from openai import OpenAI
|
| 4 |
|
| 5 |
# ==================== LLM config ====================
|
| 6 |
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
|
| 7 |
DEEPSEEK_BASE_URL = os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com/v1")
|
| 8 |
+
DEEPSEEK_MODEL = os.getenv("DEEPSEEK_MODEL", "deepseek-chat") # <-- public model id
|
| 9 |
|
| 10 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 11 |
+
OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o-mini") # faster fallback than gpt-5
|
| 12 |
|
| 13 |
# ==================== Google Sheets config ====================
|
| 14 |
SVC_JSON = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON") # whole JSON as a single string
|
|
|
|
| 74 |
"""
|
| 75 |
|
| 76 |
# ==================== LLM Bridge (DeepSeek β OpenAI) ====================
|
| 77 |
+
def llm_chat(messages):
|
| 78 |
"""
|
| 79 |
Try DeepSeek first; on error, fallback to OpenAI.
|
| 80 |
Returns (content, model_used_str).
|
| 81 |
+
Raises with clear reason if both fail.
|
| 82 |
"""
|
| 83 |
+
# DeepSeek first
|
| 84 |
+
if DEEPSEEK_API_KEY:
|
| 85 |
try:
|
| 86 |
ds = OpenAI(api_key=DEEPSEEK_API_KEY, base_url=DEEPSEEK_BASE_URL)
|
| 87 |
resp = ds.chat.completions.create(model=DEEPSEEK_MODEL, messages=messages)
|
| 88 |
return resp.choices[0].message.content, f"DeepSeek ({DEEPSEEK_MODEL})"
|
| 89 |
except Exception as e:
|
| 90 |
+
# Attach model & base details so we can see the exact failure in UI
|
| 91 |
+
raise RuntimeError(f"DeepSeek call failed [{DEEPSEEK_MODEL} @ {DEEPSEEK_BASE_URL}]: {e}")
|
| 92 |
|
| 93 |
+
# OpenAI fallback
|
| 94 |
if OPENAI_API_KEY:
|
| 95 |
try:
|
| 96 |
oa = OpenAI(api_key=OPENAI_API_KEY)
|
| 97 |
resp = oa.chat.completions.create(model=OPENAI_MODEL, messages=messages)
|
| 98 |
return resp.choices[0].message.content, f"OpenAI ({OPENAI_MODEL})"
|
| 99 |
except Exception as e:
|
| 100 |
+
raise RuntimeError(f"OpenAI call failed [{OPENAI_MODEL}]: {e}")
|
| 101 |
|
| 102 |
+
raise RuntimeError("No LLM API available. Set DEEPSEEK_* or OPENAI_* secrets.")
|
|
|
|
|
|
|
| 103 |
|
| 104 |
# ==================== Helpers ====================
|
| 105 |
def salvage_json(s: str) -> dict:
|
| 106 |
+
"""
|
| 107 |
+
Try to parse JSON; if the model returned extra text, extract the last {...} block.
|
| 108 |
+
Also normalizes smart quotes (sometimes models emit them).
|
| 109 |
+
"""
|
| 110 |
+
s = s.strip().replace("β", "\"").replace("β", "\"").replace("β", "'")
|
| 111 |
try:
|
| 112 |
return json.loads(s)
|
| 113 |
except json.JSONDecodeError:
|
| 114 |
m = re.search(r"\{.*\}\s*$", s, flags=re.S)
|
| 115 |
if not m:
|
| 116 |
+
raise ValueError("Model did not return valid JSON:\n" + s[:500])
|
| 117 |
return json.loads(m.group(0))
|
| 118 |
|
| 119 |
def stars_bar(value: float | int | None, max_stars: int = 5) -> str:
|
|
|
|
| 177 |
|
| 178 |
# ==================== Google Sheets writer ====================
|
| 179 |
def append_to_sheet(row: list) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
if not (SVC_JSON and SHEET_ID and WS_ID):
|
| 181 |
return "Sheets not configured (missing GOOGLE_SERVICE_ACCOUNT_JSON / SHEETS_SPREADSHEET_ID / SHEETS_WORKSHEET_ID)."
|
|
|
|
| 182 |
try:
|
| 183 |
import gspread
|
| 184 |
from google.oauth2.service_account import Credentials
|
|
|
|
| 204 |
Hereβs how Iβll read and mark your story:
|
| 205 |
|
| 206 |
1. **Comprehension** β Did you really understand the story or movie?
|
| 207 |
+
2. **Expression** β Is your writing clear and smooth?
|
| 208 |
+
3. **Reflection / Moral** β What did you learn or feel?
|
| 209 |
+
4. **Grammar & Neatness** β Spelling and punctuation.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
5. **Length** β Iβll count your words:
|
| 211 |
+
- <100 β 0β, 100β150 β 1β, 150β200 β 3β, 200β250 β 4β, 250+ β 5β
|
| 212 |
+
|
| 213 |
+
Write neatly, think deeply, and paste your story below. Then press **Grade & Save!**
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
"""
|
| 215 |
|
| 216 |
# ==================== Core grading ====================
|
| 217 |
def grade_summary(student_name: str, student_class: str, title: str, student_summary: str):
|
| 218 |
+
try:
|
| 219 |
+
if not student_name.strip():
|
| 220 |
+
return "β οΈ Please enter the student's name.", "", ""
|
| 221 |
+
if not student_class.strip():
|
| 222 |
+
return "β οΈ Please enter the class/grade.", "", ""
|
| 223 |
+
if not title.strip():
|
| 224 |
+
return "β οΈ Please enter a title.", "", ""
|
| 225 |
+
if not student_summary.strip():
|
| 226 |
+
return "β οΈ Please paste the student's summary.", "", ""
|
| 227 |
+
if len(student_summary) > MAX_CHARS:
|
| 228 |
+
return f"β οΈ Summary too long ({len(student_summary)} chars). Limit is {MAX_CHARS}.", "", ""
|
| 229 |
+
|
| 230 |
+
prompt = f"""
|
| 231 |
TITLE: {title}
|
| 232 |
|
| 233 |
STUDENT SUMMARY (ORIGINAL TEXT BELOW):
|
|
|
|
| 237 |
|
| 238 |
{JSON_SCHEMA_HINT}
|
| 239 |
"""
|
| 240 |
+
# LLM call (now raises with explicit reason if it fails)
|
| 241 |
+
content, model_used = llm_chat([{"role": "user", "content": prompt}])
|
| 242 |
+
|
| 243 |
+
# Parse JSON (robust)
|
| 244 |
+
data = salvage_json(content)
|
| 245 |
+
|
| 246 |
+
# Extract
|
| 247 |
+
knows_story = bool(data.get("knows_story", False))
|
| 248 |
+
scores = data.get("scores", {}) or {}
|
| 249 |
+
comp = scores.get("Comprehension", None)
|
| 250 |
+
expr = clamp_1_to_5(scores.get("Expression", 1))
|
| 251 |
+
refl = clamp_1_to_5(scores.get("Reflection/Moral Takeaway", 1))
|
| 252 |
+
issues = data.get("grammar_issues", []) or []
|
| 253 |
+
corrected = (data.get("corrected_summary") or "").strip()
|
| 254 |
+
remarks = (data.get("remarks") or "").strip()
|
| 255 |
+
if not knows_story:
|
| 256 |
+
comp = None
|
| 257 |
+
|
| 258 |
+
wc = count_words(student_summary)
|
| 259 |
+
len_s = length_stars(wc)
|
| 260 |
+
grammar_count = len(issues)
|
| 261 |
+
grammar_star = round(grammar_stars_from_count(grammar_count), 1)
|
| 262 |
+
|
| 263 |
+
vals = [float(expr), float(refl), float(len_s), float(grammar_star)]
|
| 264 |
+
if knows_story and comp is not None:
|
| 265 |
+
vals.append(float(comp))
|
| 266 |
+
avg = round(sum(vals) / len(vals), 2) if vals else 0.0
|
| 267 |
+
|
| 268 |
+
# Build report
|
| 269 |
+
md = []
|
| 270 |
+
md.append(f"### π Summary Grading Report")
|
| 271 |
+
md.append(f"**Name:** {student_name} **Class:** {student_class}")
|
| 272 |
+
md.append(f"**Title:** {title}")
|
| 273 |
+
md.append(f"**Word count:** {wc}")
|
| 274 |
+
md.append("")
|
| 275 |
+
md.append("#### β Category-wise Scores")
|
| 276 |
+
if knows_story and comp is not None:
|
| 277 |
+
md.append(f"- **Comprehension:** {stars_bar(comp)} ({comp} stars)")
|
| 278 |
+
else:
|
| 279 |
+
md.append(f"- **Comprehension:** *(omitted)*")
|
| 280 |
+
md.append(f"- **Expression:** {stars_bar(expr)} ({expr} stars)")
|
| 281 |
+
md.append(f"- **Reflection/Moral Takeaway:** {stars_bar(refl)} ({refl} stars)")
|
| 282 |
+
md.append(f"- **Length:** {stars_bar(len_s)} ({len_s} stars, based on {wc} words)")
|
| 283 |
+
md.append(f"- **Grammar:** {stars_bar(grammar_star)} ({grammar_star:.1f} stars, {grammar_count} mistakes)")
|
| 284 |
+
md.append("")
|
| 285 |
+
md.append(f"**Average Score:** {avg:.2f} {stars_bar(avg)} *(out of 5)*")
|
| 286 |
+
md.append("")
|
| 287 |
+
md.append("#### βοΈ Corrected Passage (LLM, minimal edits)")
|
| 288 |
+
md.append(f"{corrected if corrected else '_(No changes returned by the model.)_'}")
|
| 289 |
+
md.append("")
|
| 290 |
+
md.append("#### π Annotated Original (exact mistake spans)")
|
| 291 |
+
annotated = annotate_original_with_issues(student_summary, issues)
|
| 292 |
+
md.append(f"{annotated}")
|
| 293 |
+
md.append("")
|
| 294 |
+
md.append("#### π§Ή Grammar Issues (original β corrected)")
|
| 295 |
+
if not issues:
|
| 296 |
+
md.append("- None π")
|
| 297 |
+
else:
|
| 298 |
+
for i, it in enumerate(issues, 1):
|
| 299 |
+
err = (it.get('error_excerpt') or '').strip()
|
| 300 |
+
cor = (it.get('correction') or '').strip()
|
| 301 |
+
why = (it.get('explanation') or '').strip()
|
| 302 |
+
si = it.get('start_index', '?')
|
| 303 |
+
ei = it.get('end_index', '?')
|
| 304 |
+
md.append(f"{i}. `[{si}:{ei}]` **{err}** β **{cor}** β {why}")
|
| 305 |
+
md.append("")
|
| 306 |
+
md.append(f"*Graded using:* **{model_used}**")
|
| 307 |
+
md_str = "\n".join(md)
|
| 308 |
+
|
| 309 |
+
# Append to Google Sheet
|
| 310 |
+
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
|
| 311 |
+
row = [
|
| 312 |
+
timestamp,
|
| 313 |
+
student_name,
|
| 314 |
+
student_class,
|
| 315 |
+
title,
|
| 316 |
+
wc,
|
| 317 |
+
"Yes" if knows_story else "No",
|
| 318 |
+
(comp if comp is not None else ""),
|
| 319 |
+
expr,
|
| 320 |
+
refl,
|
| 321 |
+
len_s,
|
| 322 |
+
grammar_count,
|
| 323 |
+
grammar_star,
|
| 324 |
+
avg,
|
| 325 |
+
model_used,
|
| 326 |
+
remarks,
|
| 327 |
+
]
|
| 328 |
+
sheets_status = append_to_sheet(row)
|
| 329 |
+
status_text = "Saved to Google Sheet β
" if sheets_status == "OK" else f"Not saved β β {sheets_status}"
|
| 330 |
+
|
| 331 |
+
return md_str, corrected, status_text
|
| 332 |
+
|
| 333 |
+
except Exception as e:
|
| 334 |
+
# Show the REAL reason in the UI (no more tiny red 'Error' pill)
|
| 335 |
+
err_md = (
|
| 336 |
+
"### β Grading failed\n"
|
| 337 |
+
"```\n" + str(e) + "\n```\n"
|
| 338 |
+
f"- DeepSeek model: `{DEEPSEEK_MODEL}` Base: `{DEEPSEEK_BASE_URL}`\n"
|
| 339 |
+
f"- OpenAI model: `{OPENAI_MODEL}`\n"
|
| 340 |
+
"Tip: Ensure DEEPSEEK_MODEL is `deepseek-chat` and Space was restarted after changing secrets."
|
| 341 |
+
)
|
| 342 |
+
return err_md, "", "Not saved β β error during grading"
|
| 343 |
|
| 344 |
# ==================== UI ====================
|
| 345 |
+
with gr.Blocks(title="Summary Grader") as demo:
|
| 346 |
+
gr.Markdown("## Summary Grader")
|
| 347 |
|
| 348 |
with gr.Row():
|
| 349 |
student_name = gr.Textbox(label="Student Name", placeholder="Riya Sen")
|
|
|
|
| 369 |
inputs=[student_name, student_class, title_in, summary_in],
|
| 370 |
outputs=[report_out, corrected_out, status_out])
|
| 371 |
|
|
|
|
| 372 |
if __name__ == "__main__":
|
| 373 |
demo.launch()
|