Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,239 +1,327 @@
|
|
| 1 |
# --------------------------------------------------------------
|
| 2 |
-
# IGCSE Language Platform –
|
| 3 |
-
# Model:
|
|
|
|
| 4 |
# --------------------------------------------------------------
|
| 5 |
-
|
| 6 |
import os
|
| 7 |
import json
|
|
|
|
| 8 |
from datetime import datetime
|
| 9 |
import gradio as gr
|
| 10 |
from huggingface_hub import InferenceClient
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
# ---------- 1. HF Inference
|
| 13 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 14 |
if not HF_TOKEN:
|
| 15 |
-
raise gr.Error("
|
| 16 |
-
|
| 17 |
client = InferenceClient(token=HF_TOKEN)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
MODEL = "openai/gpt-oss-safeguard-20b:groq"
|
| 20 |
-
|
| 21 |
-
# ---------- 2. Global storage ----------
|
| 22 |
-
papers_storage = []
|
| 23 |
-
|
| 24 |
-
# ---------- 3. Topic lists ----------
|
| 25 |
-
french_topics = [
|
| 26 |
-
"Greetings & Introductions", "Family & Relationships", "Daily Routines",
|
| 27 |
-
"Food & Restaurants", "Shopping & Money", "Travel & Transport",
|
| 28 |
-
"School & Education", "Hobbies & Free Time", "Weather & Seasons",
|
| 29 |
-
"House & Home", "Health & Body", "Work & Future Plans",
|
| 30 |
-
"Technology & Media", "Environment", "Grammar: Present Tense",
|
| 31 |
-
"Grammar: Past Tenses", "Grammar: Future Tense", "Grammar: Pronouns",
|
| 32 |
-
"Grammar: Adjectives"
|
| 33 |
-
]
|
| 34 |
-
|
| 35 |
-
efl_topics = [
|
| 36 |
-
"Reading Comprehension", "Writing: Narrative", "Writing: Descriptive",
|
| 37 |
-
"Writing: Argumentative", "Writing: Formal Letters", "Writing: Informal Letters",
|
| 38 |
-
"Grammar: Tenses", "Grammar: Conditionals", "Grammar: Passive Voice",
|
| 39 |
-
"Grammar: Reported Speech", "Vocabulary: Idioms", "Vocabulary: Phrasal Verbs",
|
| 40 |
-
"Literature Analysis", "Poetry Analysis", "Speaking & Pronunciation",
|
| 41 |
-
"Listening Comprehension"
|
| 42 |
-
]
|
| 43 |
-
|
| 44 |
-
# ---------- 4. Helper: call the model ----------
|
| 45 |
-
def call_model(messages: list, system: str = "", max_tokens=1000):
|
| 46 |
try:
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
except Exception as e:
|
| 56 |
-
return f"Error: {e}"
|
| 57 |
-
|
| 58 |
-
# ----------
|
| 59 |
-
def
|
| 60 |
-
if not
|
| 61 |
-
return
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
history.append((message, bot))
|
| 71 |
-
return history
|
| 72 |
-
|
| 73 |
-
def clear_chat():
|
| 74 |
-
return []
|
| 75 |
-
|
| 76 |
-
# ---------- 6. Translator ----------
|
| 77 |
-
def translate_text(text, direction):
|
| 78 |
-
if not text.strip():
|
| 79 |
-
return "Enter text first."
|
| 80 |
-
src = "English" if direction == "English → French" else "French"
|
| 81 |
-
tgt = "French" if direction == "English → French" else "English"
|
| 82 |
-
prompt = f"Translate from {src} to {tgt}. Only the translation:\n\n{text}"
|
| 83 |
-
return call_model([{"role": "user", "content": prompt}], max_tokens=500)
|
| 84 |
-
|
| 85 |
-
# ---------- 7. Dictionary ----------
|
| 86 |
-
def dictionary_lookup(word):
|
| 87 |
-
if not word.strip():
|
| 88 |
-
return "Enter a French word."
|
| 89 |
-
prompt = f"""Give a clear French dictionary entry for "{word}":
|
| 90 |
-
- Part of speech
|
| 91 |
-
- English meaning(s)
|
| 92 |
-
- Gender (if noun)
|
| 93 |
-
- 2 example sentences (French + English)
|
| 94 |
-
- Common phrases"""
|
| 95 |
-
return call_model([{"role": "user", "content": prompt}], max_tokens=800)
|
| 96 |
-
|
| 97 |
-
# ---------- 8. Practice Questions ----------
|
| 98 |
-
def generate_question(subject, topic):
|
| 99 |
-
if not topic:
|
| 100 |
-
return "Select a topic!", "", ""
|
| 101 |
-
prompt = f"""Create ONE IGCSE {subject} question on "{topic}".
|
| 102 |
-
Return valid JSON with exactly these keys:
|
| 103 |
-
{{"question": "...", "expectedAnswer": "short description of expected answer"}}"""
|
| 104 |
-
txt = call_model([{"role": "user", "content": prompt}], max_tokens=600)
|
| 105 |
-
try:
|
| 106 |
-
data = json.loads(txt.replace("```json", "").replace("```", "").strip())
|
| 107 |
-
return data["question"], data["expectedAnswer"], ""
|
| 108 |
-
except Exception:
|
| 109 |
-
return txt, "", ""
|
| 110 |
|
| 111 |
-
|
|
|
|
| 112 |
if not user_answer.strip():
|
| 113 |
-
return "
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
Student answer: {user_answer}
|
| 118 |
|
| 119 |
-
Reply
|
| 120 |
-
{{
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
if not all([title, subject, content]):
|
| 133 |
-
return "Fill all fields!", get_papers_list()
|
| 134 |
-
papers_storage.append({
|
| 135 |
-
"id": len(papers_storage) + 1,
|
| 136 |
-
"title": title,
|
| 137 |
-
"subject": subject.lower(),
|
| 138 |
-
"content": content,
|
| 139 |
-
"uploaded_at": datetime.now().strftime("%Y-%m-%d %H:%M")
|
| 140 |
-
})
|
| 141 |
-
return "Uploaded!", get_papers_list()
|
| 142 |
-
|
| 143 |
-
def get_papers_list():
|
| 144 |
-
if not papers_storage:
|
| 145 |
-
return "No papers yet."
|
| 146 |
-
return "\n".join(
|
| 147 |
-
f"**{p['title']}** ({p['subject'].upper()})\n{p['uploaded_at']}\n{p['content'][:120]}...\n{'─'*40}"
|
| 148 |
-
for p in papers_storage
|
| 149 |
-
)
|
| 150 |
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
return "\n".join(
|
| 156 |
-
f"**{p['title']}**
|
| 157 |
-
for p in
|
| 158 |
)
|
| 159 |
|
| 160 |
-
# ---------- 10.
|
| 161 |
-
with gr.Blocks(theme=gr.themes.Soft(), title="IGCSE Language
|
| 162 |
-
gr.Markdown("
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
|
| 164 |
with gr.Tabs():
|
| 165 |
-
#
|
| 166 |
-
with gr.Tab("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
with gr.Tabs():
|
| 168 |
-
with gr.Tab("
|
| 169 |
-
gr.
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
subj.change(upd_topics, subj, topc)
|
| 177 |
-
|
| 178 |
-
chat = gr.Chatbot(height=450)
|
| 179 |
-
txt = gr.Textbox(placeholder="Ask anything…", label="Message", scale=4)
|
| 180 |
-
with gr.Row():
|
| 181 |
-
send = gr.Button("Send")
|
| 182 |
-
clr = gr.Button("Clear")
|
| 183 |
-
send.click(ai_tutor_chat, [txt, chat, subj, topc], chat)
|
| 184 |
-
txt.submit(ai_tutor_chat, [txt, chat, subj, topc], chat)
|
| 185 |
-
clr.click(clear_chat, outputs=chat)
|
| 186 |
-
|
| 187 |
-
with gr.Tab("Translator"):
|
| 188 |
-
dir_ = gr.Radio(["English → French", "French → English"], label="Direction", value="English → French")
|
| 189 |
-
inp = gr.Textbox(lines=4, label="Text")
|
| 190 |
-
out = gr.Textbox(lines=4, label="Translation")
|
| 191 |
-
gr.Button("Translate").click(translate_text, [inp, dir_], out)
|
| 192 |
-
|
| 193 |
with gr.Tab("Dictionary"):
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
gr.Button("Lookup").click(
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
ans = gr.Textbox(lines=5, label="Your answer")
|
| 207 |
-
fb = gr.Textbox(lines=8, label="Feedback")
|
| 208 |
-
|
| 209 |
-
gr.Button("Generate").click(generate_question, [ps, pt], [q, exp, fb])
|
| 210 |
-
gr.Button("Check").click(check_answer, [q, exp, ans, ps], fb)
|
| 211 |
-
|
| 212 |
-
with gr.Tab("Past Papers"):
|
| 213 |
-
psb = gr.Radio(["French", "EFL"], label="Subject", value="French")
|
| 214 |
-
pd = gr.Textbox(lines=20, label="Papers")
|
| 215 |
-
gr.Button("Show").click(view_papers_student, psb, pd)
|
| 216 |
-
|
| 217 |
-
# ───── ADMIN ─────
|
| 218 |
-
with gr.Tab("Admin Panel"):
|
| 219 |
-
gr.Markdown("### Upload past papers")
|
| 220 |
with gr.Row():
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
|
|
|
|
|
|
|
|
|
| 230 |
|
| 231 |
gr.Markdown("""
|
| 232 |
---
|
| 233 |
-
**
|
| 234 |
-
|
| 235 |
-
2. Settings → Secrets → Add `HF_TOKEN` (your Hugging Face token)
|
| 236 |
-
3. Restart → Done!
|
| 237 |
""")
|
| 238 |
|
| 239 |
-
app.launch()
|
|
|
|
| 1 |
# --------------------------------------------------------------
|
| 2 |
+
# IGCSE Language Platform – REAL Past-Paper Powered (2025)
|
| 3 |
+
# Model: Groq + Llama-3.1-70B (fast & free tier)
|
| 4 |
+
# PDF → Text → AI → Real Exam Questions
|
| 5 |
# --------------------------------------------------------------
|
|
|
|
| 6 |
import os
|
| 7 |
import json
|
| 8 |
+
import uuid
|
| 9 |
from datetime import datetime
|
| 10 |
import gradio as gr
|
| 11 |
from huggingface_hub import InferenceClient
|
| 12 |
+
import PyPDF2
|
| 13 |
+
from pdf2image import convert_from_bytes
|
| 14 |
+
import pytesseract
|
| 15 |
+
from io import BytesIO
|
| 16 |
|
| 17 |
+
# ---------- 1. HF Inference (FREE) ----------
|
| 18 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 19 |
if not HF_TOKEN:
|
| 20 |
+
raise gr.Error("Add HF_TOKEN in Secrets!")
|
|
|
|
| 21 |
client = InferenceClient(token=HF_TOKEN)
|
| 22 |
+
MODEL = "meta-llama/Meta-Llama-3.1-70B-Instruct"
|
| 23 |
+
|
| 24 |
+
# ---------- 2. Global Storage ----------
|
| 25 |
+
papers_db = [] # Raw uploaded papers
|
| 26 |
+
questions_db = {} # {topic: [questions]}
|
| 27 |
+
user_progress = {} # {user_id: {topic: {correct, total, streak}}}
|
| 28 |
+
|
| 29 |
+
# ---------- 3. Topics ----------
|
| 30 |
+
TOPICS = {
|
| 31 |
+
"French": [
|
| 32 |
+
"Greetings", "Family", "Daily Routine", "Food", "Travel", "School",
|
| 33 |
+
"Hobbies", "Health", "Work", "Environment", "Present Tense",
|
| 34 |
+
"Passé Composé", "Imparfait", "Future", "Subjunctive", "Pronouns"
|
| 35 |
+
],
|
| 36 |
+
"EFL": [
|
| 37 |
+
"Reading Comp", "Narrative Writing", "Descriptive", "Argumentative",
|
| 38 |
+
"Formal Letter", "Informal Email", "Tenses", "Conditionals",
|
| 39 |
+
"Passive", "Reported Speech", "Idioms", "Phrasal Verbs"
|
| 40 |
+
]
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
# ---------- 4. OCR + PDF Text Extract ----------
|
| 44 |
+
def extract_text_from_pdf(file_obj):
|
| 45 |
+
try:
|
| 46 |
+
# Try direct text
|
| 47 |
+
reader = PyPDF2.PdfReader(file_obj)
|
| 48 |
+
text = "\n".join(page.extract_text() or "" for page in reader.pages)
|
| 49 |
+
if len(text.strip()) > 200:
|
| 50 |
+
return text
|
| 51 |
+
except:
|
| 52 |
+
pass
|
| 53 |
+
# Fallback: OCR
|
| 54 |
+
images = convert_from_bytes(file_obj.read())
|
| 55 |
+
return "\n".join(pytesseract.image_to_string(img) for img in images)
|
| 56 |
+
|
| 57 |
+
# ---------- 5. AI: Tag + Extract Questions ----------
|
| 58 |
+
def process_past_paper(title, subject, pdf_file, insert_file=None):
|
| 59 |
+
text = extract_text_from_pdf(pdf_file)
|
| 60 |
+
insert_text = extract_text_from_pdf(insert_file) if insert_file else ""
|
| 61 |
+
|
| 62 |
+
prompt = f"""
|
| 63 |
+
You are an IGCSE {subject} examiner. Extract EVERY question from this past paper.
|
| 64 |
+
For each question:
|
| 65 |
+
- Exact question text
|
| 66 |
+
- Topic (choose one: {', '.join(TOPICS[subject])})
|
| 67 |
+
- Marks
|
| 68 |
+
- Year & Paper code (if visible)
|
| 69 |
+
- Type: Reading / Writing / Listening / Translation
|
| 70 |
+
|
| 71 |
+
Return valid JSON only:
|
| 72 |
+
{{
|
| 73 |
+
"paper": "{title}",
|
| 74 |
+
"questions": [
|
| 75 |
+
{{
|
| 76 |
+
"id": "auto",
|
| 77 |
+
"text": "...",
|
| 78 |
+
"topic": "Food",
|
| 79 |
+
"marks": 5,
|
| 80 |
+
"year": "2023",
|
| 81 |
+
"type": "Reading"
|
| 82 |
+
}}
|
| 83 |
+
]
|
| 84 |
+
}}
|
| 85 |
+
Paper text:
|
| 86 |
+
{text[:12000]}
|
| 87 |
+
|
| 88 |
+
Insert (if any):
|
| 89 |
+
{insert_text[:4000]}
|
| 90 |
+
"""
|
| 91 |
+
resp = client.chat.completions.create(
|
| 92 |
+
model=MODEL,
|
| 93 |
+
messages=[{"role": "user", "content": prompt}],
|
| 94 |
+
max_tokens=4000,
|
| 95 |
+
temperature=0.3
|
| 96 |
+
).choices[0].message.content.strip()
|
| 97 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
try:
|
| 99 |
+
data = json.loads(resp.replace("```json", "").replace("```", ""))
|
| 100 |
+
paper_id = str(uuid.uuid4())[:8]
|
| 101 |
+
added = 0
|
| 102 |
+
for q in data["questions"]:
|
| 103 |
+
qid = str(uuid.uuid4())[:6]
|
| 104 |
+
q["id"] = qid
|
| 105 |
+
q["paper_id"] = paper_id
|
| 106 |
+
q["source"] = title
|
| 107 |
+
topic = q["topic"]
|
| 108 |
+
if topic not in questions_db:
|
| 109 |
+
questions_db[topic] = []
|
| 110 |
+
questions_db[topic].append(q)
|
| 111 |
+
added += 1
|
| 112 |
+
|
| 113 |
+
papers_db.append({
|
| 114 |
+
"id": paper_id,
|
| 115 |
+
"title": title,
|
| 116 |
+
"subject": subject,
|
| 117 |
+
"uploaded_at": datetime.now().strftime("%b %d, %Y"),
|
| 118 |
+
"questions": added
|
| 119 |
+
})
|
| 120 |
+
return f"Success: {added} questions added from **{title}**!", gr.update(value=list_papers())
|
| 121 |
except Exception as e:
|
| 122 |
+
return f"Error: {e}", gr.update()
|
| 123 |
+
|
| 124 |
+
# ---------- 6. Real Question Generator ----------
|
| 125 |
+
def get_real_question(subject, topic):
|
| 126 |
+
if topic not in questions_db or not questions_db[topic]:
|
| 127 |
+
return "No real questions yet. Ask admin to upload papers!", "", ""
|
| 128 |
+
|
| 129 |
+
import random
|
| 130 |
+
q = random.choice(questions_db[topic])
|
| 131 |
+
return (
|
| 132 |
+
f"**[{q['year'] or 'Past'} | {q['marks']} marks]**\n\n{q['text']}",
|
| 133 |
+
f"Expected: {q['type']} answer worth {q['marks']} marks.",
|
| 134 |
+
q["id"]
|
| 135 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
+
# ---------- 7. Answer Checker ----------
|
| 138 |
+
def check_real_answer(qid, user_answer, user_id):
|
| 139 |
if not user_answer.strip():
|
| 140 |
+
return "Type your answer!"
|
| 141 |
+
|
| 142 |
+
# Find question
|
| 143 |
+
question = None
|
| 144 |
+
for qs in questions_db.values():
|
| 145 |
+
for q in qs:
|
| 146 |
+
if q["id"] == qid:
|
| 147 |
+
question = q
|
| 148 |
+
break
|
| 149 |
+
if question: break
|
| 150 |
+
|
| 151 |
+
if not question:
|
| 152 |
+
return "Question not found."
|
| 153 |
+
|
| 154 |
+
prompt = f"""
|
| 155 |
+
IGCSE {question.get('type','')} Marking:
|
| 156 |
+
Question: {question['text']}
|
| 157 |
+
Marks: {question['marks']}
|
| 158 |
Student answer: {user_answer}
|
| 159 |
|
| 160 |
+
Reply JSON:
|
| 161 |
+
{{
|
| 162 |
+
"score": 0-{question['marks']},
|
| 163 |
+
"feedback": "Clear strengths and errors",
|
| 164 |
+
"band": "High/Mid/Low",
|
| 165 |
+
"improvement": "One key tip"
|
| 166 |
+
}}
|
| 167 |
+
"""
|
| 168 |
+
resp = client.chat.completions.create(
|
| 169 |
+
model=MODEL,
|
| 170 |
+
messages=[{"role": "user", "content": prompt}],
|
| 171 |
+
max_tokens=600
|
| 172 |
+
).choices[0].message.content.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
|
| 174 |
+
try:
|
| 175 |
+
fb = json.loads(resp.replace("```json", "").replace("```", ""))
|
| 176 |
+
score = fb["score"]
|
| 177 |
+
max_marks = question['marks']
|
| 178 |
+
percent = int(100 * score / max_marks)
|
| 179 |
+
|
| 180 |
+
# Update progress
|
| 181 |
+
if user_id not in user_progress:
|
| 182 |
+
user_progress[user_id] = {}
|
| 183 |
+
if question["topic"] not in user_progress[user_id]:
|
| 184 |
+
user_progress[user_id][question["topic"]] = {"correct": 0, "total": 0, "streak": 0}
|
| 185 |
+
|
| 186 |
+
prog = user_progress[user_id][question["topic"]]
|
| 187 |
+
prog["total"] += 1
|
| 188 |
+
if score >= max_marks * 0.7:
|
| 189 |
+
prog["correct"] += 1
|
| 190 |
+
prog["streak"] += 1
|
| 191 |
+
else:
|
| 192 |
+
prog["streak"] = 0
|
| 193 |
+
|
| 194 |
+
xp = 10 + (5 if prog["streak"] > 2 else 0)
|
| 195 |
+
streak_emoji = "Fire" if prog["streak"] > 2 else "Checkmark"
|
| 196 |
+
|
| 197 |
+
return f"""
|
| 198 |
+
**Score: {score}/{max_marks} ({percent}%)**
|
| 199 |
+
Band: **{fb['band']}**
|
| 200 |
+
|
| 201 |
+
**Feedback:**
|
| 202 |
+
{fb['feedback']}
|
| 203 |
+
|
| 204 |
+
**Improvement:**
|
| 205 |
+
{fb['improvement']}
|
| 206 |
+
|
| 207 |
+
**+{xp} XP** | Streak: {prog['streak']} {streak_emoji}
|
| 208 |
+
"""
|
| 209 |
+
except:
|
| 210 |
+
return resp
|
| 211 |
+
|
| 212 |
+
# ---------- 8. Dashboard ----------
|
| 213 |
+
def get_progress(user_id):
|
| 214 |
+
if not user_id or user_id not in user_progress:
|
| 215 |
+
return "Start practicing to see progress!"
|
| 216 |
+
lines = ["### Your Progress"]
|
| 217 |
+
for topic, data in user_progress[user_id].items():
|
| 218 |
+
acc = data["correct"]/data["total"] if data["total"] else 0
|
| 219 |
+
lines.append(f"- **{topic}**: {data['correct']}/{data['total']} ({acc:.0%}) | Streak: {data['streak']}")
|
| 220 |
+
return "\n".join(lines)
|
| 221 |
+
|
| 222 |
+
# ---------- 9. Admin List ----------
|
| 223 |
+
def list_papers():
|
| 224 |
+
if not papers_db:
|
| 225 |
+
return "No papers uploaded yet."
|
| 226 |
return "\n".join(
|
| 227 |
+
f"**{p['title']}** ({p['subject']}) – {p['questions']} questions – {p['uploaded_at']}"
|
| 228 |
+
for p in papers_db[-10:]
|
| 229 |
)
|
| 230 |
|
| 231 |
+
# ---------- 10. UI ----------
|
| 232 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="IGCSE Language Pro") as app:
|
| 233 |
+
gr.Markdown("""
|
| 234 |
+
# IGCSE Language Pro
|
| 235 |
+
**Real Past-Paper Questions • AI Tutor • Track Progress**
|
| 236 |
+
""")
|
| 237 |
+
user_id = gr.Textbox(label="Your Name/ID", placeholder="e.g. Alex2025", value="guest")
|
| 238 |
|
| 239 |
with gr.Tabs():
|
| 240 |
+
# STUDENT
|
| 241 |
+
with gr.Tab("Practice"):
|
| 242 |
+
gr.Markdown("### Real IGCSE Questions")
|
| 243 |
+
with gr.Row():
|
| 244 |
+
subj = gr.Dropdown(["French", "EFL"], label="Subject", value="French")
|
| 245 |
+
topic = gr.Dropdown(TOPICS["French"], label="Topic")
|
| 246 |
+
def update_topics(s):
|
| 247 |
+
return gr.Dropdown(choices=TOPICS[s], value=TOPICS[s][0])
|
| 248 |
+
subj.change(update_topics, subj, topic)
|
| 249 |
+
|
| 250 |
+
q_out = gr.Markdown()
|
| 251 |
+
exp = gr.Textbox(visible=False)
|
| 252 |
+
qid_hidden = gr.Textbox(visible=False)
|
| 253 |
+
ans = gr.Textbox(lines=6, label="Your Answer", placeholder="Write in full sentences...")
|
| 254 |
+
feedback = gr.Markdown()
|
| 255 |
+
|
| 256 |
+
gr.Button("Generate Real Question").click(
|
| 257 |
+
get_real_question, [subj, topic], [q_out, exp, qid_hidden]
|
| 258 |
+
)
|
| 259 |
+
gr.Button("Check Answer").click(
|
| 260 |
+
check_real_answer, [qid_hidden, ans, user_id], feedback
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
gr.Markdown("### Your Dashboard")
|
| 264 |
+
dash = gr.Markdown()
|
| 265 |
+
gr.Button("Refresh Progress").click(get_progress, user_id, dash)
|
| 266 |
+
|
| 267 |
+
with gr.Tab("AI Tutor"):
|
| 268 |
+
chatbot = gr.Chatbot(height=500)
|
| 269 |
+
msg = gr.Textbox(placeholder="Ask about passé composé, idioms, or essay structure...")
|
| 270 |
+
def tutor_resp(message, history):
|
| 271 |
+
system = f"You are a fun, expert IGCSE tutor. Use examples from real past papers."
|
| 272 |
+
resp = client.chat.completions.create(
|
| 273 |
+
model=MODEL,
|
| 274 |
+
messages=[{"role": "system", "content": system}] +
|
| 275 |
+
[{"role": "user" if i%2==0 else "assistant", "content": turn}
|
| 276 |
+
for pair in history for i, turn in enumerate(pair)] +
|
| 277 |
+
[{"role": "user", "content": message}],
|
| 278 |
+
max_tokens=800,
|
| 279 |
+
temperature=0.8
|
| 280 |
+
).choices[0].message.content
|
| 281 |
+
return history + [[message, resp]]
|
| 282 |
+
msg.submit(tutor_resp, [msg, chatbot], chatbot)
|
| 283 |
+
|
| 284 |
+
with gr.Tab("Dictionary & Translator"):
|
| 285 |
with gr.Tabs():
|
| 286 |
+
with gr.Tab("Translate"):
|
| 287 |
+
dir = gr.Radio(["EN to FR", "FR to EN"], value="EN to FR")
|
| 288 |
+
txt = gr.Textbox(lines=3)
|
| 289 |
+
out = gr.Textbox(lines=3)
|
| 290 |
+
gr.Button("Translate").click(
|
| 291 |
+
lambda t, d: client.translation(t, src_lang="en" if "EN" in d else "fr", tgt_lang="fr" if "EN" in d else "en").translation,
|
| 292 |
+
[txt, dir], out
|
| 293 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
with gr.Tab("Dictionary"):
|
| 295 |
+
word = gr.Textbox(placeholder="e.g. magnifique")
|
| 296 |
+
defn = gr.Markdown()
|
| 297 |
+
gr.Button("Lookup").click(
|
| 298 |
+
lambda w: client.text_generation(
|
| 299 |
+
f"French dictionary entry for '{w}':\n- Meaning\n- Gender\n- 2 sentences",
|
| 300 |
+
model=MODEL, max_new_tokens=400
|
| 301 |
+
), word, defn
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
# ADMIN
|
| 305 |
+
with gr.Tab("Admin Upload"):
|
| 306 |
+
gr.Markdown("### Upload Past Paper + Insert")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
with gr.Row():
|
| 308 |
+
title = gr.Textbox(label="Paper Title", placeholder="June 2023 Paper 2")
|
| 309 |
+
sub = gr.Radio(["French", "EFL"], label="Subject", value="French")
|
| 310 |
+
pdf = gr.File(label="Question Paper (PDF)", file_types=[".pdf"])
|
| 311 |
+
insert = gr.File(label="Insert/Listening Script (Optional)", file_types=[".pdf"])
|
| 312 |
+
status = gr.Markdown()
|
| 313 |
+
papers_list = gr.Markdown(value=list_papers())
|
| 314 |
+
|
| 315 |
+
gr.Button("Process Paper").click(
|
| 316 |
+
process_past_paper,
|
| 317 |
+
[title, sub, pdf, insert],
|
| 318 |
+
[status, papers_list]
|
| 319 |
+
)
|
| 320 |
|
| 321 |
gr.Markdown("""
|
| 322 |
---
|
| 323 |
+
**Deploy:** Fork → Add `HF_TOKEN` → Done!
|
| 324 |
+
**Tip:** Upload 2020–2024 papers → instant 1000+ real questions!
|
|
|
|
|
|
|
| 325 |
""")
|
| 326 |
|
| 327 |
+
app.launch(share=True)
|