Rajarshi255 commited on
Commit
26ec06b
Β·
verified Β·
1 Parent(s): 25feff5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -14
app.py CHANGED
@@ -2,6 +2,8 @@
2
  import os, json, re, time, math, random
3
  import gradio as gr
4
  from openai import OpenAI
 
 
5
 
6
  # ==================== LLM CONFIG ====================
7
  DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
@@ -69,6 +71,16 @@ Return ONLY raw JSON (no markdown fences, no labels), exactly:
69
  - If no grammar issues, use an empty list [].
70
  - Numbers only for scores.
71
  """
 
 
 
 
 
 
 
 
 
 
72
 
73
  # ==================== LLM BRIDGE WITH RETRIES ====================
74
  def _retry_delays(n):
@@ -251,22 +263,57 @@ def apply_corrections_by_offsets(text: str, issues: list[dict]) -> str:
251
  return "".join(out)
252
 
253
  # ==================== GOOGLE SHEETS WRITER ====================
254
- def append_to_sheet(row: list) -> str:
255
  if not (SVC_JSON and SHEET_ID and WS_ID):
256
- return "Sheets not configured (missing GOOGLE_SERVICE_ACCOUNT_JSON / SHEETS_SPREADSHEET_ID / SHEETS_WORKSHEET_ID)."
 
257
  try:
258
  import gspread
259
  from google.oauth2.service_account import Credentials
260
- creds_info = json.loads(SVC_JSON)
261
- scopes = ["https://www.googleapis.com/auth/spreadsheets"]
262
- creds = Credentials.from_service_account_info(creds_info, scopes=scopes)
 
 
263
  gc = gspread.authorize(creds)
264
  ws = gc.open_by_key(SHEET_ID).get_worksheet_by_id(int(WS_ID))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
  ws.append_row(row, value_input_option="USER_ENTERED")
266
- return "OK"
 
267
  except Exception as e:
268
  return f"Sheets error: {e}"
269
 
 
270
  # ==================== FRIENDLY INTRO ====================
271
  def intro_message(name, klass):
272
  if not name.strip() or not klass.strip():
@@ -280,8 +327,13 @@ How I'll mark:
280
  2) **Expression** – clarity & flow
281
  3) **Reflection/Moral** – what you learned
282
  4) **Grammar & Neatness** – lenient but tidy
283
- 5) **Length** – word-count stars:
284
- - <100 β†’ 0⭐, 100–150 β†’ 1⭐, 150–200 β†’ 3⭐, 200–250 β†’ 4⭐, 250+ β†’ 5⭐
 
 
 
 
 
285
 
286
  Write clearly, think deeply, and press **Grade & Save!**
287
  """
@@ -381,13 +433,27 @@ STUDENT SUMMARY (ORIGINAL TEXT BELOW):
381
  # Save to Google Sheet (optional)
382
  timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
383
  row = [
384
- timestamp, student_name, student_class, title, wc,
385
- "Yes" if knows_story else "No",
386
- (comp if comp is not None else ""), expr, refl, len_s,
387
- grammar_count, grammar_star, avg, model_used, remarks,
 
 
 
 
388
  ]
389
- sheets_status = append_to_sheet(row)
390
- status_text = "Saved to Google Sheet βœ…" if sheets_status == "OK" else f"Not saved ❌ β€” {sheets_status}"
 
 
 
 
 
 
 
 
 
 
391
 
392
  return md_str, corrected, status_text
393
 
 
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")
 
71
  - If no grammar issues, use an empty list [].
72
  - Numbers only for scores.
73
  """
74
+ def student_key(name: str, klass: str) -> str:
75
+ # Use first name + class
76
+ first = name.strip().split()[0].lower()
77
+ return f"{first}_{klass.strip().lower()}"
78
+
79
+ def week_bounds(d: datetime.date):
80
+ # Week = Sunday to Saturday
81
+ sunday = d - timedelta(days=(d.weekday() + 1) % 7)
82
+ saturday = sunday + timedelta(days=6)
83
+ return sunday, saturday
84
 
85
  # ==================== LLM BRIDGE WITH RETRIES ====================
86
  def _retry_delays(n):
 
263
  return "".join(out)
264
 
265
  # ==================== GOOGLE SHEETS WRITER ====================
266
+ def append_to_sheet(row: list, student_name: str, student_class: str, avg: float) -> str:
267
  if not (SVC_JSON and SHEET_ID and WS_ID):
268
+ return "Sheets not configured."
269
+
270
  try:
271
  import gspread
272
  from google.oauth2.service_account import Credentials
273
+
274
+ creds = Credentials.from_service_account_info(
275
+ json.loads(SVC_JSON),
276
+ scopes=["https://www.googleapis.com/auth/spreadsheets"]
277
+ )
278
  gc = gspread.authorize(creds)
279
  ws = gc.open_by_key(SHEET_ID).get_worksheet_by_id(int(WS_ID))
280
+
281
+ records = ws.get_all_records()
282
+ today = datetime.now().date()
283
+ sunday, saturday = week_bounds(today)
284
+
285
+ key = student_key(student_name, student_class)
286
+
287
+ best_row = None
288
+ best_score = -1
289
+
290
+ for i, r in enumerate(records, start=2):
291
+ try:
292
+ ts = datetime.strptime(r["Timestamp"], "%Y-%m-%d %H:%M:%S").date()
293
+ except Exception:
294
+ continue
295
+
296
+ if not (sunday <= ts <= saturday):
297
+ continue
298
+
299
+ if student_key(r["Name"], r["Class"]) == key:
300
+ prev = float(r["CorrectAnswers"])
301
+ if prev > best_score:
302
+ best_score = prev
303
+ best_row = i
304
+
305
+ if best_row is not None:
306
+ if avg <= best_score:
307
+ return "⚠️ You already have a better score this week. This attempt was not saved."
308
+ ws.delete_rows(best_row)
309
+
310
  ws.append_row(row, value_input_option="USER_ENTERED")
311
+ return "βœ… Best score saved for this week."
312
+
313
  except Exception as e:
314
  return f"Sheets error: {e}"
315
 
316
+
317
  # ==================== FRIENDLY INTRO ====================
318
  def intro_message(name, klass):
319
  if not name.strip() or not klass.strip():
 
327
  2) **Expression** – clarity & flow
328
  3) **Reflection/Moral** – what you learned
329
  4) **Grammar & Neatness** – lenient but tidy
330
+ 5) **Length (IMPORTANT)**:
331
+ - Minimum **100 words** needed to get any ⭐
332
+ - 100–150 β†’ 1⭐
333
+ - 150–200 β†’ 3⭐
334
+ - 200–250 β†’ 4⭐
335
+ - 250+ β†’ 5⭐
336
+
337
 
338
  Write clearly, think deeply, and press **Grade & Save!**
339
  """
 
433
  # Save to Google Sheet (optional)
434
  timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
435
  row = [
436
+ timestamp,
437
+ student_name,
438
+ student_class,
439
+ round(avg, 2), # CorrectAnswers
440
+ 5, # TotalQuestions
441
+ int(avg * 20), # Percentage
442
+ int(round(avg)), # StarsAwarded
443
+ "summary grader" # module
444
  ]
445
+
446
+ sheets_status = append_to_sheet(
447
+ row,
448
+ student_name,
449
+ student_class,
450
+ avg
451
+ )
452
+
453
+
454
+ #status_text = "Saved to Google Sheet βœ…" if sheets_status == "OK" else f"Not saved ❌ β€” {sheets_status}"
455
+ status_text = sheets_status
456
+
457
 
458
  return md_str, corrected, status_text
459