Rajarshi255 commited on
Commit
0a27d28
Β·
verified Β·
1 Parent(s): eb9869f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -416
app.py CHANGED
@@ -1,22 +1,20 @@
1
- # app.py
2
  import os, json, re, time, math, random
3
  import gradio as gr
4
  from openai import OpenAI
5
  from datetime import datetime, timedelta
6
 
7
-
8
  # ==================== LLM CONFIG ====================
9
  DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
10
  DEEPSEEK_BASE_URL = os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com/v1")
11
- DEEPSEEK_MODEL = os.getenv("DEEPSEEK_MODEL", "deepseek-chat") # public DeepSeek chat model
12
 
13
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
14
- OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o-mini") # faster/cheaper fallback than gpt-5
15
 
16
  # ==================== GOOGLE SHEETS CONFIG ====================
17
- SVC_JSON = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON") # entire JSON string
18
  SHEET_ID = os.getenv("SHEETS_SPREADSHEET_ID")
19
- WS_ID = os.getenv("SHEETS_WORKSHEET_ID") # gid
20
 
21
  # ==================== LIMITS ====================
22
  MAX_CHARS = 12000
@@ -77,10 +75,8 @@ Return ONLY raw JSON (no markdown fences, no labels), exactly:
77
  """
78
 
79
  def check_repetition_ratio(text: str) -> float:
80
- # Finds all words and puts them in a list
81
  words = re.findall(r"\b\w+\b", text.lower())
82
  if not words: return 0.0
83
- # Compares unique words to total words
84
  unique_words = set(words)
85
  return len(unique_words) / len(words)
86
 
@@ -89,10 +85,7 @@ def save_to_master_doc(name, klass, title, summary):
89
  from google.oauth2.service_account import Credentials
90
  import json, os, datetime
91
 
92
- # Use the ID from your document link:
93
  MASTER_DOC_ID = "1IW_XsQsR3AIHpaxY3tJZuEujClC_KIHb0QeYhKLYbUM"
94
-
95
- # Use the secret name confirmed for your Hugging Face Space
96
  secret_data = os.environ.get("gcp_service_account")
97
 
98
  if not secret_data:
@@ -101,7 +94,6 @@ def save_to_master_doc(name, klass, title, summary):
101
  try:
102
  creds = Credentials.from_service_account_info(
103
  json.loads(SVC_JSON),
104
- #scopes=["https://www.googleapis.com/auth/documents"]
105
  scopes=[
106
  "https://www.googleapis.com/auth/documents",
107
  "https://www.googleapis.com/auth/drive.file",
@@ -109,11 +101,8 @@ def save_to_master_doc(name, klass, title, summary):
109
  ]
110
  )
111
  service = build('docs', 'v1', credentials=creds)
112
-
113
- # 1. Format the Entry with "Metadata Anchors" for future extraction
114
  timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
115
 
116
- # This structure allows a code to easily split the file later
117
  new_entry = (
118
  f"\n\n### START_ENTRY ###\n"
119
  f"[[METADATA|NAME:{name.strip()}|CLASS:{klass.strip()}|DATE:{timestamp}|TITLE:{title.strip()}]]\n"
@@ -123,148 +112,78 @@ def save_to_master_doc(name, klass, title, summary):
123
  f"### END_ENTRY ###\n"
124
  )
125
 
126
- # 2. Find the end of the document to append the new text
127
  doc = service.documents().get(documentId=MASTER_DOC_ID).execute()
128
- # endIndex - 1 is the position just before the very end of the doc
129
  end_index = doc.get('body').get('content')[-1].get('endIndex') - 1
130
 
131
- requests = [
132
- {
133
- 'insertText': {
134
- 'location': {'index': end_index},
135
- 'text': new_entry
136
- }
137
- }
138
- ]
139
-
140
- # 3. Append the formatted entry to the master doc
141
  service.documents().batchUpdate(documentId=MASTER_DOC_ID, body={'requests': requests}).execute()
142
  return "βœ… Essay appended to Master Doc"
143
-
144
  except Exception as e:
145
- print(f"Doc Append Error: {e}")
146
  return f"❌ Doc Error: {e}"
 
147
  def student_key(name, klass):
148
  first = str(name).strip().split()[0].lower()
149
  return f"{first}_{str(klass).strip().lower()}"
150
 
151
-
152
  def week_bounds(d: datetime.date):
153
- # Week = Sunday to Saturday
154
  sunday = d - timedelta(days=(d.weekday() + 1) % 7)
155
  saturday = sunday + timedelta(days=6)
156
  return sunday, saturday
157
 
158
- # ==================== LLM BRIDGE WITH RETRIES ====================
159
  def _retry_delays(n):
160
- # jittered exponential backoff: 0.6s, 1.2s, 2.4s ...
161
  base = 0.6
162
  for i in range(n):
163
  yield base * (2 ** i) * (0.8 + 0.4 * random.random())
164
 
165
  def call_openai_compatible(api_key, base_url, model, messages, tries=3):
166
- """
167
- Generic caller for OpenAI-compatible chat completions with retries.
168
- Returns (content, model_used_str).
169
- Raises RuntimeError after exhausting retries.
170
- """
171
  last_err = None
172
  client = OpenAI(api_key=api_key, base_url=base_url) if base_url else OpenAI(api_key=api_key)
173
-
174
- for delay in list(_retry_delays(tries)) + [0]: # run tries times; last 0 means "final attempt now"
175
  try:
176
  resp = client.chat.completions.create(model=model, messages=messages)
177
- content = resp.choices[0].message.content
178
- return content, f"{'DeepSeek' if 'deepseek' in (base_url or '') else 'OpenAI'} ({model})"
179
  except Exception as e:
180
  last_err = e
181
- if delay > 0:
182
- time.sleep(delay)
183
-
184
- raise RuntimeError(f"LLM call failed after {tries} tries [{model} @ {base_url or 'api.openai.com'}]: {last_err}")
185
 
186
  def llm_chat(messages):
187
- """
188
- Try DeepSeek (3 retries). If that fails, fallback to OpenAI (2 retries).
189
- Always returns (content, model_used_str) OR raises RuntimeError with reason.
190
- """
191
- # DeepSeek first
192
  if DEEPSEEK_API_KEY:
193
  try:
194
- return call_openai_compatible(
195
- api_key=DEEPSEEK_API_KEY,
196
- base_url=DEEPSEEK_BASE_URL,
197
- model=DEEPSEEK_MODEL,
198
- messages=messages,
199
- tries=3
200
- )
201
  except Exception as e:
202
- # Continue to fallback, but include why DS failed in final error if OA also fails
203
  ds_err = f"DeepSeek error: {e}"
204
  else:
205
  ds_err = "DeepSeek key not set."
206
 
207
- # OpenAI fallback
208
  if OPENAI_API_KEY:
209
  try:
210
- return call_openai_compatible(
211
- api_key=OPENAI_API_KEY,
212
- base_url=None, # OpenAI official
213
- model=OPENAI_MODEL,
214
- messages=messages,
215
- tries=2
216
- )
217
  except Exception as e:
218
  raise RuntimeError(f"{ds_err}\nOpenAI error: {e}")
 
219
 
220
- raise RuntimeError(f"{ds_err}\nNo OpenAI fallback configured (OPENAI_API_KEY missing).")
221
-
222
- # ==================== JSON SALVAGE (ROBUST) ====================
223
  def salvage_json(s: str) -> dict:
224
- """
225
- Make the model output JSON-parseable:
226
- - remove ```json fences
227
- - normalize quotes
228
- - keep only the last {...} block if extra text exists
229
- - remove trailing commas
230
- - fill missing start/end_index with 0
231
- - coerce types safely
232
- """
233
  s = s.strip()
234
- # strip code fences
235
  s = re.sub(r"^\s*```(?:json)?\s*", "", s)
236
  s = re.sub(r"\s*```\s*$", "", s)
237
-
238
- # normalize curly quotes
239
  s = s.replace("β€œ", '"').replace("”", '"').replace("’", "'")
240
-
241
- # capture last JSON object if there's extra prose
242
  m = re.search(r"\{.*\}\s*$", s, flags=re.S)
243
- if m:
244
- s = m.group(0)
245
-
246
- # remove trailing commas before } or ]
247
  s = re.sub(r",\s*([}\]])", r"\1", s)
248
-
249
- # handle missing numeric values
250
  s = re.sub(r'"end_index"\s*:\s*(?=(,|\}))', r'"end_index": 0', s)
251
  s = re.sub(r'"start_index"\s*:\s*(?=(,|\}))', r'"start_index": 0', s)
252
-
253
  data = json.loads(s)
254
-
255
- # sanitize grammar_issues
256
  issues = data.get("grammar_issues", [])
257
  safe_issues = []
258
  if isinstance(issues, list):
259
  for it in issues:
260
- if not isinstance(it, dict):
261
- continue
262
- si = it.get("start_index", 0)
263
- ei = it.get("end_index", 0)
264
- try: si = int(si)
265
- except Exception: si = 0
266
- try: ei = int(ei)
267
- except Exception: ei = 0
268
  safe_issues.append({
269
  "error_excerpt": str(it.get("error_excerpt", ""))[:200],
270
  "correction": str(it.get("correction", ""))[:200],
@@ -275,10 +194,8 @@ def salvage_json(s: str) -> dict:
275
  data["grammar_issues"] = safe_issues
276
  return data
277
 
278
- # ==================== HELPERS ====================
279
  def stars_bar(value: float | int | None, max_stars: int = 5) -> str:
280
- if value is None or float(value) <= 0:
281
- return "β€”"
282
  n_int = max(0, min(max_stars, int(round(float(value)))))
283
  return "⭐" * n_int
284
 
@@ -304,383 +221,121 @@ def annotate_original_with_issues(text: str, issues: list[dict]) -> str:
304
  try:
305
  si, ei = int(it["start_index"]), int(it["end_index"])
306
  if 0 <= si < ei <= len(text): clean.append((si, ei, i))
307
- except Exception:
308
- continue
309
  clean.sort(key=lambda x: x[0])
310
  out, cursor, last_end = [], 0, -1
311
  for si, ei, idx in clean:
312
- if si < last_end: # skip overlaps
313
- continue
314
  out.append(text[cursor:si])
315
  out.append(f"[[#{idx}: {text[si:ei]}]]")
316
  cursor, last_end = ei, ei
317
  out.append(text[cursor:])
318
  return "".join(out)
319
 
320
- def apply_corrections_by_offsets(text: str, issues: list[dict]) -> str:
321
- spans = []
322
- for it in issues:
323
- try:
324
- si, ei = int(it["start_index"]), int(it["end_index"])
325
- cor = str(it.get("correction", ""))
326
- if 0 <= si < ei <= len(text): spans.append((si, ei, cor))
327
- except Exception:
328
- continue
329
- spans.sort(key=lambda x: x[0])
330
- out, cursor, last_end = [], 0, -1
331
- for si, ei, cor in spans:
332
- if si < last_end: continue
333
- out.append(text[cursor:si]); out.append(cor)
334
- cursor, last_end = ei, ei
335
- out.append(text[cursor:])
336
- return "".join(out)
337
-
338
- # ==================== GOOGLE SHEETS WRITER ====================
339
- '''def append_to_sheet(row: list, student_name: str, student_class: str, avg: float) -> str:
340
- if not (SVC_JSON and SHEET_ID and WS_ID):
341
- return "Sheets not configured."
342
-
343
- try:
344
- import gspread
345
- from google.oauth2.service_account import Credentials
346
-
347
- creds = Credentials.from_service_account_info(
348
- json.loads(SVC_JSON),
349
- scopes=["https://www.googleapis.com/auth/spreadsheets"]
350
- )
351
- gc = gspread.authorize(creds)
352
- ws = gc.open_by_key(SHEET_ID).get_worksheet_by_id(int(WS_ID))
353
-
354
- records = ws.get_all_records(
355
- expected_headers=[
356
- "Timestamp",
357
- "Name",
358
- "Class",
359
- "CorrectAnswers",
360
- "TotalQuestions",
361
- "Percentage",
362
- "StarsAwarded",
363
- "module"
364
- ]
365
- )
366
-
367
- today = datetime.now().date()
368
- sunday, saturday = week_bounds(today)
369
-
370
- key = student_key(student_name, student_class)
371
-
372
- best_row = None
373
- best_score = -1
374
-
375
- for i, r in enumerate(records, start=2):
376
- try:
377
- ts = datetime.strptime(r["Timestamp"], "%Y-%m-%d %H:%M:%S").date()
378
- except Exception:
379
- continue
380
-
381
- if not (sunday <= ts <= saturday):
382
- continue
383
-
384
- if student_key(r["Name"], r["Class"]) == key:
385
- prev = float(r["CorrectAnswers"])
386
- if prev > best_score:
387
- best_score = prev
388
- best_row = i
389
-
390
- if best_row is not None:
391
- if avg <= best_score:
392
- return "⚠️ You already have a better score this week. This attempt was not saved."
393
- ws.delete_rows(best_row)
394
-
395
- ws.append_row(row, value_input_option="USER_ENTERED")
396
- return "βœ… Best score saved for this week."
397
-
398
- except Exception as e:
399
- return f"Sheets error: {e}"'''
400
-
401
  def append_to_sheet(row: list, student_name: str, student_class: str, avg: float) -> str:
402
- if not SVC_JSON:
403
- return "Sheets error: Secret 'gcp_service_account' not found in Hugging Face."
404
-
405
  try:
406
  import gspread
407
  from google.oauth2.service_account import Credentials
408
-
409
- creds = Credentials.from_service_account_info(
410
- json.loads(SVC_JSON),
411
- scopes=["https://www.googleapis.com/auth/spreadsheets"]
412
- )
413
  gc = gspread.authorize(creds)
414
-
415
- # Open by Key and use the tab name "Scores"
416
  sh = gc.open_by_key(SHEET_ID)
417
  ws = sh.worksheet("Scores")
418
-
419
- # Get records to check for existing weekly scores
420
  records = ws.get_all_records()
421
-
422
  today = datetime.now().date()
423
- sunday, saturday = week_bounds(today)
424
  key = student_key(student_name, student_class)
425
-
426
- best_row = None
427
- best_score = -1
428
-
429
- # Check for existing records to find the "Best Score of the Week"
430
  for i, r in enumerate(records, start=2):
431
  try:
432
- # Match your Excel column names: 'Date', 'Name', 'Classs'
433
- raw_date = r.get("Date") or r.get("Timestamp")
434
- ts = datetime.strptime(raw_date, "%Y-%m-%d %H:%M:%S").date()
435
-
436
- if sunday <= ts <= saturday and student_key(r.get("Name"), r.get("Classs") or r.get("Class")) == key:
437
- # Column 'Star' or 'Result'
438
  prev = float(r.get("Star") or r.get("Result") or 0)
439
  if prev > best_score:
440
  best_score = prev
441
  best_row = i
442
- except:
443
- continue
444
-
445
- # Logic: Only save if this current 'avg' (Star) is better than the one already there
446
- if best_row is not None:
447
- if avg <= best_score:
448
- return f"⚠️ You already have a better star count ({best_score}) this week. Not saved."
449
- ws.delete_rows(best_row)
450
-
451
  ws.append_row(row, value_input_option="USER_ENTERED")
452
  return "βœ… Best score saved to Google Sheets!"
453
-
454
  except Exception as e:
455
- print(f"Detailed Sheet Error: {e}")
456
  return f"Sheets error: {e}"
457
 
458
-
459
- # ==================== FRIENDLY INTRO ====================
460
  def intro_message(name, klass):
461
- if not name.strip() or not klass.strip():
462
- return "πŸ‘‹ Please tell me your name and class first!"
463
- return f"""
464
- ### 🌟 Hi {name} of {klass}!
465
- Welcome to the **Summary Grader** πŸ‘‹
466
-
467
- How I'll mark:
468
- 1) **Comprehension** – only if I know the story
469
- 2) **Expression** – clarity & flow
470
- 3) **Reflection/Moral** – what you learned
471
- 4) **Grammar & Neatness** – lenient but tidy
472
- 5) **Length (IMPORTANT)**:
473
- - Minimum **100 words** needed to get any ⭐
474
- - 100–150 β†’ 1⭐
475
- - 150–200 β†’ 3⭐
476
- - 200–250 β†’ 4⭐
477
- - 250+ β†’ 5⭐
478
- Writing Nonsense will invite negative star
479
-
480
- Write clearly, think deeply, and press **Grade & Save!**
481
- """
482
 
483
- # ==================== CORE GRADING ====================
484
  def grade_summary(student_name: str, student_class: str, title: str, student_summary: str):
485
  try:
486
- if not student_name.strip():
487
- return "⚠️ Please enter the student's name.", "", ""
488
- if not student_class.strip():
489
- return "⚠️ Please enter the class/grade.", "", ""
490
- if not title.strip():
491
- return "⚠️ Please enter a title.", "", ""
492
- if not student_summary.strip():
493
- return "⚠️ Please paste the student's summary.", "", ""
494
- if len(student_summary) > MAX_CHARS:
495
- return f"⚠️ Summary too long ({len(student_summary)} chars). Limit is {MAX_CHARS}.", "", ""
496
-
497
- prompt = f"""
498
- TITLE: {title}
499
-
500
- STUDENT SUMMARY (ORIGINAL TEXT BELOW):
501
- {student_summary}
502
-
503
- {RUBRIC_USER_TEXT}
504
-
505
- {JSON_SCHEMA_HINT}
506
- """
507
- # DeepSeek (with retries) β†’ OpenAI fallback (with retries)
508
  content, model_used = llm_chat([{"role": "user", "content": prompt}])
509
-
510
- # Parse safely
511
  data = salvage_json(content)
512
- # 2. Extract Data (Including new nonsense flag)
513
- is_nonsense_ai = bool(data.get("is_nonsense", False))
514
 
515
- # 3. RUN MATHEMATICAL REPETITION CHECK
516
- rep_ratio = check_repetition_ratio(student_summary)
517
- # If less than 40% of words are unique, they are likely repeating to cheat.
518
- is_repetitive_math = rep_ratio < 0.40 and count_words(student_summary) > 25
519
-
520
- # Extract
521
  knows_story = bool(data.get("knows_story", False))
522
  scores = data.get("scores", {}) or {}
523
  comp = scores.get("Comprehension", None)
524
  expr = clamp_1_to_5(scores.get("Expression", 1))
525
  refl = clamp_1_to_5(scores.get("Reflection/Moral Takeaway", 1))
526
- issues = data.get("grammar_issues", []) or []
527
  corrected = (data.get("corrected_summary") or "").strip()
528
- remarks = (data.get("remarks") or "").strip()
529
- if not knows_story:
530
- comp = None
531
-
532
- # ======================== START OF REPLACEMENT ========================
533
  wc = count_words(student_summary)
534
  len_s = length_stars(wc)
535
- grammar_count = len(issues)
536
- grammar_star = round(grammar_stars_from_count(grammar_count), 1)
537
-
538
- # Base values for calculation
539
- vals = [float(expr), float(refl), float(len_s), float(grammar_star)]
540
- if knows_story and comp is not None:
541
- vals.append(float(comp))
542
 
543
- # Initial average calculation
 
544
  avg = round(sum(vals) / len(vals), 2) if vals else 0.0
545
 
546
- # RUN NONSENSE & REPETITION CHECKS
547
  rep_ratio = check_repetition_ratio(student_summary)
548
-
549
- # Determine specific penalty reasons
550
  reasons = []
551
- if is_nonsense_ai:
552
- reasons.append("The AI teacher flagged this text as nonsense or gibberish.")
553
- if rep_ratio < 0.30 and wc > 20:
554
- reasons.append(f"High repetition detected. You only used {round(rep_ratio * 100)}% unique words.")
555
-
556
  is_failing = len(reasons) > 0
 
557
 
558
- # OVERRIDE SCORE IF FAILING (Absolute -1 Star)
559
- if is_failing:
560
- avg = -1.0
561
-
562
- # Start building the Report
563
- md = []
564
- md.append(f"### πŸ“š Summary Grading Report")
565
-
566
  if is_failing:
567
  md.append("> ## ❌ FINAL SCORE: -1 STAR")
568
- md.append("> **Penalty Reason(s):**")
569
- for r in reasons:
570
- md.append(f"> * {r}")
571
- md.append("> \n> *Please write a real summary in your own words to receive a valid grade.*")
572
  md.append("")
573
 
574
  md.append(f"**Name:** {student_name} &nbsp;&nbsp; **Class:** {student_class}")
575
- # ========================= END OF REPLACEMENT =========================
576
- md.append(f"**Title:** {title}")
577
- md.append(f"**Word count:** {wc}")
578
- md.append("")
579
- md.append("#### ⭐ Category-wise Scores")
580
- if knows_story and comp is not None:
581
- md.append(f"- **Comprehension:** {stars_bar(comp)} ({comp} stars)")
582
- else:
583
- md.append(f"- **Comprehension:** *(omitted)*")
584
- md.append(f"- **Expression:** {stars_bar(expr)} ({expr} stars)")
585
- md.append(f"- **Reflection/Moral Takeaway:** {stars_bar(refl)} ({refl} stars)")
586
- md.append(f"- **Length:** {stars_bar(len_s)} ({len_s} stars, based on {wc} words)")
587
- md.append(f"- **Grammar:** {stars_bar(grammar_star)} ({grammar_star:.1f} stars, {grammar_count} mistakes)")
588
- md.append("")
589
- md.append(f"**Average Score:** {avg:.2f} {stars_bar(avg)} *(out of 5)*")
590
- md.append("")
591
- md.append("#### ✏️ Corrected Passage (LLM, minimal edits)")
592
- md.append(f"{corrected if corrected else '_(No changes returned by the model.)_'}")
593
- md.append("")
594
- md.append("#### πŸ”Ž Annotated Original (exact mistake spans)")
595
- md.append(annotate_original_with_issues(student_summary, issues))
596
- md.append("")
597
- md.append("#### 🧹 Grammar Issues (original β†’ corrected)")
598
- if not issues:
599
- md.append("- None πŸŽ‰")
600
- else:
601
- for i, it in enumerate(issues, 1):
602
- err = (it.get('error_excerpt') or '').strip()
603
- cor = (it.get('correction') or '').strip()
604
- why = (it.get('explanation') or '').strip()
605
- si = it.get('start_index', '?')
606
- ei = it.get('end_index', '?')
607
- md.append(f"{i}. `[{si}:{ei}]` **{err}** β†’ **{cor}** β€” {why}")
608
- md.append("")
609
- md.append(f"*Graded using:* **{model_used}**")
610
- md_str = "\n".join(md)
611
-
612
- # Save to Google Sheet (optional)
613
- # Create the row to match [Date, Name, Classs, Result, Full Marks, Percentage, Star, Level]
614
  timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
615
-
616
- row = [
617
- timestamp, # Date
618
- student_name, # Name
619
- student_class, # Classs
620
- round(avg, 2), # Result (Saving the decimal score here)
621
- "5", # Full Marks
622
- f"{round(avg * 20, 2)}%", # Percentage (Fix: avg * 20, not 2000)
623
- round(avg, 2), # Star (Fix: use round(avg, 2) to keep 4.32 instead of 4)
624
- "Summary Grader" # Level
625
- ]
626
-
627
- sheets_status = append_to_sheet(
628
- row,
629
- student_name,
630
- student_class,
631
- avg
632
- )
633
-
634
-
635
- #status_text = "Saved to Google Sheet βœ…" if sheets_status == "OK" else f"Not saved ❌ β€” {sheets_status}"
636
- status_text = sheets_status
637
- # After your sheets_status call:
638
  doc_status = save_to_master_doc(student_name, student_class, title, student_summary)
639
-
640
- # Update your final status message to show both results
641
- status_text = f"{sheets_status} | {doc_status}"
642
-
643
-
644
- return md_str, corrected, status_text
645
 
646
  except Exception as e:
647
- # show real reason; never crash to tiny red chip
648
- err_md = (
649
- "### ❌ Grading failed\n"
650
- "```\n" + str(e) + "\n```\n"
651
- f"- DeepSeek model: `{DEEPSEEK_MODEL}` Base: `{DEEPSEEK_BASE_URL}`\n"
652
- f"- OpenAI model: `{OPENAI_MODEL}`\n"
653
- "I retried DeepSeek, then fell back to OpenAI. If this keeps happening, check secrets and model IDs."
654
- )
655
- return err_md, "", "Not saved ❌ β€” error during grading"
656
 
657
- # ==================== UI ====================
658
  with gr.Blocks(title="Summary Grader") as demo:
659
  gr.Markdown("## Summary Grader")
660
-
661
- with gr.Row():
662
- student_name = gr.Textbox(label="Student Name", placeholder="Riya Sen")
663
- student_class = gr.Textbox(label="Class/Grade", placeholder="Class 6")
664
-
665
- intro_out = gr.Markdown(label="Welcome Message", visible=True)
666
- gr.Button("Show How I’ll Mark You", variant="secondary").click(
667
- fn=intro_message, inputs=[student_name, student_class], outputs=intro_out
668
- )
669
-
670
  with gr.Row():
671
- title_in = gr.Textbox(label="Book/Movie Title", placeholder="The Gift of the Magi")
672
-
673
- summary_in = gr.Textbox(label="Paste the student's summary", lines=12, placeholder="Paste text here...")
674
-
 
675
  btn = gr.Button("Grade & Save", variant="primary")
676
-
677
- report_out = gr.Markdown(label="Grading Report")
678
- corrected_out = gr.Textbox(label="Corrected Passage (plain text)", lines=10)
679
- status_out = gr.Markdown(label="Save Status")
680
-
681
- btn.click(fn=grade_summary,
682
- inputs=[student_name, student_class, title_in, summary_in],
683
- outputs=[report_out, corrected_out, status_out])
684
 
685
  if __name__ == "__main__":
686
- demo.launch()
 
 
1
  import os, json, re, time, math, random
2
  import gradio as gr
3
  from openai import OpenAI
4
  from datetime import datetime, timedelta
5
 
 
6
  # ==================== LLM CONFIG ====================
7
  DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
8
  DEEPSEEK_BASE_URL = os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com/v1")
9
+ DEEPSEEK_MODEL = os.getenv("DEEPSEEK_MODEL", "deepseek-chat")
10
 
11
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
12
+ OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
13
 
14
  # ==================== GOOGLE SHEETS CONFIG ====================
15
+ SVC_JSON = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON")
16
  SHEET_ID = os.getenv("SHEETS_SPREADSHEET_ID")
17
+ WS_ID = os.getenv("SHEETS_WORKSHEET_ID")
18
 
19
  # ==================== LIMITS ====================
20
  MAX_CHARS = 12000
 
75
  """
76
 
77
  def check_repetition_ratio(text: str) -> float:
 
78
  words = re.findall(r"\b\w+\b", text.lower())
79
  if not words: return 0.0
 
80
  unique_words = set(words)
81
  return len(unique_words) / len(words)
82
 
 
85
  from google.oauth2.service_account import Credentials
86
  import json, os, datetime
87
 
 
88
  MASTER_DOC_ID = "1IW_XsQsR3AIHpaxY3tJZuEujClC_KIHb0QeYhKLYbUM"
 
 
89
  secret_data = os.environ.get("gcp_service_account")
90
 
91
  if not secret_data:
 
94
  try:
95
  creds = Credentials.from_service_account_info(
96
  json.loads(SVC_JSON),
 
97
  scopes=[
98
  "https://www.googleapis.com/auth/documents",
99
  "https://www.googleapis.com/auth/drive.file",
 
101
  ]
102
  )
103
  service = build('docs', 'v1', credentials=creds)
 
 
104
  timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
105
 
 
106
  new_entry = (
107
  f"\n\n### START_ENTRY ###\n"
108
  f"[[METADATA|NAME:{name.strip()}|CLASS:{klass.strip()}|DATE:{timestamp}|TITLE:{title.strip()}]]\n"
 
112
  f"### END_ENTRY ###\n"
113
  )
114
 
 
115
  doc = service.documents().get(documentId=MASTER_DOC_ID).execute()
 
116
  end_index = doc.get('body').get('content')[-1].get('endIndex') - 1
117
 
118
+ requests = [{'insertText': {'location': {'index': end_index}, 'text': new_entry}}]
 
 
 
 
 
 
 
 
 
119
  service.documents().batchUpdate(documentId=MASTER_DOC_ID, body={'requests': requests}).execute()
120
  return "βœ… Essay appended to Master Doc"
 
121
  except Exception as e:
 
122
  return f"❌ Doc Error: {e}"
123
+
124
  def student_key(name, klass):
125
  first = str(name).strip().split()[0].lower()
126
  return f"{first}_{str(klass).strip().lower()}"
127
 
 
128
  def week_bounds(d: datetime.date):
 
129
  sunday = d - timedelta(days=(d.weekday() + 1) % 7)
130
  saturday = sunday + timedelta(days=6)
131
  return sunday, saturday
132
 
 
133
  def _retry_delays(n):
 
134
  base = 0.6
135
  for i in range(n):
136
  yield base * (2 ** i) * (0.8 + 0.4 * random.random())
137
 
138
  def call_openai_compatible(api_key, base_url, model, messages, tries=3):
 
 
 
 
 
139
  last_err = None
140
  client = OpenAI(api_key=api_key, base_url=base_url) if base_url else OpenAI(api_key=api_key)
141
+ for delay in list(_retry_delays(tries)) + [0]:
 
142
  try:
143
  resp = client.chat.completions.create(model=model, messages=messages)
144
+ return resp.choices[0].message.content, f"{'DeepSeek' if 'deepseek' in (base_url or '') else 'OpenAI'} ({model})"
 
145
  except Exception as e:
146
  last_err = e
147
+ if delay > 0: time.sleep(delay)
148
+ raise RuntimeError(f"LLM failed: {last_err}")
 
 
149
 
150
  def llm_chat(messages):
 
 
 
 
 
151
  if DEEPSEEK_API_KEY:
152
  try:
153
+ return call_openai_compatible(DEEPSEEK_API_KEY, DEEPSEEK_BASE_URL, DEEPSEEK_MODEL, messages, 3)
 
 
 
 
 
 
154
  except Exception as e:
 
155
  ds_err = f"DeepSeek error: {e}"
156
  else:
157
  ds_err = "DeepSeek key not set."
158
 
 
159
  if OPENAI_API_KEY:
160
  try:
161
+ return call_openai_compatible(OPENAI_API_KEY, None, OPENAI_MODEL, messages, 2)
 
 
 
 
 
 
162
  except Exception as e:
163
  raise RuntimeError(f"{ds_err}\nOpenAI error: {e}")
164
+ raise RuntimeError(f"{ds_err}\nNo OpenAI fallback.")
165
 
 
 
 
166
  def salvage_json(s: str) -> dict:
 
 
 
 
 
 
 
 
 
167
  s = s.strip()
 
168
  s = re.sub(r"^\s*```(?:json)?\s*", "", s)
169
  s = re.sub(r"\s*```\s*$", "", s)
 
 
170
  s = s.replace("β€œ", '"').replace("”", '"').replace("’", "'")
 
 
171
  m = re.search(r"\{.*\}\s*$", s, flags=re.S)
172
+ if m: s = m.group(0)
 
 
 
173
  s = re.sub(r",\s*([}\]])", r"\1", s)
 
 
174
  s = re.sub(r'"end_index"\s*:\s*(?=(,|\}))', r'"end_index": 0', s)
175
  s = re.sub(r'"start_index"\s*:\s*(?=(,|\}))', r'"start_index": 0', s)
 
176
  data = json.loads(s)
 
 
177
  issues = data.get("grammar_issues", [])
178
  safe_issues = []
179
  if isinstance(issues, list):
180
  for it in issues:
181
+ if not isinstance(it, dict): continue
182
+ si, ei = 0, 0
183
+ try: si = int(it.get("start_index", 0))
184
+ except: si = 0
185
+ try: ei = int(it.get("end_index", 0))
186
+ except: ei = 0
 
 
187
  safe_issues.append({
188
  "error_excerpt": str(it.get("error_excerpt", ""))[:200],
189
  "correction": str(it.get("correction", ""))[:200],
 
194
  data["grammar_issues"] = safe_issues
195
  return data
196
 
 
197
  def stars_bar(value: float | int | None, max_stars: int = 5) -> str:
198
+ if value is None or float(value) <= 0: return "β€”"
 
199
  n_int = max(0, min(max_stars, int(round(float(value)))))
200
  return "⭐" * n_int
201
 
 
221
  try:
222
  si, ei = int(it["start_index"]), int(it["end_index"])
223
  if 0 <= si < ei <= len(text): clean.append((si, ei, i))
224
+ except: continue
 
225
  clean.sort(key=lambda x: x[0])
226
  out, cursor, last_end = [], 0, -1
227
  for si, ei, idx in clean:
228
+ if si < last_end: continue
 
229
  out.append(text[cursor:si])
230
  out.append(f"[[#{idx}: {text[si:ei]}]]")
231
  cursor, last_end = ei, ei
232
  out.append(text[cursor:])
233
  return "".join(out)
234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
  def append_to_sheet(row: list, student_name: str, student_class: str, avg: float) -> str:
236
+ if not SVC_JSON: return "Sheets error: Secret missing."
 
 
237
  try:
238
  import gspread
239
  from google.oauth2.service_account import Credentials
240
+ creds = Credentials.from_service_account_info(json.loads(SVC_JSON), scopes=["https://www.googleapis.com/auth/spreadsheets"])
 
 
 
 
241
  gc = gspread.authorize(creds)
 
 
242
  sh = gc.open_by_key(SHEET_ID)
243
  ws = sh.worksheet("Scores")
 
 
244
  records = ws.get_all_records()
 
245
  today = datetime.now().date()
246
+ sun, sat = week_bounds(today)
247
  key = student_key(student_name, student_class)
248
+ best_row, best_score = None, -1
 
 
 
 
249
  for i, r in enumerate(records, start=2):
250
  try:
251
+ ts = datetime.strptime(r.get("Date") or r.get("Timestamp"), "%Y-%m-%d %H:%M:%S").date()
252
+ if sun <= ts <= sat and student_key(r.get("Name"), r.get("Classs") or r.get("Class")) == key:
 
 
 
 
253
  prev = float(r.get("Star") or r.get("Result") or 0)
254
  if prev > best_score:
255
  best_score = prev
256
  best_row = i
257
+ except: continue
258
+ if best_row is not None and avg <= best_score:
259
+ return f"⚠️ Better star count ({best_score}) exists this week. Not saved."
260
+ if best_row is not None: ws.delete_rows(best_row)
 
 
 
 
 
261
  ws.append_row(row, value_input_option="USER_ENTERED")
262
  return "βœ… Best score saved to Google Sheets!"
 
263
  except Exception as e:
 
264
  return f"Sheets error: {e}"
265
 
 
 
266
  def intro_message(name, klass):
267
+ if not name.strip() or not klass.strip(): return "πŸ‘‹ Please tell me your name and class first!"
268
+ return f"### 🌟 Hi {name} of {klass}!\nWelcome to the **Summary Grader** πŸ‘‹\n\nHow I'll mark:\n1) Comprehension\n2) Expression\n3) Reflection/Moral\n4) Grammar\n5) Length (Min 100 words)\n\nWriting Nonsense will invite -1.0 star penalty."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
 
 
270
  def grade_summary(student_name: str, student_class: str, title: str, student_summary: str):
271
  try:
272
+ if not student_name.strip() or not student_class.strip() or not title.strip() or not student_summary.strip():
273
+ return "⚠️ Missing fields.", "", ""
274
+
275
+ prompt = f"TITLE: {title}\nSUMMARY: {student_summary}\n{RUBRIC_USER_TEXT}\n{JSON_SCHEMA_HINT}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
276
  content, model_used = llm_chat([{"role": "user", "content": prompt}])
 
 
277
  data = salvage_json(content)
 
 
278
 
279
+ is_nonsense_ai = bool(data.get("is_nonsense", False))
 
 
 
 
 
280
  knows_story = bool(data.get("knows_story", False))
281
  scores = data.get("scores", {}) or {}
282
  comp = scores.get("Comprehension", None)
283
  expr = clamp_1_to_5(scores.get("Expression", 1))
284
  refl = clamp_1_to_5(scores.get("Reflection/Moral Takeaway", 1))
285
+ issues = data.get("grammar_issues", [])
286
  corrected = (data.get("corrected_summary") or "").strip()
287
+
 
 
 
 
288
  wc = count_words(student_summary)
289
  len_s = length_stars(wc)
290
+ grammar_star = round(grammar_stars_from_count(len(issues)), 1)
 
 
 
 
 
 
291
 
292
+ vals = [float(expr), float(refl), float(len_s), float(grammar_star)]
293
+ if knows_story and comp is not None: vals.append(float(comp))
294
  avg = round(sum(vals) / len(vals), 2) if vals else 0.0
295
 
 
296
  rep_ratio = check_repetition_ratio(student_summary)
 
 
297
  reasons = []
298
+ if is_nonsense_ai: reasons.append("The AI teacher flagged this as nonsense.")
299
+ if rep_ratio < 0.30 and wc > 20: reasons.append(f"High repetition ({round(rep_ratio*100)}% unique).")
300
+
 
 
301
  is_failing = len(reasons) > 0
302
+ if is_failing: avg = -1.0
303
 
304
+ md = [f"### πŸ“š Summary Grading Report"]
 
 
 
 
 
 
 
305
  if is_failing:
306
  md.append("> ## ❌ FINAL SCORE: -1 STAR")
307
+ md.append("> **Reasons:** " + " | ".join(reasons))
 
 
 
308
  md.append("")
309
 
310
  md.append(f"**Name:** {student_name} &nbsp;&nbsp; **Class:** {student_class}")
311
+ md.append(f"**Title:** {title} | **Words:** {wc}")
312
+ md.append("#### ⭐ Category Scores")
313
+ md.append(f"- Comprehension: {stars_bar(comp)} | Expression: {stars_bar(expr)}")
314
+ md.append(f"- Reflection: {stars_bar(refl)} | Length: {stars_bar(len_s)} | Grammar: {stars_bar(grammar_star)}")
315
+ md.append(f"\n**Average Score: {avg:.2f} {stars_bar(avg)}**")
316
+ md.append(f"\n#### πŸ”Ž Annotated Original\n{annotate_original_with_issues(student_summary, issues)}")
317
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
  timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
319
+ row = [timestamp, student_name, student_class, round(avg, 2), "5", f"{round(avg * 20, 2)}%", round(avg, 2), "Summary Grader"]
320
+
321
+ sheets_status = append_to_sheet(row, student_name, student_class, avg)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
322
  doc_status = save_to_master_doc(student_name, student_class, title, student_summary)
323
+
324
+ return "\n".join(md), corrected, f"{sheets_status} | {doc_status}"
 
 
 
 
325
 
326
  except Exception as e:
327
+ return f"### ❌ Error\n{e}", "", "Not saved."
 
 
 
 
 
 
 
 
328
 
 
329
  with gr.Blocks(title="Summary Grader") as demo:
330
  gr.Markdown("## Summary Grader")
 
 
 
 
 
 
 
 
 
 
331
  with gr.Row():
332
+ name_in = gr.Textbox(label="Student Name")
333
+ class_in = gr.Textbox(label="Class")
334
+ gr.Button("Marking Scheme").click(fn=intro_message, inputs=[name_in, class_in], outputs=gr.Markdown())
335
+ title_in = gr.Textbox(label="Title")
336
+ summary_in = gr.Textbox(label="Summary", lines=10)
337
  btn = gr.Button("Grade & Save", variant="primary")
338
+ btn.click(fn=grade_summary, inputs=[name_in, class_in, title_in, summary_in], outputs=[gr.Markdown(), gr.Textbox(), gr.Markdown()])
 
 
 
 
 
 
 
339
 
340
  if __name__ == "__main__":
341
+ demo.launch()