Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,35 +2,54 @@ import os, json, textwrap, re, time
|
|
| 2 |
import gradio as gr
|
| 3 |
from openai import OpenAI
|
| 4 |
|
| 5 |
-
# ==================== LLM
|
| 6 |
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
|
| 7 |
DEEPSEEK_BASE_URL = os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com/v1")
|
| 8 |
-
DEEPSEEK_MODEL = os.getenv("DEEPSEEK_MODEL", "DeepSeek-V3.2-Exp")
|
| 9 |
|
| 10 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 11 |
OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-5")
|
| 12 |
|
| 13 |
-
# ====================
|
| 14 |
-
SVC_JSON = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON") #
|
| 15 |
-
SHEET_ID = os.getenv("SHEETS_SPREADSHEET_ID")
|
| 16 |
-
WS_ID = os.getenv("SHEETS_WORKSHEET_ID")
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
|
|
|
|
| 34 |
{
|
| 35 |
"knows_story": true/false,
|
| 36 |
"scores": {
|
|
@@ -39,23 +58,35 @@ Return valid JSON:
|
|
| 39 |
"Reflection/Moral Takeaway": 1-5
|
| 40 |
},
|
| 41 |
"grammar_issues": [
|
| 42 |
-
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
],
|
| 44 |
-
"corrected_summary": "<
|
| 45 |
-
"remarks": "<
|
| 46 |
}
|
|
|
|
|
|
|
| 47 |
"""
|
| 48 |
|
| 49 |
-
# ==================== LLM
|
| 50 |
-
def llm_chat(messages):
|
| 51 |
-
"""
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
ds = OpenAI(api_key=DEEPSEEK_API_KEY, base_url=DEEPSEEK_BASE_URL)
|
| 55 |
resp = ds.chat.completions.create(model=DEEPSEEK_MODEL, messages=messages)
|
| 56 |
return resp.choices[0].message.content, f"DeepSeek ({DEEPSEEK_MODEL})"
|
| 57 |
-
|
| 58 |
-
|
| 59 |
|
| 60 |
if OPENAI_API_KEY:
|
| 61 |
try:
|
|
@@ -63,160 +94,289 @@ def llm_chat(messages):
|
|
| 63 |
resp = oa.chat.completions.create(model=OPENAI_MODEL, messages=messages)
|
| 64 |
return resp.choices[0].message.content, f"OpenAI ({OPENAI_MODEL})"
|
| 65 |
except Exception as e:
|
| 66 |
-
|
| 67 |
|
| 68 |
-
|
|
|
|
|
|
|
| 69 |
|
|
|
|
| 70 |
def salvage_json(s: str) -> dict:
|
| 71 |
s = s.strip()
|
| 72 |
try:
|
| 73 |
return json.loads(s)
|
| 74 |
-
except:
|
| 75 |
m = re.search(r"\{.*\}\s*$", s, flags=re.S)
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
return 5
|
| 90 |
|
| 91 |
-
def
|
| 92 |
-
return 0 if n >= 50 else round(5 - 0.1 * n, 1)
|
| 93 |
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
if not (SVC_JSON and SHEET_ID and WS_ID):
|
| 98 |
-
return "
|
| 99 |
|
| 100 |
try:
|
| 101 |
import gspread
|
| 102 |
from google.oauth2.service_account import Credentials
|
| 103 |
-
|
| 104 |
-
|
|
|
|
| 105 |
gc = gspread.authorize(creds)
|
| 106 |
-
|
|
|
|
| 107 |
ws.append_row(row, value_input_option="USER_ENTERED")
|
| 108 |
-
return "
|
| 109 |
except Exception as e:
|
| 110 |
-
return f"
|
| 111 |
|
| 112 |
-
# ====================
|
| 113 |
def intro_message(name, klass):
|
| 114 |
if not name.strip() or not klass.strip():
|
| 115 |
return "π Please tell me your name and class first!"
|
| 116 |
return f"""
|
| 117 |
### π Hi {name} of {klass}!
|
| 118 |
-
Welcome to the **Summary Grader
|
| 119 |
-
|
| 120 |
-
Hereβs how Iβll mark your story:
|
| 121 |
-
|
| 122 |
-
1
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
"""
|
| 136 |
|
| 137 |
-
# ====================
|
| 138 |
-
def grade_summary(
|
| 139 |
-
if not
|
| 140 |
-
return "β οΈ Please
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
prompt = f"""
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
-
|
| 146 |
-
{summary}
|
| 147 |
|
| 148 |
-
{
|
| 149 |
"""
|
| 150 |
-
|
|
|
|
| 151 |
data = salvage_json(content)
|
| 152 |
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
|
|
|
|
|
|
|
|
|
| 164 |
grammar_count = len(issues)
|
| 165 |
-
grammar_star =
|
| 166 |
|
| 167 |
-
|
| 168 |
-
if knows_story and comp
|
| 169 |
-
|
|
|
|
| 170 |
|
|
|
|
| 171 |
md = []
|
| 172 |
-
md.append(f"### π Summary
|
|
|
|
| 173 |
md.append(f"**Title:** {title}")
|
|
|
|
| 174 |
md.append(f"**Model used:** `{model_used}`")
|
| 175 |
md.append("")
|
| 176 |
-
md.append("####
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
md.append(f"-
|
|
|
|
|
|
|
|
|
|
| 182 |
md.append("")
|
| 183 |
-
md.append(f"**
|
| 184 |
md.append("")
|
| 185 |
-
md.append(
|
|
|
|
| 186 |
md.append("")
|
| 187 |
-
md.append(
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
|
| 198 |
# ==================== UI ====================
|
| 199 |
-
with gr.Blocks(title="Summary Grader (DeepSeek β OpenAI)") as demo:
|
| 200 |
-
gr.Markdown("##
|
| 201 |
|
| 202 |
with gr.Row():
|
| 203 |
-
|
| 204 |
-
|
| 205 |
|
| 206 |
-
|
| 207 |
-
gr.
|
|
|
|
|
|
|
| 208 |
|
| 209 |
with gr.Row():
|
| 210 |
-
|
| 211 |
-
|
|
|
|
|
|
|
|
|
|
| 212 |
|
| 213 |
-
report_out = gr.Markdown()
|
| 214 |
-
corrected_out = gr.Textbox(label="Corrected
|
| 215 |
-
status_out = gr.Markdown()
|
| 216 |
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
|
|
|
|
| 221 |
if __name__ == "__main__":
|
| 222 |
demo.launch()
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
from openai import OpenAI
|
| 4 |
|
| 5 |
+
# ==================== LLM config ====================
|
| 6 |
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
|
| 7 |
DEEPSEEK_BASE_URL = os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com/v1")
|
| 8 |
+
DEEPSEEK_MODEL = os.getenv("DEEPSEEK_MODEL", "DeepSeek-V3.2-Exp") # non-thinking
|
| 9 |
|
| 10 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 11 |
OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-5")
|
| 12 |
|
| 13 |
+
# ==================== Google Sheets config ====================
|
| 14 |
+
SVC_JSON = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON") # whole JSON as a single string
|
| 15 |
+
SHEET_ID = os.getenv("SHEETS_SPREADSHEET_ID") # from your sheet URL
|
| 16 |
+
WS_ID = os.getenv("SHEETS_WORKSHEET_ID") # gid from your sheet URL (e.g., 1659517197)
|
| 17 |
+
|
| 18 |
+
# ==================== Limits ====================
|
| 19 |
+
MAX_CHARS = 12000 # keep latency sane for Spaces
|
| 20 |
+
|
| 21 |
+
# ==================== Rubric prompts ====================
|
| 22 |
+
RUBRIC_USER_TEXT = """
|
| 23 |
+
You are a teacher grading a student's summary. Follow these rules strictly.
|
| 24 |
+
|
| 25 |
+
Step 1: Decide if you KNOW the story.
|
| 26 |
+
- If you KNOW the work (book/movie), set "knows_story": true.
|
| 27 |
+
- If you DO NOT know the work, set "knows_story": false.
|
| 28 |
+
|
| 29 |
+
Step 2: Scoring rules.
|
| 30 |
+
- If knows_story=true, grade all of these:
|
| 31 |
+
1) Comprehension β 1 to 5 stars (how accurately the student captured the story or message).
|
| 32 |
+
2) Expression β 1 to 5 stars (clarity, coherence, fluency; how understandable if narrated).
|
| 33 |
+
3) Reflection/Moral Takeaway β 1 to 5 stars (thoughtfulness, personal connection).
|
| 34 |
+
4) Grammar (lenient): Identify grammar/spelling/punctuation mistakes in the student's text. Ignore minor conversational-English slips.
|
| 35 |
+
Return a list of issues where each item contains:
|
| 36 |
+
- "error_excerpt": student's exact snippet with the mistake (max ~120 chars)
|
| 37 |
+
- "correction": corrected version of that snippet
|
| 38 |
+
- "explanation": short reason (e.g., "subjectβverb agreement", "punctuation spacing")
|
| 39 |
+
- "start_index": 0-based char index in the ORIGINAL text where the error begins
|
| 40 |
+
- "end_index": exclusive end index
|
| 41 |
+
- If knows_story=false, omit Comprehension (set it to null) but grade the rest with the same grammar rules.
|
| 42 |
+
|
| 43 |
+
Constraints:
|
| 44 |
+
- Keep "error_excerpt" and "correction" minimal and tightly focused (no rewriting entire paragraphs).
|
| 45 |
+
- Indices MUST refer to the student's ORIGINAL text provided.
|
| 46 |
+
- After listing issues, also return a "corrected_summary" that lightly fixes the student's full passage (minimal edits, same meaning, natural).
|
| 47 |
+
|
| 48 |
+
IMPORTANT: Do NOT compute "Length" stars. The app computes them locally by word count bins.
|
| 49 |
+
"""
|
| 50 |
|
| 51 |
+
JSON_SCHEMA_HINT = """
|
| 52 |
+
Return ONLY valid JSON with this EXACT structure:
|
| 53 |
{
|
| 54 |
"knows_story": true/false,
|
| 55 |
"scores": {
|
|
|
|
| 58 |
"Reflection/Moral Takeaway": 1-5
|
| 59 |
},
|
| 60 |
"grammar_issues": [
|
| 61 |
+
{
|
| 62 |
+
"error_excerpt": "<string>",
|
| 63 |
+
"correction": "<string>",
|
| 64 |
+
"explanation": "<string>",
|
| 65 |
+
"start_index": 0,
|
| 66 |
+
"end_index": 0
|
| 67 |
+
}
|
| 68 |
],
|
| 69 |
+
"corrected_summary": "<the student's passage corrected for grammar (minimal edits)>",
|
| 70 |
+
"remarks": "<1β2 sentence feedback (plain text)>"
|
| 71 |
}
|
| 72 |
+
- If there are no grammar issues, return "grammar_issues": [].
|
| 73 |
+
- No markdown. No extra keys. Numbers only for scores.
|
| 74 |
"""
|
| 75 |
|
| 76 |
+
# ==================== LLM Bridge (DeepSeek β OpenAI) ====================
|
| 77 |
+
def llm_chat(messages, prefer_deepseek=True):
|
| 78 |
+
"""
|
| 79 |
+
Try DeepSeek first; on error, fallback to OpenAI.
|
| 80 |
+
Returns (content, model_used_str).
|
| 81 |
+
"""
|
| 82 |
+
last_err = None
|
| 83 |
+
if prefer_deepseek and DEEPSEEK_API_KEY:
|
| 84 |
+
try:
|
| 85 |
ds = OpenAI(api_key=DEEPSEEK_API_KEY, base_url=DEEPSEEK_BASE_URL)
|
| 86 |
resp = ds.chat.completions.create(model=DEEPSEEK_MODEL, messages=messages)
|
| 87 |
return resp.choices[0].message.content, f"DeepSeek ({DEEPSEEK_MODEL})"
|
| 88 |
+
except Exception as e:
|
| 89 |
+
last_err = e # fall through
|
| 90 |
|
| 91 |
if OPENAI_API_KEY:
|
| 92 |
try:
|
|
|
|
| 94 |
resp = oa.chat.completions.create(model=OPENAI_MODEL, messages=messages)
|
| 95 |
return resp.choices[0].message.content, f"OpenAI ({OPENAI_MODEL})"
|
| 96 |
except Exception as e:
|
| 97 |
+
last_err = e
|
| 98 |
|
| 99 |
+
if not DEEPSEEK_API_KEY and not OPENAI_API_KEY:
|
| 100 |
+
raise RuntimeError("No API key found. Set DEEPSEEK_API_KEY and/or OPENAI_API_KEY as Secrets.")
|
| 101 |
+
raise RuntimeError(f"Both DeepSeek and OpenAI calls failed. Last error: {last_err}")
|
| 102 |
|
| 103 |
+
# ==================== Helpers ====================
|
| 104 |
def salvage_json(s: str) -> dict:
|
| 105 |
s = s.strip()
|
| 106 |
try:
|
| 107 |
return json.loads(s)
|
| 108 |
+
except json.JSONDecodeError:
|
| 109 |
m = re.search(r"\{.*\}\s*$", s, flags=re.S)
|
| 110 |
+
if not m:
|
| 111 |
+
raise ValueError("Model did not return valid JSON.")
|
| 112 |
+
return json.loads(m.group(0))
|
| 113 |
+
|
| 114 |
+
def stars_bar(value: float | int | None, max_stars: int = 5) -> str:
|
| 115 |
+
if value is None or float(value) <= 0:
|
| 116 |
+
return "β"
|
| 117 |
+
n_int = max(0, min(max_stars, int(round(float(value)))))
|
| 118 |
+
return "β" * n_int
|
| 119 |
+
|
| 120 |
+
def count_words(text: str) -> int:
|
| 121 |
+
return len(re.findall(r"\b\w[\w'-]*\b", text))
|
| 122 |
+
|
| 123 |
+
def length_stars(word_count: int) -> int:
|
| 124 |
+
if word_count < 100: return 0
|
| 125 |
+
if word_count <= 150: return 1
|
| 126 |
+
if word_count <= 200: return 3
|
| 127 |
+
if word_count <= 250: return 4
|
| 128 |
return 5
|
| 129 |
|
| 130 |
+
def clamp_1_to_5(x): return max(1, min(5, int(x)))
|
|
|
|
| 131 |
|
| 132 |
+
def grammar_stars_from_count(n: int) -> float:
|
| 133 |
+
if n >= 50: return 0.0
|
| 134 |
+
return max(0.0, 5.0 - 0.1 * n)
|
| 135 |
+
|
| 136 |
+
def annotate_original_with_issues(text: str, issues: list[dict]) -> str:
|
| 137 |
+
clean = []
|
| 138 |
+
for i, it in enumerate(issues, 1):
|
| 139 |
+
try:
|
| 140 |
+
si, ei = int(it["start_index"]), int(it["end_index"])
|
| 141 |
+
if 0 <= si < ei <= len(text): clean.append((si, ei, i))
|
| 142 |
+
except Exception:
|
| 143 |
+
continue
|
| 144 |
+
clean.sort(key=lambda x: x[0])
|
| 145 |
+
out, cursor, last_end = [], 0, -1
|
| 146 |
+
for si, ei, idx in clean:
|
| 147 |
+
if si < last_end: # skip overlaps
|
| 148 |
+
continue
|
| 149 |
+
out.append(text[cursor:si])
|
| 150 |
+
out.append(f"[[#{idx}: {text[si:ei]}]]")
|
| 151 |
+
cursor, last_end = ei, ei
|
| 152 |
+
out.append(text[cursor:])
|
| 153 |
+
return "".join(out)
|
| 154 |
+
|
| 155 |
+
def apply_corrections_by_offsets(text: str, issues: list[dict]) -> str:
|
| 156 |
+
spans = []
|
| 157 |
+
for it in issues:
|
| 158 |
+
try:
|
| 159 |
+
si, ei = int(it["start_index"]), int(it["end_index"])
|
| 160 |
+
cor = str(it.get("correction", ""))
|
| 161 |
+
if 0 <= si < ei <= len(text): spans.append((si, ei, cor))
|
| 162 |
+
except Exception:
|
| 163 |
+
continue
|
| 164 |
+
spans.sort(key=lambda x: x[0])
|
| 165 |
+
out, cursor, last_end = [], 0, -1
|
| 166 |
+
for si, ei, cor in spans:
|
| 167 |
+
if si < last_end: continue
|
| 168 |
+
out.append(text[cursor:si]); out.append(cor)
|
| 169 |
+
cursor, last_end = ei, ei
|
| 170 |
+
out.append(text[cursor:])
|
| 171 |
+
return "".join(out)
|
| 172 |
+
|
| 173 |
+
# ==================== Google Sheets writer ====================
|
| 174 |
+
def append_to_sheet(row: list) -> str:
|
| 175 |
+
"""
|
| 176 |
+
Appends a row to the configured worksheet.
|
| 177 |
+
Row order:
|
| 178 |
+
[timestamp, name, class, title, word_count, knows_story,
|
| 179 |
+
comprehension, expression, reflection, length_stars,
|
| 180 |
+
grammar_mistakes, grammar_stars, average_stars, model_used, remarks]
|
| 181 |
+
"""
|
| 182 |
if not (SVC_JSON and SHEET_ID and WS_ID):
|
| 183 |
+
return "Sheets not configured (missing GOOGLE_SERVICE_ACCOUNT_JSON / SHEETS_SPREADSHEET_ID / SHEETS_WORKSHEET_ID)."
|
| 184 |
|
| 185 |
try:
|
| 186 |
import gspread
|
| 187 |
from google.oauth2.service_account import Credentials
|
| 188 |
+
creds_info = json.loads(SVC_JSON)
|
| 189 |
+
scopes = ["https://www.googleapis.com/auth/spreadsheets"]
|
| 190 |
+
creds = Credentials.from_service_account_info(creds_info, scopes=scopes)
|
| 191 |
gc = gspread.authorize(creds)
|
| 192 |
+
sh = gc.open_by_key(SHEET_ID)
|
| 193 |
+
ws = sh.get_worksheet_by_id(int(WS_ID)) # use gid
|
| 194 |
ws.append_row(row, value_input_option="USER_ENTERED")
|
| 195 |
+
return "OK"
|
| 196 |
except Exception as e:
|
| 197 |
+
return f"Sheets error: {e}"
|
| 198 |
|
| 199 |
+
# ==================== Friendly intro for kids ====================
|
| 200 |
def intro_message(name, klass):
|
| 201 |
if not name.strip() or not klass.strip():
|
| 202 |
return "π Please tell me your name and class first!"
|
| 203 |
return f"""
|
| 204 |
### π Hi {name} of {klass}!
|
| 205 |
+
Welcome to the **Summary Grader** π
|
| 206 |
+
|
| 207 |
+
Hereβs how Iβll read and mark your story:
|
| 208 |
+
|
| 209 |
+
1. **Comprehension** β Did you really understand the story or movie?
|
| 210 |
+
βοΈ *Tip:* Retell it in your own words, in the right order.
|
| 211 |
+
|
| 212 |
+
2. **Expression** β How clearly and smoothly you write.
|
| 213 |
+
βοΈ *Tip:* Use short sentences, correct punctuation, and connect ideas.
|
| 214 |
+
|
| 215 |
+
3. **Reflection / Moral** β What lesson or idea did you take away?
|
| 216 |
+
βοΈ *Tip:* Write one or two sentences about what it means to you.
|
| 217 |
+
|
| 218 |
+
4. **Grammar & Neatness** β Spelling, punctuation, and correctness.
|
| 219 |
+
βοΈ *Tip:* Read aloud once to catch small mistakes.
|
| 220 |
+
|
| 221 |
+
5. **Length** β Iβll count your words:
|
| 222 |
+
- Less than **100 words β 0β**
|
| 223 |
+
- **100β150 β 1β**
|
| 224 |
+
- **150β200 β 3β**
|
| 225 |
+
- **200β250 β 4β**
|
| 226 |
+
- **250+ β 5β**
|
| 227 |
+
|
| 228 |
+
π Try your best: write neatly, think deeply, and explain clearly.
|
| 229 |
+
When youβre ready, paste your story below and press **Grade & Save!**
|
| 230 |
"""
|
| 231 |
|
| 232 |
+
# ==================== Core grading ====================
|
| 233 |
+
def grade_summary(student_name: str, student_class: str, title: str, student_summary: str):
|
| 234 |
+
if not student_name.strip():
|
| 235 |
+
return "β οΈ Please enter the student's name.", "", ""
|
| 236 |
+
if not student_class.strip():
|
| 237 |
+
return "β οΈ Please enter the class/grade.", "", ""
|
| 238 |
+
if not title.strip():
|
| 239 |
+
return "β οΈ Please enter a title.", "", ""
|
| 240 |
+
if not student_summary.strip():
|
| 241 |
+
return "β οΈ Please paste the student's summary.", "", ""
|
| 242 |
+
if len(student_summary) > MAX_CHARS:
|
| 243 |
+
return f"β οΈ Summary too long ({len(student_summary)} chars). Limit is {MAX_CHARS}.", "", ""
|
| 244 |
|
| 245 |
prompt = f"""
|
| 246 |
+
TITLE: {title}
|
| 247 |
+
|
| 248 |
+
STUDENT SUMMARY (ORIGINAL TEXT BELOW):
|
| 249 |
+
{student_summary}
|
| 250 |
|
| 251 |
+
{RUBRIC_USER_TEXT}
|
|
|
|
| 252 |
|
| 253 |
+
{JSON_SCHEMA_HINT}
|
| 254 |
"""
|
| 255 |
+
# LLM call
|
| 256 |
+
content, model_used = llm_chat([{"role": "user", "content": prompt}], prefer_deepseek=True)
|
| 257 |
data = salvage_json(content)
|
| 258 |
|
| 259 |
+
# Extract
|
| 260 |
+
knows_story = bool(data.get("knows_story", False))
|
| 261 |
+
scores = data.get("scores", {}) or {}
|
| 262 |
+
comp = scores.get("Comprehension", None)
|
| 263 |
+
expr = clamp_1_to_5(scores.get("Expression", 1))
|
| 264 |
+
refl = clamp_1_to_5(scores.get("Reflection/Moral Takeaway", 1))
|
| 265 |
+
issues = data.get("grammar_issues", []) or []
|
| 266 |
+
corrected = (data.get("corrected_summary") or "").strip()
|
| 267 |
+
remarks = (data.get("remarks") or "").strip()
|
| 268 |
+
if not knows_story:
|
| 269 |
+
comp = None
|
| 270 |
+
|
| 271 |
+
wc = count_words(student_summary)
|
| 272 |
+
len_s = length_stars(wc)
|
| 273 |
grammar_count = len(issues)
|
| 274 |
+
grammar_star = round(grammar_stars_from_count(grammar_count), 1)
|
| 275 |
|
| 276 |
+
vals = [float(expr), float(refl), float(len_s), float(grammar_star)]
|
| 277 |
+
if knows_story and comp is not None:
|
| 278 |
+
vals.append(float(comp))
|
| 279 |
+
avg = round(sum(vals) / len(vals), 2) if vals else 0.0
|
| 280 |
|
| 281 |
+
# Build report
|
| 282 |
md = []
|
| 283 |
+
md.append(f"### π Summary Grading Report")
|
| 284 |
+
md.append(f"**Name:** {student_name} **Class:** {student_class}")
|
| 285 |
md.append(f"**Title:** {title}")
|
| 286 |
+
md.append(f"**Word count:** {wc}")
|
| 287 |
md.append(f"**Model used:** `{model_used}`")
|
| 288 |
md.append("")
|
| 289 |
+
md.append("#### Category-wise Scores")
|
| 290 |
+
if knows_story and comp is not None:
|
| 291 |
+
md.append(f"- **Comprehension:** {stars_bar(comp)} ({comp} stars)")
|
| 292 |
+
else:
|
| 293 |
+
md.append(f"- **Comprehension:** *(omitted)*")
|
| 294 |
+
md.append(f"- **Expression:** {stars_bar(expr)} ({expr} stars)")
|
| 295 |
+
md.append(f"- **Reflection/Moral Takeaway:** {stars_bar(refl)} ({refl} stars)")
|
| 296 |
+
md.append(f"- **Length:** {stars_bar(len_s)} ({len_s} stars, based on {wc} words)")
|
| 297 |
+
md.append(f"- **Grammar:** {stars_bar(grammar_star)} ({grammar_star:.1f} stars, {grammar_count} mistakes)")
|
| 298 |
md.append("")
|
| 299 |
+
md.append(f"**Average Score:** {avg:.2f} {stars_bar(avg)} *(out of 5)*")
|
| 300 |
md.append("")
|
| 301 |
+
md.append("#### Corrected Passage (LLM, minimal edits)")
|
| 302 |
+
md.append(f"{corrected if corrected else '_(No changes returned by the model.)_'}")
|
| 303 |
md.append("")
|
| 304 |
+
md.append("#### Annotated Original (exact mistake spans)")
|
| 305 |
+
annotated = annotate_original_with_issues(student_summary, issues)
|
| 306 |
+
md.append(f"{annotated}")
|
| 307 |
+
md.append("")
|
| 308 |
+
md.append("#### Grammar Issues (with positions)")
|
| 309 |
+
if not issues:
|
| 310 |
+
md.append("- None π")
|
| 311 |
+
else:
|
| 312 |
+
for i, it in enumerate(issues, 1):
|
| 313 |
+
err = (it.get('error_excerpt') or '').strip()
|
| 314 |
+
cor = (it.get('correction') or '').strip()
|
| 315 |
+
why = (it.get('explanation') or '').strip()
|
| 316 |
+
si = it.get('start_index', '?')
|
| 317 |
+
ei = it.get('end_index', '?')
|
| 318 |
+
md.append(f"{i}. `[{si}:{ei}]` **{err}** β **{cor}** β {why}")
|
| 319 |
+
md.append("")
|
| 320 |
+
md.append("#### Program-applied corrections (by offsets)")
|
| 321 |
+
program_fixed = apply_corrections_by_offsets(student_summary, issues)
|
| 322 |
+
md.append(f"{program_fixed}")
|
| 323 |
+
md.append("")
|
| 324 |
+
md.append("#### Overall Remark")
|
| 325 |
+
md.append(f"{remarks if remarks else '_(None)_'}")
|
| 326 |
+
md_str = "\n".join(md)
|
| 327 |
+
|
| 328 |
+
# Append to Google Sheet
|
| 329 |
+
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
|
| 330 |
+
row = [
|
| 331 |
+
timestamp,
|
| 332 |
+
student_name,
|
| 333 |
+
student_class,
|
| 334 |
+
title,
|
| 335 |
+
wc,
|
| 336 |
+
"Yes" if knows_story else "No",
|
| 337 |
+
(comp if comp is not None else ""),
|
| 338 |
+
expr,
|
| 339 |
+
refl,
|
| 340 |
+
len_s,
|
| 341 |
+
grammar_count,
|
| 342 |
+
grammar_star,
|
| 343 |
+
avg,
|
| 344 |
+
model_used,
|
| 345 |
+
remarks,
|
| 346 |
+
]
|
| 347 |
+
sheets_status = append_to_sheet(row)
|
| 348 |
+
status_text = "Saved to Google Sheet β
" if sheets_status == "OK" else f"Not saved β β {sheets_status}"
|
| 349 |
+
|
| 350 |
+
return md_str, corrected, status_text
|
| 351 |
|
| 352 |
# ==================== UI ====================
|
| 353 |
+
with gr.Blocks(title="Summary Grader (DeepSeek β OpenAI) + Google Sheets") as demo:
|
| 354 |
+
gr.Markdown("## Summary Grader\nDeepSeek-V3.2-Exp first; falls back to OpenAI GPT-5 if needed. Results are saved to Google Sheets.")
|
| 355 |
|
| 356 |
with gr.Row():
|
| 357 |
+
student_name = gr.Textbox(label="Student Name", placeholder="Riya Sen")
|
| 358 |
+
student_class = gr.Textbox(label="Class/Grade", placeholder="Class 6")
|
| 359 |
|
| 360 |
+
# Friendly explainer
|
| 361 |
+
intro_out = gr.Markdown(label="Welcome Message", visible=True)
|
| 362 |
+
start_btn = gr.Button("Show How Iβll Mark You", variant="secondary")
|
| 363 |
+
start_btn.click(fn=intro_message, inputs=[student_name, student_class], outputs=intro_out)
|
| 364 |
|
| 365 |
with gr.Row():
|
| 366 |
+
title_in = gr.Textbox(label="Book/Movie Title", placeholder="The Gift of the Magi")
|
| 367 |
+
|
| 368 |
+
summary_in = gr.Textbox(label="Paste the student's summary", lines=12, placeholder="Paste text here...")
|
| 369 |
+
|
| 370 |
+
btn = gr.Button("Grade & Save", variant="primary")
|
| 371 |
|
| 372 |
+
report_out = gr.Markdown(label="Grading Report")
|
| 373 |
+
corrected_out = gr.Textbox(label="Corrected Passage (plain text)", lines=10)
|
| 374 |
+
status_out = gr.Markdown(label="Save Status")
|
| 375 |
|
| 376 |
+
btn.click(fn=grade_summary,
|
| 377 |
+
inputs=[student_name, student_class, title_in, summary_in],
|
| 378 |
+
outputs=[report_out, corrected_out, status_out])
|
| 379 |
|
| 380 |
+
# Entrypoint for Spaces
|
| 381 |
if __name__ == "__main__":
|
| 382 |
demo.launch()
|