Rajarshi255 commited on
Commit
1b40c1e
ยท
verified ยท
1 Parent(s): ecbed39

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1013 -73
app.py CHANGED
@@ -1,134 +1,1074 @@
1
- # ONLY KEY PARTS SHOWN EARLIER ARE NOW FULLY MERGED INTO YOUR ORIGINAL FILE
2
- # THIS IS YOUR ORIGINAL FILE + FIXES. NOTHING ELSE CHANGED.
3
-
4
  import os, json, re, time, math, random, logging
5
  import gradio as gr
6
  from openai import OpenAI
7
  from datetime import datetime, timedelta
8
 
9
  # ==================== LOGGING ====================
10
- logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
 
 
 
11
  log = logging.getLogger(__name__)
12
 
13
- # ==================== HELPERS ====================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  def is_nonsense_heuristic(text: str) -> tuple[bool, str]:
 
 
 
 
 
 
 
 
16
  words = re.findall(r"\b\w+\b", text.lower())
17
  if len(words) < 5:
18
  return False, ""
19
 
 
20
  from collections import Counter
21
  word_counts = Counter(words)
22
  most_common_word, most_common_count = word_counts.most_common(1)[0]
23
  if most_common_count / len(words) > 0.5:
24
- return True, f"Word '{most_common_word}' repeated too much."
25
 
 
26
  bigrams = list(zip(words, words[1:]))
27
  if bigrams:
28
  unique_bigrams = set(bigrams)
29
- if len(unique_bigrams) / len(bigrams) < 0.25:
30
- return True, "Highly repetitive pattern."
 
 
 
 
 
 
31
 
32
  return False, ""
33
 
34
- # โœ… NEW FUNCTION
35
- def is_irrelevant_answer(student_text: str, reference_text: str) -> tuple[bool, str]:
36
- student_words = set(re.findall(r"\b\w+\b", student_text.lower()))
37
- ref_words = set(re.findall(r"\b\w+\b", reference_text.lower()))
38
 
39
- if len(student_words) < 5:
40
- return True, "Answer too short or empty."
 
 
41
 
42
- overlap = student_words & ref_words
43
- overlap_ratio = len(overlap) / max(1, len(student_words))
 
 
44
 
45
- if overlap_ratio < 0.2:
46
- return True, "Answer does not match the passage content."
 
 
 
 
 
 
 
 
 
 
 
47
 
48
- return False, ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
  def count_words(text: str) -> int:
51
- return len(re.findall(r"\b\w+\b", text))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
- # ==================== STANDARD MODE ====================
 
 
 
 
 
 
 
 
 
 
54
 
55
- def grade_standard(student_name, student_class, title, student_summary):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  try:
57
  if not all([student_name.strip(), student_class.strip(), title.strip(), student_summary.strip()]):
58
  return "โš ๏ธ Please fill in all fields.", "", ""
59
 
60
- wc = count_words(student_summary)
 
 
 
61
 
62
- # โœ… HARD FAIL INSERTED CORRECTLY
63
- if wc < 100:
64
- md = [
65
- "### ๐Ÿ“š Standard Mode โ€” Grading Report",
66
- "> ## โŒ FINAL SCORE: โˆ’1 โญ",
67
- f"> **Reason:** Too short ({wc} words). Minimum 100 words required."
68
- ]
69
- return "\n".join(md), "", "Not saved."
70
 
71
- # --- ORIGINAL LOGIC CONTINUES ---
72
- return f"โœ… Processed {wc} words (rest of logic unchanged)", "", ""
 
 
 
 
 
 
 
73
 
74
- except Exception as e:
75
- return f"Error: {e}", "", ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
- # ==================== PASSAGE MODE ====================
 
 
 
 
 
78
 
79
- def grade_passage_mode(student_name, student_class, student_text, level, mode):
 
 
 
 
 
 
80
  try:
81
- reference_text = "sample passage content here"
 
 
 
 
 
 
 
 
 
82
 
83
- # โœ… NEW CHECK
84
- irrelevant, ir_reason = is_irrelevant_answer(student_text, reference_text)
 
 
 
 
 
 
 
85
 
86
- is_nonsense_ai = False
87
  heuristic_bad, heuristic_reason = is_nonsense_heuristic(student_text)
 
88
 
89
- # โœ… MODIFIED FAIL CONDITION
90
- is_failing = is_nonsense_ai or heuristic_bad or irrelevant
 
 
 
 
91
 
92
  if is_failing:
93
- if is_nonsense_ai:
94
- fail_reason = "AI flagged as gibberish."
95
- elif heuristic_bad:
96
- fail_reason = heuristic_reason
97
- elif irrelevant:
98
- fail_reason = ir_reason
99
- else:
100
- fail_reason = "Invalid answer."
 
 
 
 
 
 
 
 
 
101
 
102
- return f"โŒ FINAL SCORE: -1 โญ\nReason: {fail_reason}", level, "Not saved."
 
 
 
103
 
104
- return "โœ… Passage graded normally", level, "Saved"
 
 
 
 
 
105
 
 
 
 
 
 
 
 
 
 
106
  except Exception as e:
107
- return f"Error: {e}", level, ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
- # ==================== UI ====================
 
 
 
 
 
 
 
 
110
 
111
- with gr.Blocks() as demo:
112
- gr.Markdown("# ๐Ÿ“ Summary Grader")
 
 
 
113
 
114
- with gr.Tab("Standard"):
115
- name = gr.Textbox(label="Name")
116
- cls = gr.Textbox(label="Class")
117
- title = gr.Textbox(label="Title")
118
- summary = gr.Textbox(label="Summary", lines=5)
119
- btn = gr.Button("Grade")
120
- out = gr.Markdown()
121
 
122
- btn.click(grade_standard, [name, cls, title, summary], [out])
 
 
 
 
 
 
123
 
124
- with gr.Tab("Passage"):
125
- pname = gr.Textbox(label="Name")
126
- pcls = gr.Textbox(label="Class")
127
- ans = gr.Textbox(label="Answer", lines=5)
128
- pbtn = gr.Button("Submit")
129
- pout = gr.Markdown()
130
 
131
- pbtn.click(grade_passage_mode, [pname, pcls, ans, gr.State(2), gr.State("moderate")], [pout, gr.State(), gr.State()])
132
 
133
  if __name__ == "__main__":
134
- demo.launch()
 
 
 
 
 
1
  import os, json, re, time, math, random, logging
2
  import gradio as gr
3
  from openai import OpenAI
4
  from datetime import datetime, timedelta
5
 
6
  # ==================== LOGGING ====================
7
+ logging.basicConfig(
8
+ level=logging.INFO,
9
+ format="%(asctime)s [%(levelname)s] %(message)s"
10
+ )
11
  log = logging.getLogger(__name__)
12
 
13
+ # ==================== LLM CONFIG ====================
14
+ DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
15
+ DEEPSEEK_BASE_URL = os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com/v1")
16
+ DEEPSEEK_MODEL = os.getenv("DEEPSEEK_MODEL", "deepseek-chat")
17
+
18
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
19
+ OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
20
+
21
+ # ==================== GOOGLE SHEETS / DOC CONFIG ====================
22
+ SVC_JSON = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON")
23
+ SHEET_ID = os.getenv("SHEETS_SPREADSHEET_ID")
24
+ MASTER_DOC_ID = "1IW_XsQsR3AIHpaxY3tJZuEujClC_KIHb0QeYhKLYbUM"
25
+
26
+ # ==================== RATE LIMITING ====================
27
+ # Simple in-memory per-session rate limit: max N LLM calls per rolling window
28
+ _rate_store: dict[str, list[float]] = {}
29
+ RATE_LIMIT_CALLS = 20 # max calls
30
+ RATE_LIMIT_WINDOW = 3600 # per hour (seconds)
31
+
32
+ def _check_rate_limit(key: str) -> bool:
33
+ """Returns True if allowed, False if rate-limited."""
34
+ now = time.time()
35
+ window_start = now - RATE_LIMIT_WINDOW
36
+ calls = [t for t in _rate_store.get(key, []) if t > window_start]
37
+ if len(calls) >= RATE_LIMIT_CALLS:
38
+ log.warning(f"Rate limit hit for key={key}")
39
+ return False
40
+ calls.append(now)
41
+ _rate_store[key] = calls
42
+ return True
43
+
44
+ # ==================== PASSAGE FILES ====================
45
+ # Check both root and passages/ subfolder so it works regardless of where files are uploaded
46
+ PASSAGE_DIR = "passages"
47
+
48
+ def load_passage(n: int) -> str | None:
49
+ candidates = [
50
+ f"pssg{n}.txt", # root of repo
51
+ os.path.join(PASSAGE_DIR, f"pssg{n}.txt"), # passages/ subfolder
52
+ ]
53
+ for path in candidates:
54
+ if os.path.exists(path):
55
+ with open(path, "r", encoding="utf-8") as f:
56
+ return f.read().strip()
57
+ log.info(f"Passage file not found in root or passages/: pssg{n}.txt")
58
+ return None
59
+
60
+ def passages_for_level(level: int) -> list[str]:
61
+ """Count = level + 1, minimum 1."""
62
+ count = max(1, level + 1)
63
+ result = []
64
+ for i in range(1, count + 1):
65
+ p = load_passage(i)
66
+ if p:
67
+ result.append(p)
68
+ return result
69
+
70
+ def extract_english_only(passage_text: str) -> str:
71
+ """
72
+ Passages have English first, then Bengali below.
73
+ We split on the first Bengali character to extract only English lines.
74
+ """
75
+ lines = passage_text.splitlines()
76
+ english_lines = []
77
+ for line in lines:
78
+ # Stop at first line containing Bengali Unicode range (0x0980-0x09FF)
79
+ if re.search(r'[\u0980-\u09FF]', line):
80
+ break
81
+ english_lines.append(line)
82
+ return "\n".join(english_lines).strip()
83
+
84
+ # ==================== SVC JSON VALIDATION ====================
85
+ def validate_svc_json(raw: str) -> dict:
86
+ """Parse and validate service account JSON structure before use."""
87
+ try:
88
+ data = json.loads(raw)
89
+ except Exception as e:
90
+ raise ValueError(f"GOOGLE_SERVICE_ACCOUNT_JSON is not valid JSON: {e}")
91
+ required_keys = {"type", "project_id", "private_key_id", "private_key", "client_email"}
92
+ missing = required_keys - set(data.keys())
93
+ if missing:
94
+ raise ValueError(f"Service account JSON missing keys: {missing}")
95
+ if data.get("type") != "service_account":
96
+ raise ValueError("Service account JSON 'type' must be 'service_account'")
97
+ return data
98
+
99
+ def get_svc_creds(scopes: list[str]):
100
+ from google.oauth2.service_account import Credentials
101
+ svc_data = validate_svc_json(SVC_JSON)
102
+ return Credentials.from_service_account_info(svc_data, scopes=scopes)
103
+
104
+ # ==================== PROMPTS (STANDARD) ====================
105
+ RUBRIC_USER_TEXT = """
106
+ You are a teacher grading a student's summary.
107
+ Step 0: Quality Check.
108
+ - Check if the text is "nonsensical" (random arbitrary words, or same sentence repeated).
109
+ - If nonsense/repetitive, set "is_nonsense": true; otherwise false.
110
+
111
+ Step 1: Decide if you KNOW the story.
112
+ - If you know it, set "knows_story": true; else false.
113
 
114
+ Step 2: Scoring.
115
+ - If knows_story=true, grade:
116
+ 1) Comprehension (1-5)
117
+ 2) Expression (1-5)
118
+ 3) Reflection/Moral Takeaway (1-5)
119
+ 4) Grammar (lenient): identify grammar/spelling/punctuation issues.
120
+ - If knows_story=false, set Comprehension to null and still do Expression, Reflection, Grammar.
121
+
122
+ Grammar issue format: for each issue provide
123
+ - "error_excerpt" (short snippet โ‰ค120 chars),
124
+ - "correction" (corrected snippet only),
125
+ - "explanation" (one short reason),
126
+ - "start_index" (0-based char position in ORIGINAL text),
127
+ - "end_index" (exclusive char position).
128
+
129
+ IMPORTANT for start_index/end_index: count characters carefully from the start of the
130
+ ORIGINAL text. Verify the excerpt actually appears at those positions.
131
+
132
+ Also provide "corrected_summary" (light edits only) and "remarks" (1-2 sentences).
133
+ """
134
+
135
+ JSON_SCHEMA_HINT = """
136
+ Return ONLY raw JSON (no markdown fences, no extra text), exactly this structure:
137
+ {
138
+ "is_nonsense": true,
139
+ "knows_story": true,
140
+ "scores": {
141
+ "Comprehension": 3,
142
+ "Expression": 4,
143
+ "Reflection/Moral Takeaway": 3
144
+ },
145
+ "grammar_issues": [
146
+ {
147
+ "error_excerpt": "he go to school",
148
+ "correction": "he goes to school",
149
+ "explanation": "Subject-verb agreement",
150
+ "start_index": 12,
151
+ "end_index": 27
152
+ }
153
+ ],
154
+ "corrected_summary": "...",
155
+ "remarks": "..."
156
+ }
157
+ Rules:
158
+ - Comprehension must be null (not a string) if knows_story is false.
159
+ - grammar_issues must be [] if none found.
160
+ - All numeric scores must be plain integers, not strings.
161
+ - No trailing commas anywhere.
162
+ """
163
+
164
+ # ==================== PASSAGE GRADING PROMPT ====================
165
+ def passage_grading_prompt(original_english: str, student_text: str) -> str:
166
+ return f"""
167
+ You are grading a student's attempt to reproduce an English passage from memory.
168
+
169
+ ORIGINAL PASSAGE (English only):
170
+ \"\"\"
171
+ {original_english}
172
+ \"\"\"
173
+
174
+ STUDENT'S ATTEMPT:
175
+ \"\"\"
176
+ {student_text}
177
+ \"\"\"
178
+
179
+ Instructions:
180
+ - Compare word by word. COMPLETELY IGNORE capitalisation and spacing differences.
181
+ - IGNORE minor punctuation differences (missing comma, full stop).
182
+ - Score 1 to 5:
183
+ 5 = perfect or near-perfect (only trivial differences)
184
+ 4 = mostly correct, 1-2 wrong/missing words per sentence
185
+ 3 = roughly half the content correct, some sentences missing or wrong
186
+ 2 = significant errors, most words wrong or missing
187
+ 1 = barely matches, only a few words in common
188
+ - is_nonsense = true ONLY if the text is random gibberish or mindless repetition of
189
+ the same word/phrase (NOT just a bad copy โ€” bad copies get score 1 or 2).
190
+
191
+ Return ONLY raw JSON, no markdown, no extra text:
192
+ {{
193
+ "score": 3,
194
+ "is_nonsense": false,
195
+ "remarks": "One or two sentences of specific feedback."
196
+ }}
197
+ """
198
+
199
+ # ==================== HELPERS ====================
200
  def is_nonsense_heuristic(text: str) -> tuple[bool, str]:
201
+ """
202
+ Multi-signal nonsense detector. Returns (is_bad, reason).
203
+ Checks:
204
+ 1. Unique word ratio (weak signal, used with other checks)
205
+ 2. Bigram repetition (catches 'cat dog cat dog')
206
+ 3. Single repeated token
207
+ 4. Ratio of unique bigrams to total bigrams
208
+ """
209
  words = re.findall(r"\b\w+\b", text.lower())
210
  if len(words) < 5:
211
  return False, ""
212
 
213
+ # Check 1: single word repeated almost exclusively
214
  from collections import Counter
215
  word_counts = Counter(words)
216
  most_common_word, most_common_count = word_counts.most_common(1)[0]
217
  if most_common_count / len(words) > 0.5:
218
+ return True, f"Word '{most_common_word}' repeated {most_common_count} times."
219
 
220
+ # Check 2: bigram repetition ratio
221
  bigrams = list(zip(words, words[1:]))
222
  if bigrams:
223
  unique_bigrams = set(bigrams)
224
+ bigram_ratio = len(unique_bigrams) / len(bigrams)
225
+ if bigram_ratio < 0.25 and len(words) > 15:
226
+ return True, f"Highly repetitive bigram pattern detected."
227
+
228
+ # Check 3: overall unique word ratio (only flag if very low AND many words)
229
+ unique_ratio = len(set(words)) / len(words)
230
+ if unique_ratio < 0.20 and len(words) > 20:
231
+ return True, f"Only {round(unique_ratio*100)}% unique words."
232
 
233
  return False, ""
234
 
235
+ def student_key(name: str, klass: str) -> str:
236
+ first = str(name).strip().split()[0].lower()
237
+ return f"{first}_{str(klass).strip().lower()}"
 
238
 
239
+ def week_bounds(d):
240
+ sunday = d - timedelta(days=(d.weekday() + 1) % 7)
241
+ saturday = sunday + timedelta(days=6)
242
+ return sunday, saturday
243
 
244
+ def _retry_delays(n: int):
245
+ base = 0.6
246
+ for i in range(n):
247
+ yield base * (2 ** i) * (0.8 + 0.4 * random.random())
248
 
249
+ def call_openai_compatible(api_key, base_url, model, messages, tries=3):
250
+ last_err = None
251
+ client = OpenAI(api_key=api_key, base_url=base_url) if base_url else OpenAI(api_key=api_key)
252
+ for delay in list(_retry_delays(tries)) + [0]:
253
+ try:
254
+ resp = client.chat.completions.create(model=model, messages=messages)
255
+ return resp.choices[0].message.content, f"{'DeepSeek' if 'deepseek' in (base_url or '') else 'OpenAI'} ({model})"
256
+ except Exception as e:
257
+ last_err = e
258
+ log.warning(f"LLM call failed (will retry): {e}")
259
+ if delay > 0:
260
+ time.sleep(delay)
261
+ raise RuntimeError(f"LLM failed after {tries} attempts: {last_err}")
262
 
263
+ def llm_chat(messages, rate_key: str = "global"):
264
+ if not _check_rate_limit(rate_key):
265
+ raise RuntimeError("โš ๏ธ Too many requests. Please wait a few minutes before trying again.")
266
+ if DEEPSEEK_API_KEY:
267
+ try:
268
+ return call_openai_compatible(DEEPSEEK_API_KEY, DEEPSEEK_BASE_URL, DEEPSEEK_MODEL, messages, 3)
269
+ except Exception as e:
270
+ ds_err = str(e)
271
+ log.error(f"DeepSeek failed: {ds_err}")
272
+ else:
273
+ ds_err = "DeepSeek key not set."
274
+ if OPENAI_API_KEY:
275
+ try:
276
+ return call_openai_compatible(OPENAI_API_KEY, None, OPENAI_MODEL, messages, 2)
277
+ except Exception as e:
278
+ oe = str(e)
279
+ log.error(f"OpenAI fallback failed: {oe}")
280
+ raise RuntimeError(f"DeepSeek: {ds_err}\nOpenAI: {oe}")
281
+ raise RuntimeError(f"{ds_err}\nNo OpenAI fallback configured.")
282
+
283
+ def salvage_json(s: str) -> dict:
284
+ """Robust JSON parser โ€” handles markdown fences, trailing commas, smart quotes."""
285
+ s = s.strip()
286
+ # Strip markdown fences
287
+ s = re.sub(r"^\s*```(?:json)?\s*", "", s)
288
+ s = re.sub(r"\s*```\s*$", "", s)
289
+ # Fix smart quotes
290
+ s = s.replace("\u201c", '"').replace("\u201d", '"').replace("\u2019", "'").replace("\u2018", "'")
291
+ # Extract outermost JSON object
292
+ m = re.search(r"\{.*\}\s*$", s, flags=re.S)
293
+ if m:
294
+ s = m.group(0)
295
+ # Fix trailing commas before } or ]
296
+ s = re.sub(r",\s*([}\]])", r"\1", s)
297
+ # Fix missing values for index fields (LLM sometimes omits them)
298
+ s = re.sub(r'"end_index"\s*:\s*(?=(,|\}))', '"end_index": 0', s)
299
+ s = re.sub(r'"start_index"\s*:\s*(?=(,|\}))', '"start_index": 0', s)
300
+
301
+ data = json.loads(s) # will raise if still invalid โ€” caller handles
302
+
303
+ # Sanitise grammar_issues
304
+ issues = data.get("grammar_issues", [])
305
+ safe_issues = []
306
+ if isinstance(issues, list):
307
+ for it in issues:
308
+ if not isinstance(it, dict):
309
+ continue
310
+ try: si = int(it.get("start_index", 0))
311
+ except: si = 0
312
+ try: ei = int(it.get("end_index", 0))
313
+ except: ei = 0
314
+ safe_issues.append({
315
+ "error_excerpt": str(it.get("error_excerpt", ""))[:200],
316
+ "correction": str(it.get("correction", ""))[:200],
317
+ "explanation": str(it.get("explanation", ""))[:200],
318
+ "start_index": si,
319
+ "end_index": ei,
320
+ })
321
+ data["grammar_issues"] = safe_issues
322
+ return data
323
+
324
+ def salvage_passage_json(s: str) -> dict:
325
+ """salvage_json variant for the simpler passage-grading response."""
326
+ s = s.strip()
327
+ s = re.sub(r"^\s*```(?:json)?\s*", "", s)
328
+ s = re.sub(r"\s*```\s*$", "", s)
329
+ s = s.replace("\u201c", '"').replace("\u201d", '"').replace("\u2019", "'")
330
+ m = re.search(r"\{.*\}\s*$", s, flags=re.S)
331
+ if m:
332
+ s = m.group(0)
333
+ s = re.sub(r",\s*([}\]])", r"\1", s)
334
+ data = json.loads(s)
335
+ # Ensure required keys have sane defaults
336
+ data.setdefault("score", 1)
337
+ data.setdefault("is_nonsense", False)
338
+ data.setdefault("remarks", "")
339
+ try:
340
+ data["score"] = max(1.0, min(5.0, float(data["score"])))
341
+ except Exception:
342
+ log.warning(f"Could not parse score from passage JSON, defaulting to 1")
343
+ data["score"] = 1.0
344
+ return data
345
+
346
+ def stars_bar(value, max_stars: int = 5) -> str:
347
+ if value is None:
348
+ return "โ€”"
349
+ try:
350
+ v = float(value)
351
+ except Exception:
352
+ return "โ€”"
353
+ if v <= 0:
354
+ return "โ€”"
355
+ n_int = max(0, min(max_stars, int(round(v))))
356
+ return "โญ" * n_int
357
 
358
  def count_words(text: str) -> int:
359
+ return len(re.findall(r"\b\w[\w'-]*\b", text))
360
+
361
+ def length_stars(word_count: int) -> int:
362
+ if word_count < 100: return 0
363
+ if word_count <= 150: return 1
364
+ if word_count <= 200: return 3
365
+ if word_count <= 250: return 4
366
+ return 5
367
+
368
+ def clamp_1_to_5(x) -> int:
369
+ try:
370
+ return max(1, min(5, int(x)))
371
+ except Exception:
372
+ return 1
373
+
374
+ def grammar_stars_from_count(n: int) -> float:
375
+ if n >= 50: return 0.0
376
+ return max(0.0, 5.0 - 0.1 * n)
377
+
378
+ def annotate_original_with_issues(text: str, issues: list) -> str:
379
+ """
380
+ Annotate text with grammar issues.
381
+ Falls back gracefully if LLM indices are wrong โ€” uses fuzzy search.
382
+ """
383
+ valid = []
384
+ for i, it in enumerate(issues, 1):
385
+ si, ei = int(it.get("start_index", 0)), int(it.get("end_index", 0))
386
+ excerpt = it.get("error_excerpt", "")
387
+
388
+ # Validate LLM-provided indices
389
+ if 0 <= si < ei <= len(text) and text[si:ei].lower() == excerpt[:ei-si].lower():
390
+ valid.append((si, ei, i))
391
+ elif excerpt:
392
+ # Fuzzy fallback: find excerpt in text
393
+ idx = text.lower().find(excerpt.lower())
394
+ if idx != -1:
395
+ valid.append((idx, idx + len(excerpt), i))
396
+ else:
397
+ log.info(f"Grammar issue #{i}: could not locate excerpt '{excerpt[:30]}' in text โ€” skipping annotation")
398
+ # Still list in table below, just skip inline annotation
399
+ # else: skip silently
400
+
401
+ valid.sort(key=lambda x: x[0])
402
+ out, cursor, last_end = [], 0, -1
403
+ for si, ei, idx in valid:
404
+ if si < last_end:
405
+ continue
406
+ out.append(text[cursor:si])
407
+ out.append(f"[[#{idx}: {text[si:ei]}]]")
408
+ cursor, last_end = ei, ei
409
+ out.append(text[cursor:])
410
+ return "".join(out)
411
+
412
+ def now_ist() -> datetime:
413
+ return datetime.utcnow() + timedelta(hours=5, minutes=30)
414
+
415
+ # ==================== GOOGLE SHEETS ====================
416
+ def get_gspread_ws():
417
+ import gspread
418
+ creds = get_svc_creds(["https://www.googleapis.com/auth/spreadsheets"])
419
+ gc = gspread.authorize(creds)
420
+ sh = gc.open_by_key(SHEET_ID)
421
+ return sh.worksheet("Scores")
422
+
423
+ def get_student_level(name: str, klass: str, mode: str) -> int:
424
+ """Fetch persisted level from Sheets. Returns 2 on any failure."""
425
+ if not SVC_JSON:
426
+ log.info("SVC_JSON not set โ€” using default level 2")
427
+ return 2
428
+ try:
429
+ ws = get_gspread_ws()
430
+ records = ws.get_all_records()
431
+ key = student_key(name, klass)
432
+ best_level = 2
433
+ best_ts = None
434
+ for r in records:
435
+ mode_col = str(r.get("Mode", "") or r.get("Summary", "") or "")
436
+ if mode.lower() not in mode_col.lower():
437
+ continue
438
+ try:
439
+ rkey = student_key(str(r.get("Name", "")), str(r.get("Classs") or r.get("Class", "")))
440
+ except Exception:
441
+ continue
442
+ if rkey != key:
443
+ continue
444
+ m = re.search(r'-(\d+)-', mode_col)
445
+ if m:
446
+ try:
447
+ ts_str = str(r.get("Date") or r.get("Timestamp", ""))
448
+ ts = datetime.strptime(ts_str, "%Y-%m-%d %H:%M:%S")
449
+ if best_ts is None or ts > best_ts:
450
+ best_ts = ts
451
+ best_level = int(m.group(1))
452
+ except Exception as parse_err:
453
+ log.debug(f"Level parse error for row {r}: {parse_err}")
454
+ log.info(f"Loaded level={best_level} for {key} mode={mode}")
455
+ return best_level
456
+ except Exception as e:
457
+ log.error(f"get_student_level failed: {e}")
458
+ return 2
459
+
460
+ def append_to_sheet(row: list, student_name: str, student_class: str, avg: float, mode_label: str) -> str:
461
+ """
462
+ Append best score. Instead of deleting old row (risky), we ADD a new row and mark
463
+ the old one as superseded by prepending 'OLD|' to its Mode column.
464
+ This preserves audit trail while still allowing best-score logic.
465
+ """
466
+ if not SVC_JSON:
467
+ return "โš ๏ธ Sheets not configured (GOOGLE_SERVICE_ACCOUNT_JSON missing)."
468
+ try:
469
+ ws = get_gspread_ws()
470
+ records = ws.get_all_records()
471
+ today = now_ist().date()
472
+ sun, sat = week_bounds(today)
473
+ key = student_key(student_name, student_class)
474
+ mode_prefix = mode_label.split("-")[0]
475
+
476
+ # Find this week's best for same student+mode
477
+ best_row_idx = None
478
+ best_score = -999.0
479
+ for i, r in enumerate(records, start=2):
480
+ try:
481
+ ts_str = str(r.get("Date") or r.get("Timestamp", ""))
482
+ ts = datetime.strptime(ts_str, "%Y-%m-%d %H:%M:%S").date()
483
+ mode_col = str(r.get("Mode", "") or r.get("Summary", "") or "")
484
+ # Skip already-superseded rows
485
+ if mode_col.startswith("OLD|"):
486
+ continue
487
+ rkey = student_key(str(r.get("Name", "")), str(r.get("Classs") or r.get("Class", "")))
488
+ if sun <= ts <= sat and rkey == key and mode_prefix in mode_col:
489
+ prev = float(r.get("Star") or r.get("Result") or 0)
490
+ if prev > best_score:
491
+ best_score = prev
492
+ best_row_idx = i
493
+ except Exception as row_err:
494
+ log.debug(f"Sheet row {i} parse error: {row_err}")
495
+ continue
496
+
497
+ if best_row_idx is not None and avg <= best_score:
498
+ log.info(f"Not saving: existing best={best_score} >= new={avg}")
499
+ return f"โš ๏ธ A better score ({best_score:.2f}) already exists this week. Not saved."
500
+
501
+ # Mark old row as superseded (audit trail preserved)
502
+ if best_row_idx is not None:
503
+ try:
504
+ # Find the Mode/Summary column index (1-based)
505
+ headers = ws.row_values(1)
506
+ mode_col_idx = None
507
+ for ci, h in enumerate(headers, start=1):
508
+ if h in ("Mode", "Summary"):
509
+ mode_col_idx = ci
510
+ break
511
+ if mode_col_idx:
512
+ old_val = ws.cell(best_row_idx, mode_col_idx).value or ""
513
+ ws.update_cell(best_row_idx, mode_col_idx, f"OLD|{old_val}")
514
+ log.info(f"Marked row {best_row_idx} as OLD")
515
+ except Exception as mark_err:
516
+ log.warning(f"Could not mark old row: {mark_err}")
517
+
518
+ ws.append_row(row, value_input_option="USER_ENTERED")
519
+ log.info(f"Appended new row for {key} mode={mode_label} score={avg}")
520
+ return "โœ… Score saved to Google Sheets!"
521
+ except Exception as e:
522
+ log.error(f"append_to_sheet failed: {e}")
523
+ return f"โŒ Sheets error: {e}"
524
+
525
+ def save_to_master_doc(name: str, klass: str, title: str, summary: str) -> str:
526
+ try:
527
+ from googleapiclient.discovery import build
528
+ creds = get_svc_creds([
529
+ "https://www.googleapis.com/auth/documents",
530
+ "https://www.googleapis.com/auth/drive"
531
+ ])
532
+ service = build('docs', 'v1', credentials=creds)
533
+ timestamp = now_ist().strftime('%Y-%m-%d %H:%M:%S')
534
+ new_entry = (
535
+ f"\n\n### START_ENTRY ###\n"
536
+ f"[[METADATA|NAME:{name.strip()}|CLASS:{klass.strip()}|DATE:{timestamp}|TITLE:{title.strip()}]]\n"
537
+ f"--- ESSAY START ---\n{summary.strip()}\n--- ESSAY END ---\n"
538
+ f"### END_ENTRY ###\n"
539
+ )
540
+ doc = service.documents().get(documentId=MASTER_DOC_ID).execute()
541
+ end_index = doc['body']['content'][-1]['endIndex'] - 1
542
+ service.documents().batchUpdate(
543
+ documentId=MASTER_DOC_ID,
544
+ body={'requests': [{'insertText': {'location': {'index': end_index}, 'text': new_entry}}]}
545
+ ).execute()
546
+ log.info(f"Saved to master doc: {name} / {title}")
547
+ return "โœ… Saved to Master Doc"
548
+ except Exception as e:
549
+ log.error(f"save_to_master_doc failed: {e}")
550
+ return f"โŒ Doc Error: {e}"
551
+
552
+ # ==================== SCORING RULES ====================
553
+ # MODERATE: max=7 at level 2. Level up if >=5 stars. Level down if <3. Stay for 3-4.
554
+ # For levels above 2: max = 7 + (level-2)*1.2*5 (bonus on top of base 7)
555
+ # For levels below 2: max stays 7 (no reduction)
556
+ # EASY: max=5 at all levels. Level up if >=4. Level down if <=3.
557
+
558
+ def compute_max_stars_moderate(level: int) -> float:
559
+ base = 7.0
560
+ if level <= 2:
561
+ return base
562
+ return base + (level - 2) * 1.2 * 5.0
563
+
564
+ def compute_max_stars_easy(level: int) -> float:
565
+ return 5.0 # fixed max for easy mode
566
 
567
+ def level_change_moderate(raw_score: float, current_level: int) -> int:
568
+ """Returns new level based on raw 1-5 LLM score."""
569
+ # raw_score is on 1-5 scale from LLM
570
+ # We need to translate to "stars out of max" for threshold check
571
+ # Level up: raw >= 5 (out of 7, that's ~5/7 * max)
572
+ # Level thresholds are applied on raw_score directly since LLM scores 1-5
573
+ if raw_score >= 5:
574
+ return current_level + 1
575
+ elif raw_score < 3:
576
+ return max(0, current_level - 1)
577
+ return current_level # 3 or 4 โ†’ stay
578
 
579
+ def level_change_easy(raw_score: float, current_level: int) -> int:
580
+ """Easy mode: up if >=4, down if <=3."""
581
+ if raw_score >= 4:
582
+ return current_level + 1
583
+ elif raw_score <= 3:
584
+ return max(0, current_level - 1)
585
+ return current_level
586
+
587
+ # ==================== RULES TEXT ====================
588
+ STANDARD_RULES = """
589
+ ## ๐Ÿ“‹ Standard Mode โ€” Full Rules
590
+
591
+ Write a **summary** of a story or book you have read. The app will grade it automatically.
592
+
593
+ ### How it's marked
594
+ Each category is scored out of 5, then **multiplied by 5** โ†’ maximum **25 โญ**
595
+
596
+ | Category | What we look for |
597
+ |---|---|
598
+ | ๐Ÿ“– Comprehension | Did you understand the story correctly? |
599
+ | โœ๏ธ Expression | Is your writing clear, fluent and well-organised? |
600
+ | ๐Ÿ’ก Reflection / Moral | Did you capture the lesson or moral of the story? |
601
+ | ๐Ÿ“ Length | Min 100 words needed. 250+ words = full marks. |
602
+ | โœ… Grammar | Fewer mistakes = more stars. |
603
+
604
+ > **Note:** If the AI doesn't recognise the story, Comprehension is skipped and the average is over 4 categories instead of 5.
605
+
606
+ ### โš ๏ธ Penalties & Rules
607
+ - Writing **gibberish or repeating the same words** โ†’ **โˆ’1 โญ**
608
+ - **Copy-paste is disabled** โ€” you must type manually
609
+ - After grading you'll see a **corrected version** of your summary
610
+ - You can **redo as many times as you like** โ€” only your **best score** is saved
611
+ """
612
+
613
+ MODERATE_RULES = """
614
+ ## ๐Ÿ“‹ Moderate Mode โ€” Full Rules
615
+
616
+ You'll see **English passages** with Bengali translations below each one.
617
+ Read them, then **the passage disappears after a time limit** โ€” type it back from memory!
618
+
619
+ ### โฑ๏ธ Timer
620
+ | Level | Passage visible for |
621
+ |---|---|
622
+ | Level 0 | 1 minute |
623
+ | Level 1 | 2 minutes |
624
+ | Level 2 | 3 minutes |
625
+ | Level 3 | 4 minutes |
626
+ | Level N | (N+1) minutes |
627
+
628
+ After time is up the passage is **hidden** โ€” type what you remember!
629
+
630
+ ### Scoring
631
+ | LLM Score | Meaning |
632
+ |---|---|
633
+ | 5/5 | Perfect or near-perfect reproduction |
634
+ | 4/5 | Mostly correct, 1-2 minor word differences per sentence |
635
+ | 3/5 | About half correct, some sentences missing or wrong |
636
+ | 2/5 | Significant errors, most words wrong |
637
+ | 1/5 | Barely matches |
638
+
639
+ ### ๐ŸŽฎ Level System
640
+ - Your level is **saved across sessions** (starts at Level 2 for new students)
641
+ - **Passages shown = level + 1** (Level 2 โ†’ 3 passages, Level 3 โ†’ 4 passages, etc.)
642
+ - **Max stars at Level 2 = 7 โญ** (base)
643
+ - **Above Level 2:** max = 7 + (levelโˆ’2) ร— 1.2 ร— 5
644
+ - **Level 2 or below:** max stays at 7
645
+
646
+ ### ๐Ÿ”ผ Level Changes (after each attempt)
647
+ | Your score | Result |
648
+ |---|---|
649
+ | LLM gives 5/5 | Level UP โ†‘ |
650
+ | LLM gives 3 or 4 out of 5 | Stay same level |
651
+ | LLM gives below 3/5 | Level DOWN โ†“ |
652
+
653
+ ### โš ๏ธ Rules
654
+ - Capitalisation and spacing **do not matter** โ€” the app ignores them
655
+ - Gibberish or mindless repetition โ†’ **โˆ’1 โญ**
656
+ - **Copy-paste is disabled**
657
+ """
658
+
659
+ EASY_RULES = """
660
+ ## ๐Ÿ“‹ Easy Mode โ€” Full Rules
661
+
662
+ You'll see **English passages** with Bengali translations below each one.
663
+ The passage **stays visible** the whole time โ€” just read and type it back accurately!
664
+
665
+ ### Scoring (max = 5 โญ at all levels)
666
+ | LLM Score | Meaning |
667
+ |---|---|
668
+ | 5/5 | Perfect or near-perfect reproduction |
669
+ | 4/5 | Mostly correct, 1-2 minor word differences per sentence |
670
+ | 3/5 | About half correct, some sentences missing or wrong |
671
+ | 2/5 | Significant errors, most words wrong |
672
+ | 1/5 | Barely matches |
673
+
674
+ ### ๐ŸŽฎ Level System
675
+ - Your level is **saved across sessions** (starts at Level 2 for new students)
676
+ - **Passages shown = level + 1**
677
+
678
+ ### ๐Ÿ”ผ Level Changes
679
+ | Your score | Result |
680
+ |---|---|
681
+ | LLM gives 4 or 5 out of 5 | Level UP โ†‘ |
682
+ | LLM gives 3 or below | Level DOWN โ†“ |
683
+
684
+ ### โš ๏ธ Rules
685
+ - Capitalisation and spacing **do not matter**
686
+ - Gibberish or mindless repetition โ†’ **โˆ’1 โญ**
687
+ - **Copy-paste is disabled**
688
+ """
689
+
690
+ # ==================== STANDARD MODE GRADING ====================
691
+ def intro_message_standard(name: str, klass: str) -> str:
692
+ if not name.strip() or not klass.strip():
693
+ return "๐Ÿ‘‹ Please enter your name and class first!"
694
+ return f"### ๐ŸŒŸ Hi {name} of {klass}!\n\nYou're in **Standard Mode**. Read the rules above and write your summary below. Good luck!"
695
+
696
+ def grade_standard(student_name: str, student_class: str, title: str, student_summary: str):
697
  try:
698
  if not all([student_name.strip(), student_class.strip(), title.strip(), student_summary.strip()]):
699
  return "โš ๏ธ Please fill in all fields.", "", ""
700
 
701
+ rate_key = student_key(student_name, student_class)
702
+ prompt = f"TITLE: {title}\nSUMMARY: {student_summary}\n{RUBRIC_USER_TEXT}\n{JSON_SCHEMA_HINT}"
703
+ content, model_used = llm_chat([{"role": "user", "content": prompt}], rate_key=rate_key)
704
+ log.info(f"Standard grade: {student_name} / {title} โ€” model={model_used}")
705
 
706
+ data = salvage_json(content)
 
 
 
 
 
 
 
707
 
708
+ is_nonsense_ai = bool(data.get("is_nonsense", False))
709
+ knows_story = bool(data.get("knows_story", False))
710
+ scores = data.get("scores", {}) or {}
711
+ comp = scores.get("Comprehension", None)
712
+ expr = clamp_1_to_5(scores.get("Expression", 1))
713
+ refl = clamp_1_to_5(scores.get("Reflection/Moral Takeaway", 1))
714
+ issues = data.get("grammar_issues", [])
715
+ corrected = (data.get("corrected_summary") or "").strip()
716
+ remarks = (data.get("remarks") or "").strip()
717
 
718
+ wc = count_words(student_summary)
719
+ len_s = length_stars(wc)
720
+ grammar_star = round(grammar_stars_from_count(len(issues)), 1)
721
+
722
+ # Heuristic nonsense check (multi-signal)
723
+ heuristic_bad, heuristic_reason = is_nonsense_heuristic(student_summary)
724
+
725
+ reasons = []
726
+ if is_nonsense_ai:
727
+ reasons.append("AI flagged this as nonsense or gibberish.")
728
+ if heuristic_bad:
729
+ reasons.append(heuristic_reason)
730
+
731
+ is_failing = len(reasons) > 0
732
+ if is_failing:
733
+ final_score = -1.0
734
+ display_stars = 0
735
+ else:
736
+ vals = [float(expr), float(refl), float(len_s), float(grammar_star)]
737
+ if knows_story and comp is not None:
738
+ vals.append(float(comp))
739
+ raw_avg = round(sum(vals) / len(vals), 2) if vals else 0.0
740
+ final_score = round(raw_avg * 5, 2) # multiply by 5 โ†’ max 25
741
+ final_score = max(0.0, final_score)
742
+ display_stars = min(25, int(round(final_score))) # capped at 25
743
+
744
+ md = ["### ๐Ÿ“š Standard Mode โ€” Grading Report"]
745
+ if is_failing:
746
+ md.append("> ## โŒ FINAL SCORE: โˆ’1 โญ")
747
+ md.append("> **Reason:** " + " | ".join(reasons))
748
+ else:
749
+ md.append(f"\n**๐Ÿ† FINAL SCORE: {final_score:.1f} / 25**")
750
+ md.append("โญ" * display_stars)
751
+
752
+ md.append(f"\n**Name:** {student_name} &nbsp;&nbsp; **Class:** {student_class}")
753
+ md.append(f"**Title:** {title} &nbsp;&nbsp; **Words:** {wc}")
754
+ md.append("\n#### Category Scores (each out of 5)")
755
+ if knows_story:
756
+ md.append(f"- ๐Ÿ“– Comprehension: {stars_bar(comp)}")
757
+ else:
758
+ md.append(f"- ๐Ÿ“– Comprehension: โ€” *(story not recognised by AI)*")
759
+ md.append(f"- โœ๏ธ Expression: {stars_bar(expr)}")
760
+ md.append(f"- ๐Ÿ’ก Reflection: {stars_bar(refl)}")
761
+ md.append(f"- ๐Ÿ“ Length ({wc} words): {stars_bar(len_s)}")
762
+ md.append(f"- โœ… Grammar ({len(issues)} issues): {stars_bar(grammar_star)}")
763
+ if remarks:
764
+ md.append(f"\n> ๐Ÿ’ฌ **Remarks:** {remarks}")
765
+
766
+ if issues:
767
+ md.append(f"\n#### ๐Ÿ”Ž Annotated Text\n```\n{annotate_original_with_issues(student_summary, issues)}\n```")
768
+ md.append("\n#### ๐Ÿ“ Grammar Issues")
769
+ for i, it in enumerate(issues, 1):
770
+ md.append(f"{i}. โŒ `{it['error_excerpt']}` โ†’ โœ… `{it['correction']}` โ€” *{it['explanation']}*")
771
 
772
+ timestamp = now_ist().strftime("%Y-%m-%d %H:%M:%S")
773
+ mode_label = "standard-2-summary"
774
+ pct = round(final_score / 25 * 100, 1) if final_score >= 0 else 0
775
+ row = [timestamp, student_name, student_class, round(final_score, 2), "25", f"{pct}%", round(final_score, 2), mode_label]
776
+ sheets_status = append_to_sheet(row, student_name, student_class, final_score, mode_label)
777
+ doc_status = save_to_master_doc(student_name, student_class, title, student_summary)
778
 
779
+ return "\n".join(md), corrected, f"{sheets_status} | {doc_status}"
780
+ except Exception as e:
781
+ log.error(f"grade_standard error: {e}", exc_info=True)
782
+ return f"### โŒ Error\n{e}", "", "Not saved."
783
+
784
+ # ==================== PASSAGE MODE GRADING ====================
785
+ def grade_passage_mode(student_name: str, student_class: str, student_text: str, level: int, mode: str):
786
  try:
787
+ if not all([student_name.strip(), student_class.strip(), student_text.strip()]):
788
+ return "โš ๏ธ Please fill in all fields.", level, ""
789
+
790
+ passages = passages_for_level(level)
791
+ if not passages:
792
+ return "โš ๏ธ No passages found. Please upload pssg1.txt etc. to the root of your HF repo (same folder as app.py).", level, ""
793
+
794
+ # Extract English-only portions for grading
795
+ english_only_passages = [extract_english_only(p) for p in passages]
796
+ combined_english = "\n\n".join(english_only_passages)
797
 
798
+ rate_key = student_key(student_name, student_class)
799
+ prompt = passage_grading_prompt(combined_english, student_text)
800
+ content, model_used = llm_chat([{"role": "user", "content": prompt}], rate_key=rate_key)
801
+ log.info(f"Passage grade: {student_name} level={level} mode={mode} model={model_used}")
802
+
803
+ data = salvage_passage_json(content) # robust parsing
804
+ raw_score = float(data.get("score", 1))
805
+ is_nonsense_ai = bool(data.get("is_nonsense", False))
806
+ remarks = str(data.get("remarks", "")).strip()
807
 
 
808
  heuristic_bad, heuristic_reason = is_nonsense_heuristic(student_text)
809
+ is_failing = is_nonsense_ai or heuristic_bad
810
 
811
+ if mode == "moderate":
812
+ max_stars = compute_max_stars_moderate(level)
813
+ new_level = level_change_moderate(raw_score, level) if not is_failing else level
814
+ else: # easy
815
+ max_stars = compute_max_stars_easy(level)
816
+ new_level = level_change_easy(raw_score, level) if not is_failing else level
817
 
818
  if is_failing:
819
+ final_score = -1.0
820
+ display_stars = 0
821
+ fail_reason = is_nonsense_ai and "AI flagged as gibberish." or heuristic_reason
822
+ else:
823
+ # Scale raw_score (1-5) to (0 - max_stars), floor at 0
824
+ final_score = max(0.0, round((raw_score / 5.0) * max_stars, 2))
825
+ display_stars = min(int(max_stars) + 1, int(round(final_score))) # capped at max_stars (not max+5)
826
+
827
+ mode_title = "๐ŸŽฎ Moderate" if mode == "moderate" else "๐ŸŸข Easy"
828
+ md = [f"### {mode_title} Mode โ€” Results (Level {level})"]
829
+ if is_failing:
830
+ md.append("> ## โŒ FINAL SCORE: โˆ’1 โญ")
831
+ md.append(f"> **Reason:** {fail_reason if is_nonsense_ai else heuristic_reason}")
832
+ else:
833
+ md.append(f"\n**๐Ÿ† Score: {final_score:.1f} / {max_stars:.1f}**")
834
+ md.append("โญ" * display_stars)
835
+ md.append(f"\n*(LLM accuracy: {raw_score:.0f}/5)*")
836
 
837
+ md.append(f"\n**Name:** {student_name} &nbsp;&nbsp; **Class:** {student_class}")
838
+ md.append(f"**Level:** {level} &nbsp;&nbsp; **Passages used:** {len(passages)}")
839
+ if remarks:
840
+ md.append(f"\n> ๐Ÿ’ฌ {remarks}")
841
 
842
+ if new_level > level:
843
+ md.append(f"\n๐ŸŽ‰ **Level UP! {level} โ†’ {new_level}**")
844
+ elif new_level < level:
845
+ md.append(f"\n๐Ÿ“‰ **Level DOWN: {level} โ†’ {new_level}**")
846
+ else:
847
+ md.append(f"\nโžก๏ธ **Level stays at {level}**")
848
 
849
+ timestamp = now_ist().strftime("%Y-%m-%d %H:%M:%S")
850
+ mode_label = f"{mode.lower()}-{new_level}-summary" # save NEW level
851
+ pct = round(final_score / max_stars * 100, 1) if max_stars > 0 and final_score >= 0 else 0
852
+ row = [timestamp, student_name, student_class, round(final_score, 2),
853
+ str(round(max_stars, 1)), f"{pct}%", round(final_score, 2), mode_label]
854
+ sheets_status = append_to_sheet(row, student_name, student_class, final_score, mode_label)
855
+ doc_status = save_to_master_doc(student_name, student_class, f"{mode}-level{level}", student_text)
856
+
857
+ return "\n".join(md), new_level, f"{sheets_status} | {doc_status}"
858
  except Exception as e:
859
+ log.error(f"grade_passage_mode error: {e}", exc_info=True)
860
+ return f"### โŒ Error\n{e}", level, "Not saved."
861
+
862
+ # ==================== DISPLAY HELPERS ====================
863
+ def format_passages_display(passages: list[str]) -> str:
864
+ if not passages:
865
+ return "โš ๏ธ No passages loaded. Please upload pssg1.txt, pssg2.txt etc. to the root of your HF repo (same folder as app.py)."
866
+ parts = []
867
+ for i, p in enumerate(passages, 1):
868
+ parts.append(f"### Passage {i}\n{p}")
869
+ return "\n\n---\n\n".join(parts)
870
+
871
+ # ==================== JAVASCRIPT ====================
872
+ block_paste_js = """
873
+ function() {
874
+ function blockPaste(id) {
875
+ const el = document.querySelector(id + " textarea");
876
+ if (el) {
877
+ el.addEventListener('paste', function(e) {
878
+ e.preventDefault();
879
+ alert("โš ๏ธ Copy-pasting is disabled. Please type manually!");
880
+ });
881
+ }
882
+ }
883
+ blockPaste("#std-summary-input");
884
+ blockPaste("#mod-answer-input");
885
+ blockPaste("#easy-answer-input");
886
+ }
887
+ """
888
+
889
+ # ==================== GRADIO UI ====================
890
+ with gr.Blocks(title="Summary & Passage Grader", theme=gr.themes.Soft()) as demo:
891
+ gr.Markdown("# ๐Ÿ“ Summary & Passage Grader")
892
+ gr.Markdown("Select a mode below. Read the rules carefully before you start!")
893
+
894
+ with gr.Tabs():
895
+
896
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
897
+ # STANDARD MODE
898
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
899
+ with gr.Tab("๐Ÿ“š Standard Mode"):
900
+ gr.Markdown(STANDARD_RULES)
901
+ with gr.Row():
902
+ std_name = gr.Textbox(label="Student Name", placeholder="Your full name")
903
+ std_class = gr.Textbox(label="Class", placeholder="e.g. 5A")
904
+ std_intro_btn = gr.Button("๐Ÿ‘‹ Show Personalised Welcome")
905
+ std_intro_out = gr.Markdown()
906
+ std_intro_btn.click(fn=intro_message_standard, inputs=[std_name, std_class], outputs=std_intro_out)
907
+
908
+ std_title = gr.Textbox(label="Book / Story Title")
909
+ std_summary = gr.Textbox(label="Your Summary (type manually โ€” no copy-paste!)",
910
+ lines=10, elem_id="std-summary-input")
911
+
912
+ std_grade_btn = gr.Button("โœ… Grade My Summary", variant="primary")
913
+ std_report = gr.Markdown()
914
+ std_corrected = gr.Textbox(label="๐Ÿ“ Corrected Summary (edit if you like, then click Redo)",
915
+ lines=8)
916
+ std_status = gr.Markdown()
917
+ std_redo_btn = gr.Button("๐Ÿ”„ Redo with Corrected Text", variant="secondary")
918
+
919
+ std_grade_btn.click(
920
+ fn=grade_standard,
921
+ inputs=[std_name, std_class, std_title, std_summary],
922
+ outputs=[std_report, std_corrected, std_status]
923
+ )
924
+ std_redo_btn.click(
925
+ fn=lambda c: c,
926
+ inputs=[std_corrected],
927
+ outputs=[std_summary]
928
+ )
929
+
930
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
931
+ # MODERATE MODE (passage disappears after timer)
932
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
933
+ with gr.Tab("๐ŸŽฎ Moderate Mode"):
934
+ gr.Markdown(MODERATE_RULES)
935
+ with gr.Row():
936
+ mod_name = gr.Textbox(label="Student Name", placeholder="Your full name")
937
+ mod_class = gr.Textbox(label="Class", placeholder="e.g. 5A")
938
+
939
+ mod_level_state = gr.State(value=2)
940
+ mod_timer_state = gr.State(value=0)
941
+ mod_visible_state = gr.State(value=True)
942
+
943
+ mod_load_btn = gr.Button("๐Ÿš€ Load My Level & Passages", variant="primary")
944
+ mod_level_display = gr.Markdown()
945
+ mod_timer_display = gr.Markdown()
946
+ mod_passages_display = gr.Markdown()
947
+
948
+ def mod_load(name, klass):
949
+ if not name.strip() or not klass.strip():
950
+ return "โš ๏ธ Enter name and class first.", "", "", 2, 0, True
951
+ level = get_student_level(name, klass, "moderate")
952
+ passages = passages_for_level(level)
953
+ ptext = format_passages_display(passages)
954
+ max_s = compute_max_stars_moderate(level)
955
+ mins = level + 1
956
+ level_md = (f"### ๐ŸŽฎ Your Level: **{level}** &nbsp;&nbsp; "
957
+ f"Passages: **{len(passages)}** &nbsp;&nbsp; "
958
+ f"Max stars: **{max_s:.1f} โญ**")
959
+ timer_md = f"โฑ๏ธ **You have {mins} minute(s) to read. The passage will disappear after that!**"
960
+ ts = time.time()
961
+ return level_md, timer_md, ptext, level, ts, True
962
+
963
+ mod_load_btn.click(
964
+ fn=mod_load,
965
+ inputs=[mod_name, mod_class],
966
+ outputs=[mod_level_display, mod_timer_display, mod_passages_display,
967
+ mod_level_state, mod_timer_state, mod_visible_state]
968
+ )
969
+
970
+ mod_check_btn = gr.Button("๐Ÿ” Check Timer / Hide Passage")
971
+
972
+ def mod_check_timer(level, ts, visible):
973
+ if ts == 0:
974
+ return gr.update(), "โš ๏ธ Load passages first.", visible
975
+ elapsed = time.time() - ts
976
+ secs_allowed = (level + 1) * 60
977
+ remaining = max(0.0, secs_allowed - elapsed)
978
+ if remaining > 0:
979
+ mins_left = int(remaining // 60)
980
+ secs_left = int(remaining % 60)
981
+ timer_md = f"โฑ๏ธ **Time remaining: {mins_left}m {secs_left}s**"
982
+ return gr.update(), timer_md, True
983
+ else:
984
+ timer_md = "โฐ **Time's up! Passage hidden. Now type from memory!**"
985
+ return gr.update(value="๐Ÿ™ˆ *Passage hidden โ€” time is up! Type what you remember.*"), timer_md, False
986
+
987
+ mod_check_btn.click(
988
+ fn=mod_check_timer,
989
+ inputs=[mod_level_state, mod_timer_state, mod_visible_state],
990
+ outputs=[mod_passages_display, mod_timer_display, mod_visible_state]
991
+ )
992
+
993
+ mod_answer = gr.Textbox(label="โœ๏ธ Type the English passage(s) here (no copy-paste!)",
994
+ lines=10, elem_id="mod-answer-input")
995
+ mod_submit_btn = gr.Button("โœ… Submit Answer", variant="primary")
996
+ mod_report = gr.Markdown()
997
+ mod_status = gr.Markdown()
998
+
999
+ def mod_grade(name, klass, answer, level):
1000
+ report, new_level, status = grade_passage_mode(name, klass, answer, level, "moderate")
1001
+ passages = passages_for_level(new_level)
1002
+ ptext = format_passages_display(passages)
1003
+ max_s = compute_max_stars_moderate(new_level)
1004
+ mins = new_level + 1
1005
+ level_md = (f"### ๐ŸŽฎ Your Level: **{new_level}** &nbsp;&nbsp; "
1006
+ f"Passages: **{len(passages)}** &nbsp;&nbsp; "
1007
+ f"Max stars: **{max_s:.1f} โญ**")
1008
+ timer_md = f"โฑ๏ธ **Next round: you'll have {mins} minute(s) to read.**"
1009
+ return report, status, level_md, timer_md, ptext, new_level, 0, True
1010
+
1011
+ mod_submit_btn.click(
1012
+ fn=mod_grade,
1013
+ inputs=[mod_name, mod_class, mod_answer, mod_level_state],
1014
+ outputs=[mod_report, mod_status, mod_level_display, mod_timer_display,
1015
+ mod_passages_display, mod_level_state, mod_timer_state, mod_visible_state]
1016
+ )
1017
+
1018
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
1019
+ # EASY MODE (passage stays visible always)
1020
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
1021
+ with gr.Tab("๐ŸŸข Easy Mode"):
1022
+ gr.Markdown(EASY_RULES)
1023
+ with gr.Row():
1024
+ easy_name = gr.Textbox(label="Student Name", placeholder="Your full name")
1025
+ easy_class = gr.Textbox(label="Class", placeholder="e.g. 5A")
1026
+
1027
+ easy_level_state = gr.State(value=2)
1028
+
1029
+ easy_load_btn = gr.Button("๐Ÿš€ Load My Level & Passages", variant="primary")
1030
+ easy_level_display = gr.Markdown()
1031
+ easy_passages_display = gr.Markdown()
1032
 
1033
+ def easy_load(name, klass):
1034
+ if not name.strip() or not klass.strip():
1035
+ return "โš ๏ธ Enter name and class first.", "", 2
1036
+ level = get_student_level(name, klass, "easy")
1037
+ passages = passages_for_level(level)
1038
+ ptext = format_passages_display(passages)
1039
+ level_md = (f"### ๐ŸŸข Your Level: **{level}** &nbsp;&nbsp; "
1040
+ f"Passages: **{len(passages)}** &nbsp;&nbsp; Max stars: **5 โญ**")
1041
+ return level_md, ptext, level
1042
 
1043
+ easy_load_btn.click(
1044
+ fn=easy_load,
1045
+ inputs=[easy_name, easy_class],
1046
+ outputs=[easy_level_display, easy_passages_display, easy_level_state]
1047
+ )
1048
 
1049
+ easy_answer = gr.Textbox(label="โœ๏ธ Type the English passage(s) here (no copy-paste!)",
1050
+ lines=10, elem_id="easy-answer-input")
1051
+ easy_submit_btn = gr.Button("โœ… Submit Answer", variant="primary")
1052
+ easy_report = gr.Markdown()
1053
+ easy_status = gr.Markdown()
 
 
1054
 
1055
+ def easy_grade(name, klass, answer, level):
1056
+ report, new_level, status = grade_passage_mode(name, klass, answer, level, "easy")
1057
+ passages = passages_for_level(new_level)
1058
+ ptext = format_passages_display(passages)
1059
+ level_md = (f"### ๐ŸŸข Your Level: **{new_level}** &nbsp;&nbsp; "
1060
+ f"Passages: **{len(passages)}** &nbsp;&nbsp; Max stars: **5 โญ**")
1061
+ return report, status, level_md, ptext, new_level
1062
 
1063
+ easy_submit_btn.click(
1064
+ fn=easy_grade,
1065
+ inputs=[easy_name, easy_class, easy_answer, easy_level_state],
1066
+ outputs=[easy_report, easy_status, easy_level_display,
1067
+ easy_passages_display, easy_level_state]
1068
+ )
1069
 
1070
+ demo.load(None, None, None, js=block_paste_js)
1071
 
1072
  if __name__ == "__main__":
1073
+ os.makedirs(PASSAGE_DIR, exist_ok=True)
1074
+ demo.launch()