Spaces:
Running
Running
File size: 22,597 Bytes
64378fa | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 | // Rubric, credits and the deterministic reviewer.
// The reviewer is rule-based and runs with no model, so every tool works
// offline. When a model is connected, marking.js can also build the JSON prompt
// used by the AI marker.
export const PARAGRAPH_RUBRIC = [
{
id: "point",
title: "Point",
max: 2,
guidance:
"A clear, focused answer to the question that uses the text's terms. 2 = precise and relevant; 1 = general or partly off-question; 0 = missing."
},
{
id: "evidence",
title: "Evidence",
max: 2,
guidance:
"A short, accurate quotation embedded in the sentence. 2 = accurate, concise and well chosen; 1 = present but vague, long or loosely used; 0 = none. A quotation missing from a partial extract is not penalised."
},
{
id: "method",
title: "Method",
max: 2,
guidance:
"Names a technique or a deliberate authorial choice (word class, imagery, structure, form). 2 = precise terminology; 1 = vague reference to language; 0 = none."
},
{
id: "effect",
title: "Effect",
max: 3,
guidance:
"Explains how the method shapes the reader's response, with a developed 'because'. 3 = layered, alternative reading; 2 = clear effect explained; 1 = asserted effect; 0 = none."
},
{
id: "link",
title: "Link",
max: 1,
guidance:
"Ties the paragraph back to the question or the text's wider ideas. 1 = explicit link; 0 = missing."
}
];
export const ESSAY_RUBRICS = {
introduction: [
{ id: "focus", title: "Focus", max: 2, guidance: "Directly answers the question with a shaped line of argument." },
{ id: "thesis", title: "Thesis", max: 2, guidance: "A clear overall argument that the essay will prove." }
],
body_1: [
{ id: "point", title: "Point", max: 2, guidance: "A topic sentence that advances the argument." },
{ id: "evidence", title: "Evidence", max: 2, guidance: "Up to three short, accurate quotations, embedded." },
{ id: "analysis", title: "Analysis", max: 2, guidance: "Method and effect developed together." }
],
body_2: [
{ id: "point", title: "Point", max: 2, guidance: "A topic sentence that advances the argument." },
{ id: "evidence", title: "Evidence", max: 2, guidance: "Up to three short, accurate quotations, embedded." },
{ id: "analysis", title: "Analysis", max: 2, guidance: "Method and effect developed together." }
],
body_3: [
{ id: "point", title: "Point", max: 2, guidance: "A topic sentence that advances the argument." },
{ id: "evidence", title: "Evidence", max: 2, guidance: "Up to three short, accurate quotations, embedded." },
{ id: "analysis", title: "Analysis", max: 2, guidance: "Method and effect developed together." }
],
conclusion: [
{ id: "return", title: "Return to question", max: 2, guidance: "Answers the question again, now that the evidence is in." },
{ id: "significance", title: "Wider significance", max: 2, guidance: "Connects to context, the whole text or a lasting idea." }
],
cohesion: [
{ id: "structure", title: "Structure", max: 2, guidance: "Paragraphs build in a deliberate order and signpost the argument." },
{ id: "thread", title: "Thread of argument", max: 2, guidance: "The same argument is developed throughout, not restated." }
]
};
export const ESSAY_PART_META = [
{ id: "introduction", title: "Introduction", short: "Intro" },
{ id: "body_1", title: "Body paragraph 1", short: "Body 1" },
{ id: "body_2", title: "Body paragraph 2", short: "Body 2" },
{ id: "body_3", title: "Body paragraph 3", short: "Body 3" },
{ id: "conclusion", title: "Conclusion", short: "Conclusion" },
{ id: "cohesion", title: "Cohesion (whole essay)", short: "Cohesion" }
];
export const CREDIT_COSTS = {
paragraphWriting: 20,
modelAnswer: 20,
essayDeep: 30,
mockExam: 40
};
export function creditsForParagraph(score) {
if (score >= 10) return 50;
if (score === 9) return 30;
if (score >= 7) return 15;
if (score >= 5) return 5;
return 0;
}
export function creditsForEssay(score) {
if (score >= 29) return 200;
if (score >= 26) return 120;
if (score >= 21) return 60;
if (score >= 15) return 20;
return 0;
}
export function streakMultiplier(days) {
if (days >= 14) return 1.4;
if (days >= 7) return 1.25;
if (days >= 3) return 1.1;
return 1;
}
export function awardCredits(base, streakDays) {
if (base <= 0) return 0;
return Math.round(base * streakMultiplier(streakDays));
}
export function levelFor(totalEarned) {
if (totalEarned <= 0) return 1;
return Math.min(10, 1 + Math.floor(totalEarned / 150));
}
export function levelProgress(totalEarned) {
const level = levelFor(totalEarned);
if (level >= 10) return 1;
return (totalEarned - (level - 1) * 150) / 150;
}
export function levelTitle(level) {
return (
[
"Starting out",
"Finding your voice",
"Close reader",
"Confident analyst",
"Sharp critic",
"Precise writer",
"Independent thinker",
"Grade 8 habit",
"Grade 9 habit",
"Examiner's eye"
][Math.min(9, Math.max(0, level - 1))]
);
}
const DAY = 86400000;
export function streakLength(isoDays) {
if (!isoDays || isoDays.length === 0) return 0;
const days = [...new Set(isoDays)].sort().reverse();
const today = new Date();
const start = new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime();
const latest = new Date(days[0] + "T00:00:00").getTime();
if (latest !== start && latest !== start - DAY) return 0;
let streak = 0;
let expected = latest;
for (const iso of days) {
const t = new Date(iso + "T00:00:00").getTime();
if (t === expected) {
streak += 1;
expected -= DAY;
} else if (t < expected) break;
}
return streak;
}
// ---------------------------------------------------------------------------
// Texts
// ---------------------------------------------------------------------------
export const TEXTS = [
{ id: "macbeth", title: "Macbeth", author: "William Shakespeare", kind: "Play" },
{ id: "christmas-carol", title: "A Christmas Carol", author: "Charles Dickens", kind: "Novel" },
{ id: "inspector-calls", title: "An Inspector Calls", author: "J. B. Priestley", kind: "Play" },
{ id: "jekyll-hyde", title: "Jekyll and Hyde", author: "R. L. Stevenson", kind: "Novel" },
{ id: "lord-flies", title: "Lord of the Flies", author: "William Golding", kind: "Novel" },
{ id: "power-conflict", title: "Power & Conflict poems", author: "AQA anthology", kind: "Poetry" },
{ id: "other", title: "Another text", author: "", kind: "Text" }
];
export const SUGGESTED_QUESTIONS = [
"How does Shakespeare present ambition in Macbeth?",
"How does Dickens present Scrooge as an outsider?",
"How does Priestley use the Inspector to challenge the Birlings?",
"How does Stevenson present duality in Jekyll and Hyde?",
"How does the writer use structure to build tension?"
];
// ---------------------------------------------------------------------------
// Text analysis
// ---------------------------------------------------------------------------
const DOUBLE_QUOTE = /[“"]([^”"]{2,220})[”"]/g;
const SINGLE_QUOTE = /(?:^|[\s(])[‘']([^’']{8,220})[’'](?=[\s.,;:!?)]|$)/g;
export function wordCount(text) {
return text.trim() ? text.trim().split(/\s+/).length : 0;
}
export function sentenceList(text) {
return text
.replace(/\s+/g, " ")
.split(/(?<=[.!?])\s+/)
.map((s) => s.trim())
.filter(Boolean);
}
export function normalise(text) {
return " " + text
.toLowerCase()
.replace(/[’‘]/g, "'")
.replace(/[“”]/g, '"')
.replace(/[^a-z0-9' ]+/g, " ")
.replace(/\s+/g, " ")
.trim() + " ";
}
const TECHNIQUES = [
"metaphor", "simile", "personification", "imagery", "semantic field", "juxtaposition",
"contrast", "repetition", "alliteration", "sibilance", "onomatopoeia", "hyperbole",
"oxymoron", "symbolism", "motif", "foreshadow", "dramatic irony", "soliloquy",
"stage direction", "aside", "enjambment", "caesura", "stanza", "rhyme", "rhythm",
"iambic", "short sentence", "long sentence", "listing", "rule of three",
"rhetorical question", "direct address", "dialect", "colloquial", "satire", "form",
"structure", "verb", "noun", "adjective", "adverb", "connotation", "tone", "voice"
];
const EFFECT_VERBS = [
"suggests", "suggesting", "conveys", "conveying", "creates", "creating", "implies",
"implying", "highlights", "emphasises", "emphasizes", "reveals", "revealing",
"reflects", "evokes", "illustrates", "demonstrates", "underscores", "presents",
"portrays", "exposes", "critiques", "challenges", "reinforces", "foreshadows",
"makes the reader", "allows the reader", "shows the reader"
];
const CAUSAL = ["because", "which", "therefore", "as a result", "so that", "in order to", "this creates", "allowing", "enabling", "meaning"];
const LINK_PHRASES = ["therefore", "overall", "this shows", "this suggests", "the wider", "context", "audience", "reader", "the text", "the play", "the novel"];
function findTechniques(lower) {
return TECHNIQUES.filter((t) => lower.includes(t));
}
function findEffectVerbs(lower) {
return EFFECT_VERBS.filter((v) => lower.includes(v));
}
function questionWords(question) {
const stop = new Set(["how", "does", "the", "and", "in", "of", "to", "a", "an", "is", "are", "what", "why", "writer", "present", "use", "using", "explain"]);
return question
.toLowerCase()
.replace(/[^a-z0-9 ]+/g, " ")
.split(/\s+/)
.filter((w) => w.length > 2 && !stop.has(w));
}
function overlap(text, words) {
const lower = " " + text.toLowerCase() + " ";
return words.filter((w) => lower.includes(w)).length;
}
export function extractQuotes(text) {
const found = [];
let match;
DOUBLE_QUOTE.lastIndex = 0;
while ((match = DOUBLE_QUOTE.exec(text)) !== null) found.push(match[1].trim());
SINGLE_QUOTE.lastIndex = 0;
while ((match = SINGLE_QUOTE.exec(text)) !== null) found.push(match[1].trim());
return found.filter((q) => q.length > 1);
}
export function checkQuotes(text, extract) {
const quotes = extractQuotes(text);
const haystack = extract && extract.trim() ? normalise(extract) : null;
return quotes.map((q) => {
const words = wordCount(q);
const inExtract = haystack ? haystack.includes(normalise(q).trim()) : null;
let note = null;
if (words > 12) note = "Long quotation — trim it to a few words and embed it in your sentence.";
else if (inExtract === false) note = "Not found in the extract you pasted. It may be from another part of the text — check your copy.";
return { text: q, words, inExtract, note };
});
}
// ---------------------------------------------------------------------------
// Scoring
// ---------------------------------------------------------------------------
function clamp(n, min, max) {
return Math.max(min, Math.min(max, n));
}
function scoreCriterion(id, ctx) {
switch (id) {
case "point":
case "focus": {
if (ctx.words >= 45 && ctx.overlap >= 2) return 2;
if (ctx.words >= 20 && (ctx.overlap >= 1 || ctx.linkHit)) return 1;
return 0;
}
case "thesis": {
if (/(this essay will|i will argue|i will show|the essay will|argue that|thesis)/.test(ctx.lower) && ctx.words >= 25) return 2;
if (ctx.overlap >= 2 && ctx.words >= 35) return 1;
return 0;
}
case "evidence": {
if (ctx.quotes.length >= 2 && ctx.quotes.some((q) => q.words <= 12)) return 2;
if (ctx.quotes.length >= 1) return 1;
return 0;
}
case "method": {
if (ctx.techniques.length >= 2) return 2;
if (ctx.techniques.length === 1) return 1;
return 0;
}
case "analysis": {
if (ctx.techniques.length >= 1 && ctx.effectVerbs.length >= 1 && ctx.hasBecause) return 2;
if (ctx.techniques.length >= 1 || ctx.effectVerbs.length >= 1) return 1;
return 0;
}
case "effect": {
if (ctx.effectVerbs.length >= 2 && ctx.hasBecause && ctx.sentences >= 4) return 3;
if (ctx.effectVerbs.length >= 1 && (ctx.hasBecause || ctx.effectVerbs.length >= 2)) return 2;
if (ctx.effectVerbs.length >= 1 || ctx.hasBecause) return 1;
return 0;
}
case "link": {
if (ctx.lastSentenceOverlap >= 1 || (ctx.linkHit && ctx.overlap >= 1)) return 1;
return 0;
}
case "return": {
if (ctx.lastSentenceOverlap >= 2) return 2;
if (ctx.lastSentenceOverlap >= 1 || ctx.linkHit) return 1;
return 0;
}
case "significance": {
if (/(context|society|audience|victorian|edwardian|shakespeare|priestley|dickens|stevenson|golding|modern|today)/.test(ctx.lower) && ctx.overlap >= 1) return 2;
if (/(context|society|audience|victorian|edwardian|shakespeare|priestley|dickens|stevenson|golding|modern|today)/.test(ctx.lower)) return 1;
return 0;
}
case "structure": {
if (ctx.paragraphs >= 3 && /(firstly|secondly|finally|however|therefore|in contrast|moreover)/.test(ctx.lower)) return 2;
if (ctx.paragraphs >= 2) return 1;
return 0;
}
case "thread": {
if (ctx.repeatedTerms >= 2 && ctx.paragraphs >= 3) return 2;
if (ctx.repeatedTerms >= 1) return 1;
return 0;
}
default:
return 0;
}
}
function noteFor(id, ctx, score, max) {
const full = score === max;
switch (id) {
case "point":
case "focus":
return full
? "Focused on the question and using the text's own terms."
: ctx.overlap === 0
? "The opening does not pick up the question's key words. Name the character, relationship or idea you are answering about."
: "Sharpen the opening so it answers the exact question, not the text in general.";
case "thesis":
return full
? "A clear overall argument is promised."
: "Add one sentence that says what the whole essay will prove: 'This essay will argue that…'.";
case "evidence":
if (ctx.quotes.length === 0) return "No quotation. Choose two or three words and embed them in your own sentence.";
if (ctx.quotes.length === 1) return "One quotation found. A second short one would let you compare or develop the point.";
return full ? "Short quotations, ready to analyse." : "Trim the longest quotation: the best evidence is usually two to five words.";
case "method":
if (full) return "Precise technique named: " + ctx.techniques.slice(0, 2).join(", ") + ".";
if (ctx.techniques.length === 1) return "One technique named (" + ctx.techniques[0] + "). Name a second choice — structure, form or a word class.";
return "Name the writer's method exactly: metaphor, personification, a short sentence, a stage direction…";
case "analysis":
if (full) return "Method and effect are working together.";
return "Link the technique to its effect in the same sentence: 'The … suggests … because …'.";
case "effect":
if (full) return "Developed effect with a reason — exactly what examiners reward.";
if (ctx.effectVerbs.length === 0) return "The effect is not explained yet. Add what the reader feels or understands, and why.";
return "Push the effect further with 'because…', or offer an alternative reading.";
case "link":
return full ? "Tied back to the question." : "End by returning to the question's key words, or to the text's wider idea.";
case "return":
return full ? "Returns to the question with the evidence behind it." : "Answer the question again in your final sentence, now that the evidence is in.";
case "significance":
return full ? "Connects the detail to context or the whole text." : "Add one sentence on why this matters beyond the quotation — context, the whole text, or the reader.";
case "structure":
return full ? "The argument is signposted and ordered." : "Signpost the argument: 'Firstly… However… Finally…'.";
case "thread":
return full ? "The same argument is developed across the essay." : "Repeat one key term across paragraphs so the argument feels continuous.";
default:
return "";
}
}
export function reviewText({ text, question = "", extract = "", rubric, title = "" }) {
const clean = text.trim();
const words = wordCount(clean);
const sentences = sentenceList(clean);
const lower = " " + clean.toLowerCase() + " ";
const quotes = checkQuotes(clean, extract);
const techniques = findTechniques(lower);
const effectVerbs = findEffectVerbs(lower);
const qWords = questionWords(question);
const questionOverlap = overlap(clean, qWords);
const lastSentence = sentences[sentences.length - 1] || "";
const lastSentenceOverlap = overlap(lastSentence, qWords);
const paragraphs = clean.split(/\n\s*\n/).filter((p) => p.trim().length > 0).length || (words > 0 ? 1 : 0);
const terms = qWords.filter((w) => (lower.match(new RegExp("\\b" + w + "\\b", "g")) || []).length >= 2);
const ctx = {
text: clean,
lower,
words,
sentences: sentences.length,
quotes,
techniques,
effectVerbs,
hasBecause: CAUSAL.some((c) => lower.includes(c)),
linkHit: LINK_PHRASES.some((p) => lower.includes(p)),
overlap: questionOverlap,
lastSentenceOverlap,
paragraphs,
repeatedTerms: terms.length
};
const criteria = rubric.map((c) => {
const raw = scoreCriterion(c.id, ctx);
const score = clamp(raw, 0, c.max);
return { ...c, score, note: noteFor(c.id, ctx, score, c.max) };
});
const total = criteria.reduce((sum, c) => sum + c.score, 0);
const max = criteria.reduce((sum, c) => sum + c.max, 0);
const sorted = [...criteria].sort((a, b) => b.score / b.max - a.score / a.max);
const best = sorted[0];
const worst = sorted[sorted.length - 1];
const strengths = [];
if (quotes.length) strengths.push("You used " + quotes.length + " quotation" + (quotes.length === 1 ? "" : "s") + ": " + quotes.slice(0, 2).map((q) => "“" + q.text + "”").join(", ") + ".");
if (techniques.length) strengths.push("Named method" + (techniques.length === 1 ? "" : "s") + ": " + techniques.slice(0, 3).join(", ") + ".");
if (ctx.hasBecause) strengths.push("You explained a cause, not just an effect — that is where analysis starts.");
if (best && best.score > 0 && strengths.length < 2) strengths.push(best.title + ": " + best.note);
if (strengths.length === 0) strengths.push("You have made a start. The first step is one clear point in your own words.");
const allFull = criteria.every((c) => c.score === c.max);
const improvements = allFull ? [] : [worst.title + ": " + worst.note];
if (quotes.some((q) => q.words > 12)) improvements.push("Trim long quotations to the few words that carry the meaning.");
if (!ctx.hasBecause && words > 30) improvements.push("Add one 'because…' to turn an asserted effect into an explanation.");
const nextStep = allFull
? "Full marks here. Keep this paragraph as a model, then try the same question on a second extract or build it into a full essay."
: worst.id === "evidence"
? "Write the next version with two short quotations, each embedded in a sentence of your own."
: worst.id === "method"
? "Rewrite one sentence to name the exact technique, then say what it makes the reader feel."
: worst.id === "effect"
? "Take your strongest quotation and add: 'This suggests … because …'."
: "Rewrite the weakest sentence to answer the question directly, then re-mark it.";
return {
total,
max,
criteria,
strengths,
improvements: improvements.slice(0, 3),
nextStep,
quotes,
techniques,
engine: "offline",
title
};
}
export function reviewParagraph(args) {
return reviewText({ ...args, rubric: PARAGRAPH_RUBRIC });
}
export function reviewEssayPart(part, args) {
return reviewText({ ...args, rubric: ESSAY_RUBRICS[part] || PARAGRAPH_RUBRIC });
}
export function combineEssay(parts) {
const total = parts.reduce((sum, p) => sum + (p ? p.total : 0), 0);
const max = parts.reduce((sum, p) => sum + (p ? p.max : 0), 0);
return { total, max };
}
// ---------------------------------------------------------------------------
// Model prompt + response parsing
// ---------------------------------------------------------------------------
export function buildMarkingMessages({ text, question, extract, rubric, textTitle, mode }) {
const system = [
"You are Explication, a GCSE English Literature writing coach for students in England.",
"You mark the student's own writing against the rubric, name what works, then name the single highest-impact improvement.",
"Reply in British English, address the student as 'you'.",
"Return ONE JSON object only, with this shape:",
'{"scores":{"<criterionId>":0},"strengths":["..."],"improvements":["..."],"nextStep":"...","quoteNotes":["..."]}',
"Scores must be whole numbers no higher than each criterion's maximum.",
"Do not write the student's paragraph for them."
].join(" ");
const rubricText = rubric.map((c) => `${c.id} (0-${c.max}): ${c.title}. ${c.guidance}`).join("\n");
const user = [
`Mode: ${mode || "paragraph"}`,
textTitle ? `Text: ${textTitle}` : "",
question ? `Question: ${question}` : "",
`Rubric:\n${rubricText}`,
extract ? `Extract the student supplied:\n"""${extract.slice(0, 4000)}"""` : "No extract supplied.",
`Student writing:\n"""${text}"""`
].filter(Boolean).join("\n\n");
return [
{ role: "system", content: system },
{ role: "user", content: user }
];
}
export function parseMarkingReply(raw, rubric) {
const start = raw.indexOf("{");
const end = raw.lastIndexOf("}");
if (start === -1 || end === -1) throw new Error("The model did not return JSON.");
const data = JSON.parse(raw.slice(start, end + 1));
const scores = data.scores || {};
const criteria = rubric.map((c) => {
const value = Number(scores[c.id]);
const score = clamp(Number.isFinite(value) ? Math.round(value) : 0, 0, c.max);
return { ...c, score, note: "" };
});
const total = criteria.reduce((sum, c) => sum + c.score, 0);
return {
total,
max: rubric.reduce((sum, c) => sum + c.max, 0),
criteria,
strengths: Array.isArray(data.strengths) ? data.strengths.slice(0, 4).map(String) : [],
improvements: Array.isArray(data.improvements) ? data.improvements.slice(0, 3).map(String) : [],
nextStep: typeof data.nextStep === "string" ? data.nextStep : "",
quotes: [],
techniques: [],
engine: "model"
};
}
|