Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,1083 +1,48 @@
|
|
| 1 |
-
|
| 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 |
-
|
| 236 |
-
|
| 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 |
-
|
| 381 |
-
Falls back gracefully if LLM indices are wrong — uses fuzzy search.
|
| 382 |
"""
|
| 383 |
-
|
| 384 |
-
|
| 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 |
-
|
| 580 |
-
|
| 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 |
-
|
| 588 |
-
|
| 589 |
-
## 📋 Standard Mode — Full Rules
|
| 590 |
|
| 591 |
-
|
|
|
|
| 592 |
|
| 593 |
-
|
| 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 |
-
|
| 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 |
-
|
| 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 |
-
# 🚫 Hard fail for short summaries
|
| 720 |
if wc < 100:
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
len_s = length_stars(wc)
|
| 729 |
-
grammar_star = round(grammar_stars_from_count(len(issues)), 1)
|
| 730 |
-
|
| 731 |
-
# Heuristic nonsense check (multi-signal)
|
| 732 |
-
heuristic_bad, heuristic_reason = is_nonsense_heuristic(student_summary)
|
| 733 |
-
|
| 734 |
-
reasons = []
|
| 735 |
-
if is_nonsense_ai:
|
| 736 |
-
reasons.append("AI flagged this as nonsense or gibberish.")
|
| 737 |
-
if heuristic_bad:
|
| 738 |
-
reasons.append(heuristic_reason)
|
| 739 |
-
|
| 740 |
-
is_failing = len(reasons) > 0
|
| 741 |
-
if is_failing:
|
| 742 |
-
final_score = -1.0
|
| 743 |
-
display_stars = 0
|
| 744 |
-
else:
|
| 745 |
-
vals = [float(expr), float(refl), float(len_s), float(grammar_star)]
|
| 746 |
-
if knows_story and comp is not None:
|
| 747 |
-
vals.append(float(comp))
|
| 748 |
-
raw_avg = round(sum(vals) / len(vals), 2) if vals else 0.0
|
| 749 |
-
final_score = round(raw_avg * 5, 2) # multiply by 5 → max 25
|
| 750 |
-
final_score = max(0.0, final_score)
|
| 751 |
-
display_stars = min(25, int(round(final_score))) # capped at 25
|
| 752 |
-
|
| 753 |
-
md = ["### 📚 Standard Mode — Grading Report"]
|
| 754 |
-
if is_failing:
|
| 755 |
-
md.append("> ## ❌ FINAL SCORE: −1 ⭐")
|
| 756 |
-
md.append("> **Reason:** " + " | ".join(reasons))
|
| 757 |
-
else:
|
| 758 |
-
md.append(f"\n**🏆 FINAL SCORE: {final_score:.1f} / 25**")
|
| 759 |
-
md.append("⭐" * display_stars)
|
| 760 |
-
|
| 761 |
-
md.append(f"\n**Name:** {student_name} **Class:** {student_class}")
|
| 762 |
-
md.append(f"**Title:** {title} **Words:** {wc}")
|
| 763 |
-
md.append("\n#### Category Scores (each out of 5)")
|
| 764 |
-
if knows_story:
|
| 765 |
-
md.append(f"- 📖 Comprehension: {stars_bar(comp)}")
|
| 766 |
-
else:
|
| 767 |
-
md.append(f"- 📖 Comprehension: — *(story not recognised by AI)*")
|
| 768 |
-
md.append(f"- ✍️ Expression: {stars_bar(expr)}")
|
| 769 |
-
md.append(f"- 💡 Reflection: {stars_bar(refl)}")
|
| 770 |
-
md.append(f"- 📏 Length ({wc} words): {stars_bar(len_s)}")
|
| 771 |
-
md.append(f"- ✅ Grammar ({len(issues)} issues): {stars_bar(grammar_star)}")
|
| 772 |
-
if remarks:
|
| 773 |
-
md.append(f"\n> 💬 **Remarks:** {remarks}")
|
| 774 |
-
|
| 775 |
-
if issues:
|
| 776 |
-
md.append(f"\n#### 🔎 Annotated Text\n```\n{annotate_original_with_issues(student_summary, issues)}\n```")
|
| 777 |
-
md.append("\n#### 📝 Grammar Issues")
|
| 778 |
-
for i, it in enumerate(issues, 1):
|
| 779 |
-
md.append(f"{i}. ❌ `{it['error_excerpt']}` → ✅ `{it['correction']}` — *{it['explanation']}*")
|
| 780 |
-
|
| 781 |
-
timestamp = now_ist().strftime("%Y-%m-%d %H:%M:%S")
|
| 782 |
-
mode_label = "standard-2-summary"
|
| 783 |
-
pct = round(final_score / 25 * 100, 1) if final_score >= 0 else 0
|
| 784 |
-
row = [timestamp, student_name, student_class, round(final_score, 2), "25", f"{pct}%", round(final_score, 2), mode_label]
|
| 785 |
-
sheets_status = append_to_sheet(row, student_name, student_class, final_score, mode_label)
|
| 786 |
-
doc_status = save_to_master_doc(student_name, student_class, title, student_summary)
|
| 787 |
-
|
| 788 |
-
return "\n".join(md), corrected, f"{sheets_status} | {doc_status}"
|
| 789 |
-
except Exception as e:
|
| 790 |
-
log.error(f"grade_standard error: {e}", exc_info=True)
|
| 791 |
-
return f"### ❌ Error\n{e}", "", "Not saved."
|
| 792 |
-
|
| 793 |
-
# ==================== PASSAGE MODE GRADING ====================
|
| 794 |
-
def grade_passage_mode(student_name: str, student_class: str, student_text: str, level: int, mode: str):
|
| 795 |
-
try:
|
| 796 |
-
if not all([student_name.strip(), student_class.strip(), student_text.strip()]):
|
| 797 |
-
return "⚠️ Please fill in all fields.", level, ""
|
| 798 |
-
|
| 799 |
-
passages = passages_for_level(level)
|
| 800 |
-
if not passages:
|
| 801 |
-
return "⚠️ No passages found. Please upload pssg1.txt etc. to the root of your HF repo (same folder as app.py).", level, ""
|
| 802 |
-
|
| 803 |
-
# Extract English-only portions for grading
|
| 804 |
-
english_only_passages = [extract_english_only(p) for p in passages]
|
| 805 |
-
combined_english = "\n\n".join(english_only_passages)
|
| 806 |
|
| 807 |
rate_key = student_key(student_name, student_class)
|
| 808 |
-
|
| 809 |
-
content, model_used = llm_chat([{"role": "user", "content": prompt}], rate_key=rate_key)
|
| 810 |
-
log.info(f"Passage grade: {student_name} level={level} mode={mode} model={model_used}")
|
| 811 |
-
|
| 812 |
-
data = salvage_passage_json(content) # robust parsing
|
| 813 |
-
raw_score = float(data.get("score", 1))
|
| 814 |
-
is_nonsense_ai = bool(data.get("is_nonsense", False))
|
| 815 |
-
remarks = str(data.get("remarks", "")).strip()
|
| 816 |
-
|
| 817 |
-
heuristic_bad, heuristic_reason = is_nonsense_heuristic(student_text)
|
| 818 |
-
is_failing = is_nonsense_ai or heuristic_bad
|
| 819 |
-
|
| 820 |
-
if mode == "moderate":
|
| 821 |
-
max_stars = compute_max_stars_moderate(level)
|
| 822 |
-
new_level = level_change_moderate(raw_score, level) if not is_failing else level
|
| 823 |
-
else: # easy
|
| 824 |
-
max_stars = compute_max_stars_easy(level)
|
| 825 |
-
new_level = level_change_easy(raw_score, level) if not is_failing else level
|
| 826 |
-
|
| 827 |
-
if is_failing:
|
| 828 |
-
final_score = -1.0
|
| 829 |
-
display_stars = 0
|
| 830 |
-
fail_reason = is_nonsense_ai and "AI flagged as gibberish." or heuristic_reason
|
| 831 |
-
else:
|
| 832 |
-
# Scale raw_score (1-5) to (0 - max_stars), floor at 0
|
| 833 |
-
final_score = max(0.0, round((raw_score / 5.0) * max_stars, 2))
|
| 834 |
-
display_stars = min(int(max_stars) + 1, int(round(final_score))) # capped at max_stars (not max+5)
|
| 835 |
-
|
| 836 |
-
mode_title = "🎮 Moderate" if mode == "moderate" else "🟢 Easy"
|
| 837 |
-
md = [f"### {mode_title} Mode — Results (Level {level})"]
|
| 838 |
-
if is_failing:
|
| 839 |
-
md.append("> ## ❌ FINAL SCORE: −1 ⭐")
|
| 840 |
-
md.append(f"> **Reason:** {fail_reason if is_nonsense_ai else heuristic_reason}")
|
| 841 |
-
else:
|
| 842 |
-
md.append(f"\n**🏆 Score: {final_score:.1f} / {max_stars:.1f}**")
|
| 843 |
-
md.append("⭐" * display_stars)
|
| 844 |
-
md.append(f"\n*(LLM accuracy: {raw_score:.0f}/5)*")
|
| 845 |
-
|
| 846 |
-
md.append(f"\n**Name:** {student_name} **Class:** {student_class}")
|
| 847 |
-
md.append(f"**Level:** {level} **Passages used:** {len(passages)}")
|
| 848 |
-
if remarks:
|
| 849 |
-
md.append(f"\n> 💬 {remarks}")
|
| 850 |
-
|
| 851 |
-
if new_level > level:
|
| 852 |
-
md.append(f"\n🎉 **Level UP! {level} → {new_level}**")
|
| 853 |
-
elif new_level < level:
|
| 854 |
-
md.append(f"\n📉 **Level DOWN: {level} → {new_level}**")
|
| 855 |
-
else:
|
| 856 |
-
md.append(f"\n➡️ **Level stays at {level}**")
|
| 857 |
-
|
| 858 |
-
timestamp = now_ist().strftime("%Y-%m-%d %H:%M:%S")
|
| 859 |
-
mode_label = f"{mode.lower()}-{new_level}-summary" # save NEW level
|
| 860 |
-
pct = round(final_score / max_stars * 100, 1) if max_stars > 0 and final_score >= 0 else 0
|
| 861 |
-
row = [timestamp, student_name, student_class, round(final_score, 2),
|
| 862 |
-
str(round(max_stars, 1)), f"{pct}%", round(final_score, 2), mode_label]
|
| 863 |
-
sheets_status = append_to_sheet(row, student_name, student_class, final_score, mode_label)
|
| 864 |
-
doc_status = save_to_master_doc(student_name, student_class, f"{mode}-level{level}", student_text)
|
| 865 |
-
|
| 866 |
-
return "\n".join(md), new_level, f"{sheets_status} | {doc_status}"
|
| 867 |
-
except Exception as e:
|
| 868 |
-
log.error(f"grade_passage_mode error: {e}", exc_info=True)
|
| 869 |
-
return f"### ❌ Error\n{e}", level, "Not saved."
|
| 870 |
-
|
| 871 |
-
# ==================== DISPLAY HELPERS ====================
|
| 872 |
-
def format_passages_display(passages: list[str]) -> str:
|
| 873 |
-
if not passages:
|
| 874 |
-
return "⚠️ No passages loaded. Please upload pssg1.txt, pssg2.txt etc. to the root of your HF repo (same folder as app.py)."
|
| 875 |
-
parts = []
|
| 876 |
-
for i, p in enumerate(passages, 1):
|
| 877 |
-
parts.append(f"### Passage {i}\n{p}")
|
| 878 |
-
return "\n\n---\n\n".join(parts)
|
| 879 |
-
|
| 880 |
-
# ==================== JAVASCRIPT ====================
|
| 881 |
-
block_paste_js = """
|
| 882 |
-
function() {
|
| 883 |
-
function blockPaste(id) {
|
| 884 |
-
const el = document.querySelector(id + " textarea");
|
| 885 |
-
if (el) {
|
| 886 |
-
el.addEventListener('paste', function(e) {
|
| 887 |
-
e.preventDefault();
|
| 888 |
-
alert("⚠️ Copy-pasting is disabled. Please type manually!");
|
| 889 |
-
});
|
| 890 |
-
}
|
| 891 |
-
}
|
| 892 |
-
blockPaste("#std-summary-input");
|
| 893 |
-
blockPaste("#mod-answer-input");
|
| 894 |
-
blockPaste("#easy-answer-input");
|
| 895 |
-
}
|
| 896 |
-
"""
|
| 897 |
-
|
| 898 |
-
# ==================== GRADIO UI ====================
|
| 899 |
-
with gr.Blocks(title="Summary & Passage Grader", theme=gr.themes.Soft()) as demo:
|
| 900 |
-
gr.Markdown("# 📝 Summary & Passage Grader")
|
| 901 |
-
gr.Markdown("Select a mode below. Read the rules carefully before you start!")
|
| 902 |
-
|
| 903 |
-
with gr.Tabs():
|
| 904 |
-
|
| 905 |
-
# ════════════════════════════════════════════
|
| 906 |
-
# STANDARD MODE
|
| 907 |
-
# ════════════════════════════════════════════
|
| 908 |
-
with gr.Tab("📚 Standard Mode"):
|
| 909 |
-
gr.Markdown(STANDARD_RULES)
|
| 910 |
-
with gr.Row():
|
| 911 |
-
std_name = gr.Textbox(label="Student Name", placeholder="Your full name")
|
| 912 |
-
std_class = gr.Textbox(label="Class", placeholder="e.g. 5A")
|
| 913 |
-
std_intro_btn = gr.Button("👋 Show Personalised Welcome")
|
| 914 |
-
std_intro_out = gr.Markdown()
|
| 915 |
-
std_intro_btn.click(fn=intro_message_standard, inputs=[std_name, std_class], outputs=std_intro_out)
|
| 916 |
-
|
| 917 |
-
std_title = gr.Textbox(label="Book / Story Title")
|
| 918 |
-
std_summary = gr.Textbox(label="Your Summary (type manually — no copy-paste!)",
|
| 919 |
-
lines=10, elem_id="std-summary-input")
|
| 920 |
-
|
| 921 |
-
std_grade_btn = gr.Button("✅ Grade My Summary", variant="primary")
|
| 922 |
-
std_report = gr.Markdown()
|
| 923 |
-
std_corrected = gr.Textbox(label="📝 Corrected Summary (edit if you like, then click Redo)",
|
| 924 |
-
lines=8)
|
| 925 |
-
std_status = gr.Markdown()
|
| 926 |
-
std_redo_btn = gr.Button("🔄 Redo with Corrected Text", variant="secondary")
|
| 927 |
-
|
| 928 |
-
std_grade_btn.click(
|
| 929 |
-
fn=grade_standard,
|
| 930 |
-
inputs=[std_name, std_class, std_title, std_summary],
|
| 931 |
-
outputs=[std_report, std_corrected, std_status]
|
| 932 |
-
)
|
| 933 |
-
std_redo_btn.click(
|
| 934 |
-
fn=lambda c: c,
|
| 935 |
-
inputs=[std_corrected],
|
| 936 |
-
outputs=[std_summary]
|
| 937 |
-
)
|
| 938 |
-
|
| 939 |
-
# ════════════════════════════════════════════
|
| 940 |
-
# MODERATE MODE (passage disappears after timer)
|
| 941 |
-
# ════════════════════════════════════════════
|
| 942 |
-
with gr.Tab("🎮 Moderate Mode"):
|
| 943 |
-
gr.Markdown(MODERATE_RULES)
|
| 944 |
-
with gr.Row():
|
| 945 |
-
mod_name = gr.Textbox(label="Student Name", placeholder="Your full name")
|
| 946 |
-
mod_class = gr.Textbox(label="Class", placeholder="e.g. 5A")
|
| 947 |
-
|
| 948 |
-
mod_level_state = gr.State(value=2)
|
| 949 |
-
mod_timer_state = gr.State(value=0)
|
| 950 |
-
mod_visible_state = gr.State(value=True)
|
| 951 |
-
|
| 952 |
-
mod_load_btn = gr.Button("🚀 Load My Level & Passages", variant="primary")
|
| 953 |
-
mod_level_display = gr.Markdown()
|
| 954 |
-
mod_timer_display = gr.Markdown()
|
| 955 |
-
mod_passages_display = gr.Markdown()
|
| 956 |
-
|
| 957 |
-
def mod_load(name, klass):
|
| 958 |
-
if not name.strip() or not klass.strip():
|
| 959 |
-
return "⚠️ Enter name and class first.", "", "", 2, 0, True
|
| 960 |
-
level = get_student_level(name, klass, "moderate")
|
| 961 |
-
passages = passages_for_level(level)
|
| 962 |
-
ptext = format_passages_display(passages)
|
| 963 |
-
max_s = compute_max_stars_moderate(level)
|
| 964 |
-
mins = level + 1
|
| 965 |
-
level_md = (f"### 🎮 Your Level: **{level}** "
|
| 966 |
-
f"Passages: **{len(passages)}** "
|
| 967 |
-
f"Max stars: **{max_s:.1f} ⭐**")
|
| 968 |
-
timer_md = f"⏱️ **You have {mins} minute(s) to read. The passage will disappear after that!**"
|
| 969 |
-
ts = time.time()
|
| 970 |
-
return level_md, timer_md, ptext, level, ts, True
|
| 971 |
-
|
| 972 |
-
mod_load_btn.click(
|
| 973 |
-
fn=mod_load,
|
| 974 |
-
inputs=[mod_name, mod_class],
|
| 975 |
-
outputs=[mod_level_display, mod_timer_display, mod_passages_display,
|
| 976 |
-
mod_level_state, mod_timer_state, mod_visible_state]
|
| 977 |
-
)
|
| 978 |
-
|
| 979 |
-
mod_check_btn = gr.Button("🔍 Check Timer / Hide Passage")
|
| 980 |
-
|
| 981 |
-
def mod_check_timer(level, ts, visible):
|
| 982 |
-
if ts == 0:
|
| 983 |
-
return gr.update(), "⚠️ Load passages first.", visible
|
| 984 |
-
elapsed = time.time() - ts
|
| 985 |
-
secs_allowed = (level + 1) * 60
|
| 986 |
-
remaining = max(0.0, secs_allowed - elapsed)
|
| 987 |
-
if remaining > 0:
|
| 988 |
-
mins_left = int(remaining // 60)
|
| 989 |
-
secs_left = int(remaining % 60)
|
| 990 |
-
timer_md = f"⏱️ **Time remaining: {mins_left}m {secs_left}s**"
|
| 991 |
-
return gr.update(), timer_md, True
|
| 992 |
-
else:
|
| 993 |
-
timer_md = "⏰ **Time's up! Passage hidden. Now type from memory!**"
|
| 994 |
-
return gr.update(value="🙈 *Passage hidden — time is up! Type what you remember.*"), timer_md, False
|
| 995 |
-
|
| 996 |
-
mod_check_btn.click(
|
| 997 |
-
fn=mod_check_timer,
|
| 998 |
-
inputs=[mod_level_state, mod_timer_state, mod_visible_state],
|
| 999 |
-
outputs=[mod_passages_display, mod_timer_display, mod_visible_state]
|
| 1000 |
-
)
|
| 1001 |
-
|
| 1002 |
-
mod_answer = gr.Textbox(label="✍️ Type the English passage(s) here (no copy-paste!)",
|
| 1003 |
-
lines=10, elem_id="mod-answer-input")
|
| 1004 |
-
mod_submit_btn = gr.Button("✅ Submit Answer", variant="primary")
|
| 1005 |
-
mod_report = gr.Markdown()
|
| 1006 |
-
mod_status = gr.Markdown()
|
| 1007 |
-
|
| 1008 |
-
def mod_grade(name, klass, answer, level):
|
| 1009 |
-
report, new_level, status = grade_passage_mode(name, klass, answer, level, "moderate")
|
| 1010 |
-
passages = passages_for_level(new_level)
|
| 1011 |
-
ptext = format_passages_display(passages)
|
| 1012 |
-
max_s = compute_max_stars_moderate(new_level)
|
| 1013 |
-
mins = new_level + 1
|
| 1014 |
-
level_md = (f"### 🎮 Your Level: **{new_level}** "
|
| 1015 |
-
f"Passages: **{len(passages)}** "
|
| 1016 |
-
f"Max stars: **{max_s:.1f} ⭐**")
|
| 1017 |
-
timer_md = f"⏱️ **Next round: you'll have {mins} minute(s) to read.**"
|
| 1018 |
-
return report, status, level_md, timer_md, ptext, new_level, 0, True
|
| 1019 |
-
|
| 1020 |
-
mod_submit_btn.click(
|
| 1021 |
-
fn=mod_grade,
|
| 1022 |
-
inputs=[mod_name, mod_class, mod_answer, mod_level_state],
|
| 1023 |
-
outputs=[mod_report, mod_status, mod_level_display, mod_timer_display,
|
| 1024 |
-
mod_passages_display, mod_level_state, mod_timer_state, mod_visible_state]
|
| 1025 |
-
)
|
| 1026 |
-
|
| 1027 |
-
# ════════════════════════════════════════════
|
| 1028 |
-
# EASY MODE (passage stays visible always)
|
| 1029 |
-
# ════════════════════════════════════════════
|
| 1030 |
-
with gr.Tab("🟢 Easy Mode"):
|
| 1031 |
-
gr.Markdown(EASY_RULES)
|
| 1032 |
-
with gr.Row():
|
| 1033 |
-
easy_name = gr.Textbox(label="Student Name", placeholder="Your full name")
|
| 1034 |
-
easy_class = gr.Textbox(label="Class", placeholder="e.g. 5A")
|
| 1035 |
-
|
| 1036 |
-
easy_level_state = gr.State(value=2)
|
| 1037 |
-
|
| 1038 |
-
easy_load_btn = gr.Button("🚀 Load My Level & Passages", variant="primary")
|
| 1039 |
-
easy_level_display = gr.Markdown()
|
| 1040 |
-
easy_passages_display = gr.Markdown()
|
| 1041 |
-
|
| 1042 |
-
def easy_load(name, klass):
|
| 1043 |
-
if not name.strip() or not klass.strip():
|
| 1044 |
-
return "⚠️ Enter name and class first.", "", 2
|
| 1045 |
-
level = get_student_level(name, klass, "easy")
|
| 1046 |
-
passages = passages_for_level(level)
|
| 1047 |
-
ptext = format_passages_display(passages)
|
| 1048 |
-
level_md = (f"### 🟢 Your Level: **{level}** "
|
| 1049 |
-
f"Passages: **{len(passages)}** Max stars: **5 ⭐**")
|
| 1050 |
-
return level_md, ptext, level
|
| 1051 |
-
|
| 1052 |
-
easy_load_btn.click(
|
| 1053 |
-
fn=easy_load,
|
| 1054 |
-
inputs=[easy_name, easy_class],
|
| 1055 |
-
outputs=[easy_level_display, easy_passages_display, easy_level_state]
|
| 1056 |
-
)
|
| 1057 |
-
|
| 1058 |
-
easy_answer = gr.Textbox(label="✍️ Type the English passage(s) here (no copy-paste!)",
|
| 1059 |
-
lines=10, elem_id="easy-answer-input")
|
| 1060 |
-
easy_submit_btn = gr.Button("✅ Submit Answer", variant="primary")
|
| 1061 |
-
easy_report = gr.Markdown()
|
| 1062 |
-
easy_status = gr.Markdown()
|
| 1063 |
-
|
| 1064 |
-
def easy_grade(name, klass, answer, level):
|
| 1065 |
-
report, new_level, status = grade_passage_mode(name, klass, answer, level, "easy")
|
| 1066 |
-
passages = passages_for_level(new_level)
|
| 1067 |
-
ptext = format_passages_display(passages)
|
| 1068 |
-
level_md = (f"### 🟢 Your Level: **{new_level}** "
|
| 1069 |
-
f"Passages: **{len(passages)}** Max stars: **5 ⭐**")
|
| 1070 |
-
return report, status, level_md, ptext, new_level
|
| 1071 |
-
|
| 1072 |
-
easy_submit_btn.click(
|
| 1073 |
-
fn=easy_grade,
|
| 1074 |
-
inputs=[easy_name, easy_class, easy_answer, easy_level_state],
|
| 1075 |
-
outputs=[easy_report, easy_status, easy_level_display,
|
| 1076 |
-
easy_passages_display, easy_level_state]
|
| 1077 |
-
)
|
| 1078 |
-
|
| 1079 |
-
demo.load(None, None, None, js=block_paste_js)
|
| 1080 |
-
|
| 1081 |
-
if __name__ == "__main__":
|
| 1082 |
-
os.makedirs(PASSAGE_DIR, exist_ok=True)
|
| 1083 |
-
demo.launch()
|
|
|
|
| 1 |
+
# (ONLY showing modified + surrounding relevant sections; rest of your file remains EXACTLY same)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
# ==================== HELPERS ====================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
def is_nonsense_heuristic(text: str) -> tuple[bool, str]:
|
| 6 |
+
...
|
| 7 |
return False, ""
|
| 8 |
|
| 9 |
+
# ✅ NEW INSERTION
|
| 10 |
+
def is_irrelevant_answer(student_text: str, reference_text: str) -> tuple[bool, str]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
"""
|
| 12 |
+
Checks if student answer is unrelated to passage using word overlap.
|
|
|
|
| 13 |
"""
|
| 14 |
+
student_words = set(re.findall(r"\b\w+\b", student_text.lower()))
|
| 15 |
+
ref_words = set(re.findall(r"\b\w+\b", reference_text.lower()))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
if len(student_words) < 5:
|
| 18 |
+
return True, "Answer too short or empty."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
+
overlap = student_words & ref_words
|
| 21 |
+
overlap_ratio = len(overlap) / max(1, len(student_words))
|
|
|
|
| 22 |
|
| 23 |
+
if overlap_ratio < 0.2:
|
| 24 |
+
return True, "Answer does not match the passage content."
|
| 25 |
|
| 26 |
+
return False, ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
# ==================== STANDARD MODE GRADING ====================
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
def grade_standard(student_name: str, student_class: str, title: str, student_summary: str):
|
| 32 |
try:
|
| 33 |
if not all([student_name.strip(), student_class.strip(), title.strip(), student_summary.strip()]):
|
| 34 |
return "⚠️ Please fill in all fields.", "", ""
|
| 35 |
|
| 36 |
+
wc = count_words(student_summary)
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
+
# ✅ NEW INSERTION (HARD FAIL)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
if wc < 100:
|
| 40 |
+
md = [
|
| 41 |
+
"### 📚 Standard Mode — Grading Report",
|
| 42 |
+
"> ## ❌ FINAL SCORE: −1 ⭐",
|
| 43 |
+
f"> **Reason:** Too short ({wc} words). Minimum 100 words required."
|
| 44 |
+
]
|
| 45 |
+
return "\n".join(md), "", "Not saved."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
rate_key = student_key(student_name, student_class)
|
| 48 |
+
...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|