Spaces:
Configuration error
Configuration error
Update app.py
Browse files123453 unmodified lines91011121314153 unmodified lines19202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411518 unmodified lines1341351361371381391401411421431441 unmodified line1461471481491501511524 unmodified lines1571581591601611621631645 unmodified lines17017117217317417517613 unmodified lines1901911921931941951966 unmodified lines2032042052062072082093 unmodified lines2132142152162172182192202212222232242252262272285 unmodified lines2342352362372382392407 unmodified lines24824925025125225325425525627 unmodified lines2842852862872882892902912922935 unmodified lines2993003013023033043053063073083093103113123133147 unmodified lines3223233243253263273283293303313322 unmodified lines33533633733833934034118 unmodified lines36036136236336436536636711 unmodified lines37938038138238338438538638738838914 unmodified lines4044054064074084094101 unmodified line41241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744826 unmodified lines47547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652710 unmodified lines5385395405415425435445455 unmodified lines5515525535545555565577 unmodified lines56556656756856957057128 unmodified lines6006016026036046056065 unmodified lines61261361461561661761861962062162262362462562662762862963063120 unmodified lines65265365465565665765865966066166266366466566666766866967067167267367467525 unmodified lines7017027037047057067072 unmodified lines71071171271371471571671710 unmodified lines72872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178234 unmodified lines81781881982082182282382482582682782882983083183283383483583683783883948 unmodified lines88888989089189289389489589615 unmodified lines9129139149159169179185 unmodified lines9249259269279289299309319329339349359369379389399409419429439449459466 unmodified lines9539549559569579589599609619629639649659669679689699709719729739749759769779789799809819828 unmodified lines99199299399499599699799899910001001100210031004100510061007100822 unmodified lines103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063"""SEA Prep AI Tutor - Complete Version for Hugging Face Spaces"""import gradio as grimport sqlite33 unmodified linesimport tempfilefrom datetime import datetimefrom typing import List, Optionalimport pandas as pd# Try to import PDF processortry:3 unmodified linesPDF_AVAILABLE = Falseprint("Note: Install pdfplumber in requirements.txt for PDF processing")# Database setup for Spacesclass DatabaseManager:def __init__(self):self.db_dir = "/tmp/database"os.makedirs(self.db_dir, exist_ok=True)self.init_databases()def init_databases(self):"""Initialize both databases"""# Questions databaseself.question_conn = sqlite3.connect(os.path.join(self.db_dir, "questions.db"))self.question_cursor = self.question_conn.cursor()# Create questions tableself.question_cursor.execute('''CREATE TABLE IF NOT EXISTS questions (id INTEGER PRIMARY KEY AUTOINCREMENT,subject TEXT,topic TEXT,question_text TEXT,question_type TEXT,difficulty INTEGER DEFAULT 3,marks INTEGER DEFAULT 1,options TEXT,answer TEXT,solution TEXT,source_paper TEXT,year INTEGER,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')# Create indexes for faster queriesself.question_cursor.execute('''CREATE INDEX IF NOT EXISTS idx_subject_topicON questions(subject, topic)''')# Add sample questions if emptyself.question_cursor.execute("SELECT COUNT(*) FROM questions")if self.question_cursor.fetchone()[0] == 0:self.add_sample_questions()self.question_conn.commit()# Student performance databaseself.student_conn = sqlite3.connect(os.path.join(self.db_dir, "students.db"))self.student_cursor = self.student_conn.cursor()self.student_cursor.execute('''CREATE TABLE IF NOT EXISTS student_performance (id INTEGER PRIMARY KEY AUTOINCREMENT,student_id TEXT DEFAULT 'default',question_id INTEGER,answered_correctly BOOLEAN,time_spent INTEGER DEFAULT 0,date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,confidence REAL DEFAULT 0.5)''')self.student_conn.commit()def add_sample_questions(self):"""Add sample SEA-style questions"""samples = [("Math", "Fractions", "Simplify the fraction 12/16 to its lowest terms.", "MCQ", 3,'{"A": "1/2", "B": "2/3", "C": "3/4", "D": "4/5"}', "C"),("Math", "Word Problems", "John has 24 marbles. He gives 1/3 to Sarah. How many marbles does John have left?", "Short Answer", 4, None, "16"),("Math", "Computation", "Calculate: 15 Γ 4 + 8 Γ· 2", "Short Answer", 4, None, "64"),("Language Arts", "Grammar", "Choose the correct sentence:", "MCQ", 2,'{"A": "He go to school.", "B": "He goes to school.", "C": "He going to school.", "D": "He gone to school."}', "B"),("Language Arts", "Vocabulary", "What is the synonym of 'happy'?", "MCQ", 1,'{"A": "Sad", "B": "Joyful", "C": "Angry", "D": "Tired"}', "B"),("Language Arts", "Comprehension", "Read the passage and answer: What was the main idea?", "Essay", 5, None, "The main idea was about friendship and loyalty.")]for subject, topic, text, qtype, difficulty, options, answer in samples:self.question_cursor.execute("""INSERT INTO questions(subject, topic, question_text, question_type, difficulty, options, answer)VALUES (?, ?, ?, ?, ?, ?, ?)""",(subject, topic, text, qtype, difficulty, options, answer))self.question_conn.commit()print(f"Added {len(samples)} sample questions")class SEATutorSystem:def __init__(self):self.db = DatabaseManager()self.subjects = {"Math": [18 unmodified linestry:text = ""with pdfplumber.open(file_path) as pdf:for page in pdf.pages[:10]: # Limit to first 10 pages for performancepage_text = page.extract_text()if page_text:text += page_text + "\n"return text[:10000] # Limit to 10k charactersexcept Exception as e:return f"Error extracting PDF: {str(e)}"1 unmodified line"""Analyze text and extract potential questions"""questions = []# Split by common question patternslines = text.split('\n')current_question = ""4 unmodified lines# Check for question indicatorsif (re.match(r'^\d+[\.\)]\s', line) orre.match(r'^Q\d+', line, re.IGNORECASE) orre.match(r'^Question\s+\d+', line, re.IGNORECASE)):if current_question and len(current_question) > 20:questions.append(self.process_question(current_question, subject))5 unmodified linesif current_question and len(current_question) > 20:questions.append(self.process_question(current_question, subject))return questions[:20] # Limit to 20 questionsdef process_question(self, text: str, subject: str) -> dict:"""Process a single question text"""13 unmodified linesoptions = self.extract_mcq_options(text)return {"text": text[:300], # Limit length"topic": topic,"type": q_type,"difficulty": difficulty,6 unmodified linestext_lower = text.lower()if subject == "Math":if any(word in text_lower for word in ["fraction", "numerator", "denominator"]):return "Fractions"elif any(word in text_lower for word in ["area", "perimeter", "volume", "shape", "circle", "triangle"]):return "Geometry"3 unmodified linesreturn "Computation"elif any(word in text_lower for word in ["word", "problem", "story", "how many", "total"]):return "Word Problems"elif subject == "Language Arts":if any(word in text_lower for word in ["comprehension", "passage", "read"]):return "Comprehension"elif any(word in text_lower for word in ["grammar", "sentence", "verb", "noun", "adjective"]):return "Grammar"elif any(word in text_lower for word in ["spell", "correct spelling"]):return "Spelling"elif any(word in text_lower for word in ["essay", "write", "paragraph"]):return "Essay Writing"return "General"5 unmodified linesreturn "MCQ"elif any(word in text_lower for word in ["explain", "describe", "why", "how"]):return "Short Answer"elif any(word in text_lower for word in ["write", "essay", "composition"]):return "Essay"elif any(word in text_lower for word in ["solve", "calculate", "find", "compute"]):return "Problem Solving"7 unmodified linesif subject == "Math":# Count numbers and operationsnumbers = len(re.findall(r'\d+', text))operations = len(re.findall(r'[+\-ΓΓ·=]', text))if numbers > 3 and operations > 1:return min(5, 3 + (word_count // 30))elif numbers > 1:return min(4, 2 + (word_count // 50))27 unmodified linesdef store_questions(self, questions: List[dict], year: int) -> int:"""Store extracted questions in database"""count = 0for q in questions:try:self.db.question_cursor.execute('''INSERT INTO questions(subject, topic, question_text, question_type, difficulty, options, source_paper, year)VALUES (?, ?, ?, ?, ?, ?, ?, ?)5 unmodified linesexcept Exception as e:print(f"Error storing question: {e}")self.db.question_conn.commit()return countdef get_question_count(self) -> int:"""Get total number of questions"""self.db.question_cursor.execute("SELECT COUNT(*) FROM questions")return self.db.question_cursor.fetchone()[0]def get_questions(self, subject: Optional[str] = None, topic: Optional[str] = None, limit: int = 10) -> List[dict]:"""Retrieve questions with filters"""query = "SELECT id, subject, topic, question_text, question_type, difficulty, options FROM questions"params = []7 unmodified linesquery += " ORDER BY RANDOM() LIMIT ?"params.append(limit)self.db.question_cursor.execute(query, params)rows = self.db.question_cursor.fetchall()questions = []for row in rows:questions.append({"id": row[0],"subject": row[1],2 unmodified lines"type": row[4],"difficulty": row[5],"difficulty_label": self.difficulty_labels.get(row[5], "Medium"),"options": json.loads(row[6]) if row[6] else None})return questions18 unmodified linesdef grade_answer(self, question_id: int, student_answer: str, student_id: str = "default") -> dict:"""Grade a student's answer"""# Get correct answer from databaseself.db.question_cursor.execute("SELECT answer FROM questions WHERE id = ?", (question_id,))result = self.db.question_cursor.fetchone()if not result or not result[0]:return {11 unmodified linesscore = 1 if is_correct else 0# Store performanceself.db.student_cursor.execute('''INSERT INTO student_performance (student_id, question_id, answered_correctly)VALUES (?, ?, ?)''', (student_id, question_id, is_correct))self.db.student_conn.commit()# Generate feedbackfeedback = self.generate_feedback(is_correct, correct_answer)14 unmodified linesdef get_student_progress(self, student_id: str = "default") -> dict:"""Get student progress summary"""self.db.student_cursor.execute('''SELECTCOUNT(*) as total_attempts,SUM(CASE WHEN answered_correctly = 1 THEN 1 ELSE 0 END) as correct_answers1 unmodified lineWHERE student_id = ?''', (student_id,))total, correct = self.db.student_cursor.fetchone() or (0, 0)accuracy = (correct / total * 100) if total > 0 else 0# Get topic-wise performanceself.db.student_cursor.execute('''SELECT q.topic,COUNT(*) as attempts,SUM(CASE WHEN sp.answered_correctly = 1 THEN 1 ELSE 0 END) as correctFROM student_performance spJOIN questions q ON sp.question_id = q.idWHERE sp.student_id = ?GROUP BY q.topicORDER BY correct * 1.0 / NULLIF(attempts, 0) ASCLIMIT 3''', (student_id,))weak_topics = []for topic, attempts, correct_count in self.db.student_cursor.fetchall():if attempts > 2: # Only consider topics with sufficient attemptstopic_accuracy = (correct_count / attempts * 100) if attempts > 0 else 0if topic_accuracy < 60:weak_topics.append(f"{topic} ({topic_accuracy:.0f}%)")return {"student_id": student_id,"total_attempts": total,"correct_answers": correct,"accuracy": round(accuracy, 1),"progress_level": self.get_progress_level(accuracy),"weak_areas": weak_topics[:3] if weak_topics else ["None identified yet"],"recommendation": self.get_recommendation(accuracy, total)}26 unmodified lines# Create Gradio Interfacedef create_interface():css = """.header {text-align: center;padding: 20px;background: linear-gradient(135deg, #1e3c72, #2a5298);color: white;border-radius: 10px;margin-bottom: 20px;}.subject-card {padding: 15px;border-radius: 10px;background: #f8f9fa;margin: 10px 0;border-left: 4px solid #2a5298;}.progress-card {padding: 15px;border-radius: 10px;background: #e8f4fd;margin: 10px 0;}.btn-primary {background: #2a5298 !important;color: white !important;}"""with gr.Blocks(title="SEA Prep AI Tutor πΉπΉ") as app:# Headergr.HTML("""<div class="header"><h1 style="margin: 0;">πΉπΉ SEA Prep AI Tutor</h1><p style="margin: 5px 0 0 0; font-size: 1.1em;">Secondary Entrance Assessment Preparation Platform</p><p style="margin: 5px 0 0 0; opacity: 0.9;">Mathematics β’ Language Arts</p></div>""")# Session state for current testcurrent_test = gr.State([])current_question_index = gr.State(0)# Main tabswith gr.Tabs():# Home Tabwith gr.Tab("π Home", id="home"):with gr.Row():with gr.Column(scale=2):gr.Markdown("""10 unmodified lines""")with gr.Row():quick_math = gr.Button("π Start Math Practice", size="lg")quick_english = gr.Button("π Start English Practice", size="lg")with gr.Column(scale=1):gr.Markdown("### π Quick Stats")5 unmodified linesprogress = sea_tutor.get_student_progress()return f"""<div class="progress-card"><p><strong>Questions in Bank:</strong> {total_q}</p><p><strong>Your Attempts:</strong> {progress['total_attempts']}</p><p><strong>Accuracy:</strong> {progress['accuracy']}%</p>7 unmodified linesapp.load(update_stats, outputs=stats_card)# Upload Tabwith gr.Tab("π€ Upload Papers", id="upload"):gr.Markdown("### Upload SEA Past Papers")gr.Markdown("Upload PDF files of past SEA papers to build your question bank.")28 unmodified lines""")with gr.Column():upload_status = gr.JSON(label="Upload Status", visible=False)upload_output = gr.Markdown(label="Results")gr.Markdown("### π Extracted Questions Preview")5 unmodified linesdef process_upload(file_path, subject, year):if not file_path:return {"error": "Please select a file"}, "β No file selected", []try:# Extract texttext = sea_tutor.extract_text_from_pdf(file_path)if text.startswith("Error") or text.startswith("PDF processing"):return {"error": text}, f"β οΈ {text}", []# Analyze for questionsquestions = sea_tutor.analyze_text_for_questions(text, subject, year)if not questions:return {"warning": "No questions found"}, "β οΈ No questions could be extracted from this PDF.", []# Store questionsstored_count = sea_tutor.store_questions(questions, year)20 unmodified linesYou can now use these questions for practice tests!"""return {"status": "success","file": os.path.basename(file_path),"questions_found": len(questions),"questions_stored": stored_count}, result_msg, preview_dataexcept Exception as e:return {"error": str(e)}, f"β Error: {str(e)}", []upload_btn.click(process_upload,inputs=[pdf_input, subject_select, year_select],outputs=[upload_status, upload_output, questions_preview])# Practice Tabwith gr.Tab("π― Practice", id="practice"):gr.Markdown("### Practice Tests")gr.Markdown("Generate custom practice tests based on your needs.")25 unmodified linesquestion_count = gr.Slider(minimum=5,maximum=30,value=10,step=5,label="Number of Questions"2 unmodified linesgenerate_btn = gr.Button("π Generate Test", variant="primary")with gr.Column(scale=2):test_output = gr.JSON(label="Generated Test", visible=False)gr.Markdown("### π Test Paper")test_display = gr.HTML()10 unmodified lineswith gr.Row():next_btn = gr.Button("β‘οΈ Next Question")finish_btn = gr.Button("π Finish Test")# Test taking statecurrent_question_data = gr.State({})def generate_test(subject, topics, count):test = sea_tutor.generate_practice_test(subject, topics, count)if not test["questions"]:html = "<div style='color: red; padding: 20px;'>No questions available. Please upload some papers first.</div>"return test, html, {}, 0, []# Store test for sessionquestions_list = test["questions"]# Display first questionhtml = f"""<div style='padding: 20px; background: #f8f9fa; border-radius: 10px;'><h3>{test['title']}</h3><p><strong>Date:</strong> {test['date']}</p><p><strong>Time:</strong> {test['total_time']}</p><p><strong>Instructions:</strong> {test['instructions']}</p><hr><h4>Question 1 of {len(questions_list)}</h4><div style='background: white; padding: 15px; border-radius: 5px; margin: 10px 0;'>{questions_list[0]['text']}</div></div>"""return test, html, questions_list[0], 0, questions_listdef display_question(questions, index):if index >= len(questions):return "Test completed!", {}, index, questionsq = questions[index]html = f"""<div style='padding: 20px; background: #f8f9fa; border-radius: 10px;'><h4>Question {index + 1} of {len(questions)}</h4><div style='background: white; padding: 15px; border-radius: 5px; margin: 10px 0;'>{q['text']}</div><p><strong>Type:</strong> {q['type']} | <strong>Difficulty:</strong> {q['difficulty_label']}</p></div>"""return html, q, index, questionsdef submit_answer(answer, current_q, q_index, questions):if not current_q:34 unmodified linesgenerate_btn.click(generate_test,inputs=[practice_subject, topic_selector, question_count],outputs=[test_output, test_display, current_question_data, current_question_index, current_test])submit_btn.click(submit_answer,inputs=[answer_input, current_question_data, current_question_index, current_test],outputs=[feedback_display, test_display, current_question_data, current_question_index, current_test, answer_input])next_btn.click(display_question,inputs=[current_test, current_question_index],outputs=[test_display, current_question_data, current_question_index, current_test])# Progress Tabwith gr.Tab("π Progress", id="progress"):gr.Markdown("### Your Learning Progress")gr.Markdown("Track your performance and get personalized recommendations.")48 unmodified lines{progress['recommendation']}**Areas to focus on:**{', '.join(progress['weak_areas'])}**Next Steps:**1. Complete daily practice sessions2. Review incorrect answers15 unmodified lines)# Question Bank Tabwith gr.Tab("π Question Bank", id="bank"):gr.Markdown("### Browse Question Bank")gr.Markdown("View and search through all available questions.")5 unmodified linesvalue="All")search_topic = gr.Dropdown(label="Filter by Topic",choices=["All"] + sea_tutor.subjects["Math"] + sea_tutor.subjects["Language Arts"],value="All")search_type = gr.Dropdown(label="Filter by Type",choices=["All", "MCQ", "Short Answer", "Essay", "Problem Solving"],value="All")search_limit = gr.Slider(label="Number of Questions",minimum=5,maximum=50,value=15,step=5)6 unmodified lineswrap=True,datatype=["str", "str", "str", "str", "str", "str"])total_found = gr.Markdown("**Total found:** 0")def search_questions(subject, topic, qtype, limit):# Get all questionsall_questions = sea_tutor.get_questions(None, None, 1000) # Large limit# Apply filtersfiltered = []for q in all_questions:if subject != "All" and q["subject"] != subject:continueif topic != "All" and q["topic"] != topic:continueif qtype != "All" and q["type"] != qtype:continuefiltered.append(q)# Apply limitfiltered = filtered[:limit]# Prepare table datatable_data = []for q in filtered:# Truncate long questionsquestion_text = q["text"]if len(question_text) > 80:8 unmodified linesq["difficulty_label"]])return table_data, f"**Total found:** {len(filtered)}"search_btn.click(search_questions,inputs=[search_subject, search_topic, search_type, search_limit],outputs=[questions_table, total_found])# Load initial dataapp.load(lambda: search_questions("All", "All", "All", 15),outputs=[questions_table, total_found])# Footer22 unmodified linesserver_name="0.0.0.0",server_port=7860,share=False,debug=False,show_error=True,css=""".header {text-align: center;padding: 20px;background: linear-gradient(135deg, #1e3c72, #2a5298);color: white;border-radius: 10px;margin-bottom: 20px;}.subject-card {padding: 15px;border-radius: 10px;background: #f8f9fa;margin: 10px 0;border-left: 4px solid #2a5298;}.progress-card {padding: 15px;border-radius: 10px;background: #e8f4fd;margin: 10px 0;}.btn-primary {background: #2a5298 !important;color: white !important;}""")123453 unmodified lines91011121314151617183 unmodified lines22232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711818 unmodified lines1371381391401411421431441451461471 unmodified line1491501511521531541554 unmodified lines1601611621631641651665 unmodified lines17217317417517617717813 unmodified lines1921931941951961971986 unmodified lines2052062072082092102113 unmodified lines2152162172182192202212222232242252262272282292302312322332342352365 unmodified lines2422432442452462472487 unmodified lines25625725825926026126226327 unmodified lines2912922932942952962972982993003013023035 unmodified lines3093103113123133143153163173183193203213223233243253263273283297 unmodified lines3373383393403413423433443453463473483493503513522 unmodified lines35535635735835936036118 unmodified lines38038138238338438538638738838911 unmodified lines40140240340440540640740840941041141241314 unmodified lines4284294304314324334344354364371 unmodified line43944044144244344444544644744844945045145245345426 unmodified lines48148248348448548648748848949049149249349449549649749849950050110 unmodified lines5125135145155165175185195 unmodified lines5255265275285295305317 unmodified lines53954054154254354454528 unmodified lines5745755765775785795 unmodified lines58558658758858959059159259359459559659759859960060160260360420 unmodified lines62562662762862963063163263363463563663763863964064164264325 unmodified lines6696706716726736746752 unmodified lines67867968068168268310 unmodified lines69469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472534 unmodified lines76076176276376476576676776876977077177277377477577648 unmodified lines82582682782882983015 unmodified lines8468478488498508518525 unmodified lines8588598608618628638648658668678686 unmodified lines8758768778788798808818828838848858868878888 unmodified lines89789889990090190290390490590690790890991091191291391422 unmodified lines937938939940941"""SEA Prep AI Tutor - Thread-Safe Version for Hugging Face Spaces"""import gradio as grimport sqlite33 unmodified linesimport tempfilefrom datetime import datetimefrom typing import List, Optionalimport threading# Thread-local storage for database connectionsthread_local = threading.local()# Try to import PDF processortry:3 unmodified linesPDF_AVAILABLE = Falseprint("Note: Install pdfplumber in requirements.txt for PDF processing")def get_db_connection(db_name="questions"):"""Get thread-local database connection"""if not hasattr(thread_local, 'connections'):thread_local.connections = {}if db_name not in thread_local.connections:db_dir = "/tmp/database"os.makedirs(db_dir, exist_ok=True)if db_name == "questions":conn = sqlite3.connect(os.path.join(db_dir, "questions.db"), check_same_thread=False)else:conn = sqlite3.connect(os.path.join(db_dir, "students.db"), check_same_thread=False)thread_local.connections[db_name] = connreturn thread_local.connections[db_name]def init_databases():"""Initialize databases (call once at startup)"""question_conn = get_db_connection("questions")student_conn = get_db_connection("students")# Questions tablequestion_cursor = question_conn.cursor()question_cursor.execute('''CREATE TABLE IF NOT EXISTS questions (id INTEGER PRIMARY KEY AUTOINCREMENT,subject TEXT,topic TEXT,question_text TEXT,question_type TEXT,difficulty INTEGER DEFAULT 3,marks INTEGER DEFAULT 1,options TEXT,answer TEXT,solution TEXT,source_paper TEXT,year INTEGER,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')# Add sample questions if emptyquestion_cursor.execute("SELECT COUNT(*) FROM questions")if question_cursor.fetchone()[0] == 0:add_sample_questions(question_cursor)question_conn.commit()# Student performance tablestudent_cursor = student_conn.cursor()student_cursor.execute('''CREATE TABLE IF NOT EXISTS student_performance (id INTEGER PRIMARY KEY AUTOINCREMENT,student_id TEXT DEFAULT 'default',question_id INTEGER,answered_correctly BOOLEAN,time_spent INTEGER DEFAULT 0,date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,confidence REAL DEFAULT 0.5)''')student_conn.commit()def add_sample_questions(cursor):"""Add sample SEA-style questions"""samples = [("Math", "Fractions", "Simplify the fraction 12/16 to its lowest terms.", "MCQ", 3,'{"A": "1/2", "B": "2/3", "C": "3/4", "D": "4/5"}', "C"),("Math", "Word Problems", "John has 24 marbles. He gives 1/3 to Sarah. How many marbles does John have left?", "Short Answer", 4, None, "16"),("Math", "Computation", "Calculate: 15 Γ 4 + 8 Γ· 2", "Short Answer", 4, None, "64"),("Language Arts", "Grammar", "Choose the correct sentence:", "MCQ", 2,'{"A": "He go to school.", "B": "He goes to school.", "C": "He going to school.", "D": "He gone to school."}', "B"),("Language Arts", "Vocabulary", "What is the synonym of 'happy'?", "MCQ", 1,'{"A": "Sad", "B": "Joyful", "C": "Angry", "D": "Tired"}', "B"),("Language Arts", "Comprehension", "Read the passage and answer: What was the main idea?", "Essay", 5, None, "The main idea was about friendship and loyalty.")]for subject, topic, text, qtype, difficulty, options, answer in samples:cursor.execute("""INSERT INTO questions(subject, topic, question_text, question_type, difficulty, options, answer)VALUES (?, ?, ?, ?, ?, ?, ?)""",(subject, topic, text, qtype, difficulty, options, answer))class SEATutorSystem:def __init__(self):# Initialize databasesinit_databases()self.subjects = {"Math": [18 unmodified linestry:text = ""with pdfplumber.open(file_path) as pdf:for page in pdf.pages[:5]: # Limit to first 5 pages for performancepage_text = page.extract_text()if page_text:text += page_text + "\n"return text[:5000] # Limit to 5k charactersexcept Exception as e:return f"Error extracting PDF: {str(e)}"1 unmodified line"""Analyze text and extract potential questions"""questions = []# Simple extraction - split by numbers followed by dot or parenthesislines = text.split('\n')current_question = ""4 unmodified lines# Check for question indicatorsif (re.match(r'^\d+[\.\)]\s', line) orre.match(r'^[IVXivx]+[\.\)]\s', line)):if current_question and len(current_question) > 20:questions.append(self.process_question(current_question, subject))5 unmodified linesif current_question and len(current_question) > 20:questions.append(self.process_question(current_question, subject))return questions[:15] # Limit to 15 questionsdef process_question(self, text: str, subject: str) -> dict:"""Process a single question text"""13 unmodified linesoptions = self.extract_mcq_options(text)return {"text": text[:250], # Limit length"topic": topic,"type": q_type,"difficulty": difficulty,6 unmodified linestext_lower = text.lower()if subject == "Math":if any(word in text_lower for word in ["fraction", "simplify", "numerator", "denominator"]):return "Fractions"elif any(word in text_lower for word in ["area", "perimeter", "volume", "shape", "circle", "triangle"]):return "Geometry"3 unmodified linesreturn "Computation"elif any(word in text_lower for word in ["word", "problem", "story", "how many", "total"]):return "Word Problems"else:return "Number Concepts"elif subject == "Language Arts":if any(word in text_lower for word in ["comprehension", "passage", "read", "paragraph"]):return "Comprehension"elif any(word in text_lower for word in ["grammar", "sentence", "verb", "noun", "adjective"]):return "Grammar"elif any(word in text_lower for word in ["spell", "correct spelling"]):return "Spelling"elif any(word in text_lower for word in ["essay", "write", "composition", "paragraph"]):return "Essay Writing"elif any(word in text_lower for word in ["vocabulary", "synonym", "antonym", "meaning"]):return "Vocabulary"else:return "General"return "General"5 unmodified linesreturn "MCQ"elif any(word in text_lower for word in ["explain", "describe", "why", "how"]):return "Short Answer"elif any(word in text_lower for word in ["write", "essay", "composition", "letter"]):return "Essay"elif any(word in text_lower for word in ["solve", "calculate", "find", "compute"]):return "Problem Solving"7 unmodified linesif subject == "Math":# Count numbers and operationsnumbers = len(re.findall(r'\d+', text))if numbers > 3:return min(5, 3 + (word_count // 30))elif numbers > 1:return min(4, 2 + (word_count // 50))27 unmodified linesdef store_questions(self, questions: List[dict], year: int) -> int:"""Store extracted questions in database"""conn = get_db_connection("questions")cursor = conn.cursor()count = 0for q in questions:try:cursor.execute('''INSERT INTO questions(subject, topic, question_text, question_type, difficulty, options, source_paper, year)VALUES (?, ?, ?, ?, ?, ?, ?, ?)5 unmodified linesexcept Exception as e:print(f"Error storing question: {e}")conn.commit()return countdef get_question_count(self) -> int:"""Get total number of questions"""conn = get_db_connection("questions")cursor = conn.cursor()cursor.execute("SELECT COUNT(*) FROM questions")return cursor.fetchone()[0]def get_questions(self, subject: Optional[str] = None, topic: Optional[str] = None, limit: int = 10) -> List[dict]:"""Retrieve questions with filters"""conn = get_db_connection("questions")cursor = conn.cursor()query = "SELECT id, subject, topic, question_text, question_type, difficulty, options FROM questions"params = []7 unmodified linesquery += " ORDER BY RANDOM() LIMIT ?"params.append(limit)cursor.execute(query, params)rows = cursor.fetchall()questions = []for row in rows:try:options = json.loads(row[6]) if row[6] else Noneexcept:options = Nonequestions.append({"id": row[0],"subject": row[1],2 unmodified lines"type": row[4],"difficulty": row[5],"difficulty_label": self.difficulty_labels.get(row[5], "Medium"),"options": options})return questions18 unmodified linesdef grade_answer(self, question_id: int, student_answer: str, student_id: str = "default") -> dict:"""Grade a student's answer"""# Get correct answer from databaseconn = get_db_connection("questions")cursor = conn.cursor()cursor.execute("SELECT answer FROM questions WHERE id = ?", (question_id,))result = cursor.fetchone()if not result or not result[0]:return {11 unmodified linesscore = 1 if is_correct else 0# Store performancestudent_conn = get_db_connection("students")student_cursor = student_conn.cursor()student_cursor.execute('''INSERT INTO student_performance (student_id, question_id, answered_correctly)VALUES (?, ?, ?)''', (student_id, question_id, is_correct))student_conn.commit()# Generate feedbackfeedback = self.generate_feedback(is_correct, correct_answer)14 unmodified linesdef get_student_progress(self, student_id: str = "default") -> dict:"""Get student progress summary"""conn = get_db_connection("students")cursor = conn.cursor()cursor.execute('''SELECTCOUNT(*) as total_attempts,SUM(CASE WHEN answered_correctly = 1 THEN 1 ELSE 0 END) as correct_answers1 unmodified lineWHERE student_id = ?''', (student_id,))total, correct = cursor.fetchone() or (0, 0)accuracy = (correct / total * 100) if total > 0 else 0return {"student_id": student_id,"total_attempts": total,"correct_answers": correct,"accuracy": round(accuracy, 1),"progress_level": self.get_progress_level(accuracy),"recommendation": self.get_recommendation(accuracy, total)}26 unmodified lines# Create Gradio Interfacedef create_interface():with gr.Blocks(title="SEA Prep AI Tutor πΉπΉ") as app:# Headergr.HTML("""<div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #1e3c72, #2a5298); color: white; border-radius: 10px; margin-bottom: 20px;"><h1 style="margin: 0;">πΉπΉ SEA Prep AI Tutor</h1><p style="margin: 5px 0 0 0; font-size: 1.1em;">Secondary Entrance Assessment Preparation Platform</p><p style="margin: 5px 0 0 0; opacity: 0.9;">Mathematics β’ Language Arts</p></div>""")# Main tabswith gr.Tabs():# Home Tabwith gr.Tab("π Home"):with gr.Row():with gr.Column(scale=2):gr.Markdown("""10 unmodified lines""")with gr.Row():gr.Button("π Start Math Practice", size="lg")gr.Button("π Start English Practice", size="lg")with gr.Column(scale=1):gr.Markdown("### π Quick Stats")5 unmodified linesprogress = sea_tutor.get_student_progress()return f"""<div style='padding: 15px; border-radius: 10px; background: #e8f4fd; margin: 10px 0;'><p><strong>Questions in Bank:</strong> {total_q}</p><p><strong>Your Attempts:</strong> {progress['total_attempts']}</p><p><strong>Accuracy:</strong> {progress['accuracy']}%</p>7 unmodified linesapp.load(update_stats, outputs=stats_card)# Upload Tabwith gr.Tab("π€ Upload Papers"):gr.Markdown("### Upload SEA Past Papers")gr.Markdown("Upload PDF files of past SEA papers to build your question bank.")28 unmodified lines""")with gr.Column():upload_output = gr.Markdown(label="Results")gr.Markdown("### π Extracted Questions Preview")5 unmodified linesdef process_upload(file_path, subject, year):if not file_path:return "β No file selected", []try:# Extract texttext = sea_tutor.extract_text_from_pdf(file_path)if text.startswith("Error") or text.startswith("PDF processing"):return f"β οΈ {text}", []# Analyze for questionsquestions = sea_tutor.analyze_text_for_questions(text, subject, year)if not questions:return "β οΈ No questions could be extracted from this PDF.", []# Store questionsstored_count = sea_tutor.store_questions(questions, year)20 unmodified linesYou can now use these questions for practice tests!"""return result_msg, preview_dataexcept Exception as e:return f"β Error: {str(e)}", []upload_btn.click(process_upload,inputs=[pdf_input, subject_select, year_select],outputs=[upload_output, questions_preview])# Practice Tabwith gr.Tab("π― Practice"):gr.Markdown("### Practice Tests")gr.Markdown("Generate custom practice tests based on your needs.")25 unmodified linesquestion_count = gr.Slider(minimum=5,maximum=20,value=10,step=5,label="Number of Questions"2 unmodified linesgenerate_btn = gr.Button("π Generate Test", variant="primary")with gr.Column(scale=2):gr.Markdown("### π Test Paper")test_display = gr.HTML()10 unmodified lineswith gr.Row():next_btn = gr.Button("β‘οΈ Next Question")# Test statecurrent_test_state = gr.State([])current_index_state = gr.State(0)current_question_state = gr.State({})def generate_test(subject, topics, count):test = sea_tutor.generate_practice_test(subject, topics, count)if not test["questions"]:html = "<div style='color: red; padding: 20px;'>No questions available. Please upload some papers first.</div>"return html, {}, 0, []# Display first questionfirst_q = test["questions"][0]html = f"""<div style='padding: 20px; background: #f8f9fa; border-radius: 10px;'><h4>Question 1 of {len(test['questions'])}</h4><div style='background: white; padding: 15px; border-radius: 5px; margin: 10px 0;'>{first_q['text']}</div><p><strong>Type:</strong> {first_q['type']} | <strong>Difficulty:</strong> {first_q['difficulty_label']}</p></div>"""return html, first_q, 0, test["questions"]def submit_answer(answer, current_q, q_index, questions):if not current_q:34 unmodified linesgenerate_btn.click(generate_test,inputs=[practice_subject, topic_selector, question_count],outputs=[test_display, current_question_state, current_index_state, current_test_state])submit_btn.click(submit_answer,inputs=[answer_input, current_question_state, current_index_state, current_test_state],outputs=[feedback_display, test_display, current_question_state, current_index_state, current_test_state, answer_input])# Progress Tabwith gr.Tab("π Progress"):gr.Markdown("### Your Learning Progress")gr.Markdown("Track your performance and get personalized recommendations.")48 unmodified lines{progress['recommendation']}**Next Steps:**1. Complete daily practice sessions2. Review incorrect answers15 unmodified lines)# Question Bank Tabwith gr.Tab("π Question Bank"):gr.Markdown("### Browse Question Bank")gr.Markdown("View and search through all available questions.")5 unmodified linesvalue="All")search_limit = gr.Slider(label="Number of Questions",minimum=5,maximum=30,value=10,step=5)6 unmodified lineswrap=True,datatype=["str", "str", "str", "str", "str", "str"])def search_questions(subject, limit):# Get questionsquestions = sea_tutor.get_questions(subject if subject != "All" else None, None, limit)# Prepare table datatable_data = []for q in questions:# Truncate long questionsquestion_text = q["text"]if len(question_text) > 80:8 unmodified linesq["difficulty_label"]])return table_datasearch_btn.click(search_questions,inputs=[search_subject, search_limit],outputs=questions_table)# Load initial dataapp.load(lambda: search_questions("All", 10),outputs=questions_table)# Footer22 unmodified linesserver_name="0.0.0.0",server_port=7860,share=False,debug=False)
app.py+180-302