Turbiling commited on
Commit
2af9690
·
verified ·
1 Parent(s): 5835efa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +212 -135
app.py CHANGED
@@ -1,148 +1,225 @@
1
- import os
2
  import gradio as gr
3
- from datetime import datetime
4
  from docx import Document
5
- from docx.shared import Pt, Inches
6
- from docx.enum.text import WD_ALIGN_PARAGRAPH
7
-
8
- # -------------------------
9
- # Grades and Difficulty
10
- # -------------------------
11
- grades = [f"Grade {i}" for i in range(1, 13)]
12
- difficulty_levels = ["Pretest (Beginner)", "Intermediate", "Advanced"]
13
- min_mcq, max_mcq = 5, 50
14
-
15
- # -------------------------
16
- # Subjects and Chapters
17
- # Use full dictionary for grades 1-12
18
- # -------------------------
19
- chapters_by_subject_and_grade = {
20
- # ----------------- Grades 1-8 (example) -----------------
21
- "Grade 1": {
22
- "Mathematics": ["Counting & Number Recognition", "Basic Addition", "Basic Subtraction", "Shapes & Space", "Measurement (Length, Weight)"],
23
- "English": ["Alphabet & Phonics", "Listening & Speaking", "Basic Vocabulary", "Simple Sentences", "Early Reading"],
24
- "Urdu": ["حروف اور آوازیں", "الفاظ", "سادہ جملے", "پڑھائی کا تعارف", "چھوٹی کہانیاں"],
25
- "Islamiyat": ["Iman Basics", "Prophets' Stories (selected)", "Good Manners", "Simple Prayers & Worship"],
26
- "General Knowledge": ["My Home & Family", "Plants & Animals", "Seasons & Weather", "My School"]
27
- },
28
- "Grade 2": {
29
- "Mathematics": ["Place Value", "Addition & Subtraction Facts", "Money", "Time (clock)", "Basic Shapes"],
30
- "English": ["Reading Short Texts", "Simple Grammar (nouns, verbs)", "Vocabulary Building", "Speaking Activities"],
31
- "Urdu": ["روزمرہ الفاظ", "مختصر کہانیاں", "قرأتِ آسان"],
32
- "Islamiyat": ["Stories of Prophets", "Good Deeds", "Worship Basics"],
33
- "General Knowledge": ["Local Community", "Transportation & Safety", "Plants & Animals"]
34
- },
35
- # ... add all remaining grades 3-12 using your previous dictionary
36
  }
37
 
38
- # -------------------------
39
- # Dummy MCQ generator (replace with actual AI API)
40
- # -------------------------
41
- def generate_mcqs(grade, subject, chapter, difficulty, num_questions):
42
- mcqs = [f"Sample question {i} for {subject} chapter {chapter}" for i in range(1, num_questions+1)]
43
- options_list = [["Option A", "Option B", "Option C", "Option D"] for _ in mcqs]
44
- answers = ["A"] * num_questions
45
- return mcqs, options_list, answers
46
-
47
- # -------------------------
48
- # Export to Word
49
- # -------------------------
50
- def export_to_word(mcqs, options_list, answers, grade, subject, chapter, difficulty):
51
- doc = Document()
52
- style = doc.styles['Normal']
53
- style.font.name = 'Times New Roman'
54
- style.font.size = Pt(12)
55
-
56
- # Heading
57
- heading = doc.add_paragraph("MONTHLY/WEEKLY TEST")
58
- heading.alignment = WD_ALIGN_PARAGRAPH.CENTER
59
- heading.runs[0].bold = True
60
- heading.runs[0].font.size = Pt(16)
61
-
62
- doc.add_paragraph() # empty line
63
-
64
- # Info Table
65
- table = doc.add_table(rows=6, cols=2)
66
- table.style = 'Table Grid'
67
- info = [
68
- ("Grade", grade), ("Subject", subject), ("Chapter", chapter),
69
- ("Difficulty", difficulty), ("Number of Questions", str(len(mcqs))),
70
- ("Date", datetime.now().strftime("%d-%m-%Y"))
71
- ]
72
- for row, (label, value) in zip(table.rows, info):
73
- row.cells[0].text = label
74
- row.cells[1].text = value
75
- row.cells[0].paragraphs[0].runs[0].bold = True
76
-
77
- doc.add_paragraph() # empty line
78
-
79
- # MCQs
80
- for i, (q, opts) in enumerate(zip(mcqs, options_list), start=1):
81
- doc.add_paragraph(f"{i}. {q}")
82
- for letter, text in zip(["A","B","C","D"], opts):
83
- p = doc.add_paragraph(f"{letter}. {text}")
84
- p.paragraph_format.left_indent = Inches(0.25)
85
-
86
- doc.add_paragraph() # empty line
87
-
88
- # Answer Key
89
- doc.add_paragraph("ANSWER KEY")
90
- ans_table = doc.add_table(rows=len(answers)+1, cols=5)
91
- ans_table.style = 'Table Grid'
92
- headers = ["Q#", "A", "B", "C", "D"]
93
- for idx, text in enumerate(headers):
94
- ans_table.cell(0, idx).text = text
95
- ans_table.cell(0, idx).paragraphs[0].runs[0].bold = True
96
- for r, ans in enumerate(answers, start=1):
97
- ans_table.cell(r, 0).text = str(r)
98
- for c, option in enumerate(["A","B","C","D"], start=1):
99
- ans_table.cell(r, c).text = "✔" if ans==option else ""
100
-
101
- file_path = f"{grade}_{subject}_{chapter}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.docx"
102
- doc.save(file_path)
103
- return file_path
104
-
105
- # -------------------------
106
- # Generate test
107
- # -------------------------
108
- def on_generate(grade, subject, chapter, difficulty, num_questions):
109
- mcqs, options_list, answers = generate_mcqs(grade, subject, chapter, difficulty, num_questions)
110
- file_path = export_to_word(mcqs, options_list, answers, grade, subject, chapter, difficulty)
111
- return f"Test ready: {file_path}", file_path
112
-
113
- # -------------------------
114
- # Gradio UI
115
- # -------------------------
116
- with gr.Blocks() as demo:
117
- gr.Markdown("### **MCQ Test Generator - Developer: Najaf Ali Sharqi**")
118
 
119
- with gr.Row():
120
- grade_dropdown = gr.Dropdown(choices=grades, label="Select Grade")
121
- subject_dropdown = gr.Dropdown(choices=[], label="Select Subject")
122
- chapter_dropdown = gr.Dropdown(choices=[], label="Select Chapter")
123
 
124
- with gr.Row():
125
- difficulty_dropdown = gr.Dropdown(choices=difficulty_levels, label="Select Difficulty")
126
- num_mcq_slider = gr.Slider(minimum=min_mcq, maximum=max_mcq, value=20, step=1, label="Number of MCQs")
127
 
128
- generate_btn = gr.Button("Generate Test")
129
- output_text = gr.Textbox(label="Status")
130
- output_file = gr.File(label="Download Test")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
- # Dropdown updates
133
- def update_subjects(grade):
134
- subjects = list(chapters_by_subject_and_grade.get(grade, {}).keys())
135
- return gr.update(choices=subjects, value=subjects[0] if subjects else None)
136
 
137
- def update_chapters(subject, grade):
138
- chapters = chapters_by_subject_and_grade.get(grade, {}).get(subject, [])
139
- return gr.update(choices=chapters, value=chapters[0] if chapters else None)
140
 
141
- grade_dropdown.change(update_subjects, grade_dropdown, subject_dropdown)
142
- subject_dropdown.change(update_chapters, [subject_dropdown, grade_dropdown], chapter_dropdown)
143
 
144
- generate_btn.click(on_generate,
145
- inputs=[grade_dropdown, subject_dropdown, chapter_dropdown, difficulty_dropdown, num_mcq_slider],
146
- outputs=[output_text, output_file])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
  demo.launch()
 
 
1
  import gradio as gr
 
2
  from docx import Document
3
+ import random
4
+
5
+ # -----------------------------
6
+
7
+ # Grades and Subjects
8
+
9
+ # -----------------------------
10
+
11
+ grades = {
12
+ "Grade 1": ["Mathematics", "English", "Urdu", "Islamiyat", "General Knowledge"],
13
+ "Grade 2": ["Mathematics", "English", "Urdu", "Islamiyat", "General Knowledge"],
14
+ "Grade 3": ["Mathematics", "English", "Urdu", "Science", "Islamiyat", "General Knowledge"],
15
+ "Grade 4": ["Mathematics", "English", "Urdu", "Science", "Islamiyat", "Social Studies"],
16
+ "Grade 5": ["Mathematics", "English", "Urdu", "Science", "Islamiyat", "Social Studies"],
17
+ "Grade 6": ["Mathematics", "English", "Urdu", "Science", "Islamiyat", "Social Studies"],
18
+ "Grade 7": ["Mathematics", "English", "Urdu", "Science", "Islamiyat", "Social Studies", "Computer"],
19
+ "Grade 8": ["Mathematics", "English", "Urdu", "Science", "Islamiyat", "Social Studies", "Computer"],
20
+ "Grade 9": ["Mathematics", "English", "Urdu", "Biology", "Chemistry", "Physics", "Islamiyat", "Pakistan Studies", "Computer"],
21
+ "Grade 10": ["Mathematics", "English", "Urdu", "Biology", "Chemistry", "Physics", "Islamiyat", "Pakistan Studies", "Computer"],
22
+ "Grade 11": ["Mathematics", "English", "Urdu", "Biology", "Chemistry", "Physics", "Computer", "Islamiyat", "Pakistan Studies"],
23
+ "Grade 12": ["Mathematics", "English", "Urdu", "Biology", "Chemistry", "Physics", "Computer", "Islamiyat", "Pakistan Studies"]
 
 
 
 
 
 
 
 
 
 
24
  }
25
 
26
+ # -----------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
+ # Chapters by subject and grade
 
 
 
29
 
30
+ # -----------------------------
 
 
31
 
32
+ chapters_by_subject_and_grade = {
33
+ "Grade 1": {
34
+ "Mathematics": ["Counting & Number Recognition", "Basic Addition", "Basic Subtraction", "Shapes & Space", "Measurement"],
35
+ "English": ["Alphabet & Phonics", "Listening & Speaking", "Basic Vocabulary", "Simple Sentences", "Early Reading"],
36
+ "Urdu": ["حروف اور آوازیں", "الفاظ", "سادہ جملے", "پڑھائی کا تعارف", "چھوٹی کہانیاں"],
37
+ "Islamiyat": ["Iman Basics", "Prophets' Stories", "Good Manners", "Simple Prayers & Worship"],
38
+ "General Knowledge": ["My Home & Family", "Plants & Animals", "Seasons & Weather", "My School"]
39
+ },
40
+ "Grade 2": {
41
+ "Mathematics": ["Place Value", "Addition & Subtraction Facts", "Money", "Time", "Basic Shapes"],
42
+ "English": ["Reading Short Texts", "Simple Grammar", "Vocabulary Building", "Speaking Activities"],
43
+ "Urdu": ["روزمرہ الفاظ", "مختصر کہانیاں", "قرأتِ آسان"],
44
+ "Islamiyat": ["Stories of Prophets", "Good Deeds", "Worship Basics"],
45
+ "General Knowledge": ["Local Community", "Transportation & Safety", "Plants & Animals"]
46
+ },
47
+ "Grade 3": {
48
+ "Mathematics": ["Multiplication & Division", "Fractions", "Geometry Basics", "Measurement", "Patterns"],
49
+ "English": ["Tenses (simple)", "Comprehension Passages", "Vocabulary Development", "Sentence Writing"],
50
+ "Urdu": ["قواعد كا تعارف", "کہیں کہانیاں"],
51
+ "Science": ["Plants & Animals", "Human Body", "Materials & Uses"],
52
+ "Islamiyat": ["Seerat Stories & Morals", "Basic Akhlaq"],
53
+ "General Knowledge": ["Community Awareness", "Simple Machines", "Weather"]
54
+ },
55
+ "Grade 4": {
56
+ "Mathematics": ["Fractions & Decimals", "Geometry", "Data & Graphs", "Word Problems"],
57
+ "English": ["Grammar", "Paragraph Writing", "Comprehension", "Listening & Speaking"],
58
+ "Urdu": ["نظم و نثر کا مطالعہ", "قواعد"],
59
+ "Science": ["Ecosystems", "Forces & Simple Machines", "Heat & Energy"],
60
+ "Islamiyat": ["Pillars of Islam", "Seerah Highlights"],
61
+ "Social Studies": ["Local Geography", "Community & Careers", "Citizenship"]
62
+ },
63
+ "Grade 5": {
64
+ "Mathematics": ["Number Operations", "Percentage & Ratio", "Geometry & Area", "Statistics"],
65
+ "English": ["Advanced Comprehension", "Essay & Letter Writing", "Grammar Consolidation"],
66
+ "Urdu": ["ادبی مطالعہ اور تحریر", "قواعد"],
67
+ "Science": ["Cells", "Matter & its Properties", "Energy & Sound"],
68
+ "Islamiyat": ["Quranic Stories & Morals"],
69
+ "Social Studies": ["History", "Map Skills", "Basic Economics"]
70
+ },
71
+ # ------------------ Grades 6-8 ------------------
72
+ "Grade 6": {
73
+ "Mathematics": ["Number System", "Algebraic Expressions", "Geometry", "Data Handling"],
74
+ "English": ["Grammar & Usage", "Comprehension", "Writing Paragraphs", "Poetry & Prose"],
75
+ "Urdu": ["نثر و نظم", "قواعد ِاردو", "تحریر"],
76
+ "Science": ["Atoms & Molecules", "Human Body Systems", "Plants & Ecology"],
77
+ "Islamiyat": ["Seerah & Ahkam"],
78
+ "Social Studies": ["Physical Geography", "Early Civilizations", "Citizenship"]
79
+ },
80
+ "Grade 7": {
81
+ "Mathematics": ["Algebra", "Geometry", "Mensuration", "Graphs"],
82
+ "English": ["Advanced Grammar", "Comprehension Passages", "Composition"],
83
+ "Urdu": ["ادبی اور تنقیدی مطالعہ", "قواعد"],
84
+ "Science": ["Cell Biology", "Electricity & Magnetism", "Properties of Matter"],
85
+ "Islamiyat": ["Islamic History & Ethics"],
86
+ "Social Studies": ["Regional Geography", "Historical Events"],
87
+ "Computer": ["ICT Basics", "Introductory Coding"]
88
+ },
89
+ "Grade 8": {
90
+ "Mathematics": ["Linear Equations", "Coordinate Geometry", "Trigonometry", "Probability"],
91
+ "English": ["Critical Reading", "Extended Writing", "Grammar Review"],
92
+ "Urdu": ["ادبی تنقید", "تحریر"],
93
+ "Science": ["Forces & Motion", "Heat & Temperature", "Waves & Optics"],
94
+ "Islamiyat": ["Fiqh Basics & Seerah"],
95
+ "Social Studies": ["Civics & Government", "Economic Concepts"],
96
+ "Computer": ["Algorithms & Flowcharts", "Application Software"]
97
+ },
98
+ # ------------------ Grade 9 ------------------
99
+ "Grade 9": {
100
+ "Mathematics": ["Number Systems", "Coordinate Geometry", "Trigonometry", "Graphs"],
101
+ "English": ["Advanced Grammar", "Comprehension", "Writing Skills"],
102
+ "Urdu": ["ادب اور نثر", "نظم", "مضامین"],
103
+ "Biology": ["Introduction to Biology","Cells and Tissues","Nutrition","Transport"],
104
+ "Chemistry": ["Fundamentals","Atomic Structure","Periodic Table","Chemical Reactivity"],
105
+ "Physics": ["Physical Quantities","Kinematics","Dynamics","Work and Energy"],
106
+ "Islamiyat": ["Seerat of Prophet","Faith & Beliefs"],
107
+ "Pakistan Studies": ["Ideological Basis","Making of Pakistan","Land & Environment"],
108
+ "Computer": ["Fundamentals of Computing","ICT Applications"]
109
+ },
110
+ # ------------------ Grade 10 ------------------
111
+ "Grade 10": {
112
+ "Mathematics": ["Advanced Algebra", "Trigonometry", "Geometry", "Probability"],
113
+ "English": ["Literature", "Advanced Composition", "Comprehension"],
114
+ "Urdu": ["ادبِ جدید", "تحقیقی مضمون"],
115
+ "Biology": ["Gaseous Exchange","Homeostasis","Coordination","Reproduction"],
116
+ "Chemistry": ["Chemical Equilibrium","Acids, Bases","Organic Chemistry","Hydrocarbons"],
117
+ "Physics": ["Simple Harmonic Motion","Sound","Optics","Electrostatics"],
118
+ "Islamiyat": ["Islamic Studies II","Ethics & Society"],
119
+ "Pakistan Studies": ["History of Pakistan-II","Population & Culture"],
120
+ "Computer": ["Programming Basics","ICT in Society"]
121
+ },
122
+ # ------------------ Grade 11 ------------------
123
+ "Grade 11": {
124
+ "Mathematics": ["Advanced Algebra","Coordinate Geometry","Trigonometry","Vectors"],
125
+ "English": ["Academic Writing","Literature Studies","Critical Reading"],
126
+ "Urdu": ["ادبی مطالعہ","نظم و نثر کی تشریح"],
127
+ "Biology": ["Cell Structure","Biological Molecules","Enzymes","Bioenergetics"],
128
+ "Chemistry": ["Stoichiometry","Atomic Structure","Bonding","States of Matter"],
129
+ "Physics": ["Measurement & Vectors","Forces & Motion","Work & Energy","Rotational Motion"],
130
+ "Computer": ["Programming Fundamentals","Data Structures"],
131
+ "Islamiyat": ["Advanced Seerah","Islamic Ethics"],
132
+ "Pakistan Studies": ["Geography","Resources & Economy","Historical Overview"]
133
+ },
134
+ # ------------------ Grade 12 ------------------
135
+ "Grade 12": {
136
+ "Mathematics": ["Calculus","Advanced Algebra","Statistics","Analytical Geometry"],
137
+ "English": ["Research Writing","Advanced Literature","Critical Analysis"],
138
+ "Urdu": ["تحقیق و تنقید","ادبی شخصیات"],
139
+ "Biology": ["Respiration","Homeostasis","Support & Movement","Reproduction","Genetics","Evolution"],
140
+ "Chemistry": ["s & p Block Elements","d Block Elements","Organic Chemistry","Analytical Chemistry"],
141
+ "Physics": ["Electromagnetism","AC Circuits","Atomic Physics","Modern Physics"],
142
+ "Computer": ["Advanced Programming","Web Technologies"],
143
+ "Islamiyat": ["Fiqh","Contemporary Islamic Thought"],
144
+ "Pakistan Studies": ["Society & Culture","Foreign Relations","Economic Policies"]
145
+ }
146
+ }
147
 
148
+ # -----------------------------
 
 
 
149
 
150
+ # Gradio UI functions
 
 
151
 
152
+ # -----------------------------
 
153
 
154
+ def update_subjects(grade):
155
+ subjects = list(chapters_by_subject_and_grade.get(grade, {}).keys())
156
+ return gr.update(choices=subjects, value=subjects[0] if subjects else None)
157
+
158
+ def update_chapters(subject, grade):
159
+ chapters = chapters_by_subject_and_grade.get(grade, {}).get(subject, [])
160
+ return gr.update(choices=chapters, value=chapters[0] if chapters else None)
161
+
162
+ def generate_mcqs(grade, subject, chapter, difficulty, num_questions):
163
+ # Simple MCQ placeholder generator
164
+ mcqs = []
165
+ answers = []
166
+ for i in range(1, num_questions+1):
167
+ mcqs.append(f"{i}. MCQ for {subject} - {chapter} (Difficulty: {difficulty})")
168
+ answers.append("A") # Placeholder
169
+ return mcqs, answers
170
+
171
+ def export_to_word(mcqs, answers, grade, subject, chapter, difficulty, num_questions):
172
+ doc = Document()
173
+ doc.add_heading("MONTHLY/WEEKLY TEST", level=0)
174
+ table = doc.add_table(rows=1, cols=2)
175
+ table.style = "Table Grid"
176
+ hdr_cells = table.rows[0].cells
177
+ hdr_cells[0].text = "MCQ"
178
+ hdr_cells[1].text = "Options"
179
+ for mcq in mcqs:
180
+ row_cells = table.add_row().cells
181
+ row_cells[0].text = mcq
182
+ row_cells[1].text = "A. ... B. ... C. ... D. ..."
183
+ # Answer Key Table
184
+ doc.add_paragraph("\nAnswer Key:")
185
+ ans_table = doc.add_table(rows=1, cols=2)
186
+ ans_table.style = "Table Grid"
187
+ ans_hdr = ans_table.rows[0].cells
188
+ ans_hdr[0].text = "MCQ No"
189
+ ans_hdr[1].text = "Answer"
190
+ for idx, ans in enumerate(answers, 1):
191
+ row_cells = ans_table.add_row().cells
192
+ row_cells[0].text = str(idx)
193
+ row_cells[1].text = ans
194
+ file_path = f"{grade}*{subject}*{chapter}_MCQs.docx"
195
+ doc.save(file_path)
196
+ return file_path
197
+
198
+ # -----------------------------
199
+
200
+ # Gradio App
201
+
202
+ # -----------------------------
203
+
204
+ with gr.Blocks() as demo:
205
+ gr.Markdown("### MCQ TEST GENERATOR (PAKISTAN CURRICULUM 2006)")
206
+ grade_input = gr.Dropdown(list(grades.keys()), label="Select Grade")
207
+ subject_input = gr.Dropdown(label="Select Subject")
208
+ chapter_input = gr.Dropdown(label="Select Chapter")
209
+ difficulty_input = gr.Dropdown(["Pretest (Beginner)", "Intermediate", "Advanced"], label="Difficulty Level")
210
+ num_questions_input = gr.Slider(minimum=5, maximum=50, step=1, value=20, label="Number of MCQs")
211
+ generate_btn = gr.Button("Generate MCQs")
212
+ download_output = gr.File(label="Download MS Word Test")
213
+
214
+ ```
215
+ grade_input.change(update_subjects, grade_input, subject_input)
216
+ grade_input.change(lambda g: update_chapters(subject_input.value, g), grade_input, chapter_input)
217
+ subject_input.change(lambda s, g: update_chapters(s, g), [subject_input, grade_input], chapter_input)
218
+ generate_btn.click(generate_mcqs, [grade_input, subject_input, chapter_input, difficulty_input, num_questions_input],
219
+ [gr.Textbox(), gr.Textbox()],
220
+ queue=False)
221
+ generate_btn.click(export_to_word, [gr.Textbox(), gr.Textbox(), grade_input, subject_input, chapter_input, difficulty_input, num_questions_input],
222
+ download_output, queue=False)
223
+ ```
224
 
225
  demo.launch()