Turbiling commited on
Commit
ddb9bc9
·
verified ·
1 Parent(s): 1707517

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -130
app.py CHANGED
@@ -5,9 +5,10 @@ from datetime import datetime
5
  from docx import Document
6
  from docx.shared import Pt
7
  from docx.enum.text import WD_ALIGN_PARAGRAPH
8
- import random
9
 
 
10
  # Initialize GROQ client
 
11
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
12
  client = Groq(api_key=GROQ_API_KEY)
13
 
@@ -15,130 +16,53 @@ grades = [f"Grade {i}" for i in range(1, 13)]
15
  difficulty_levels = ["Pretest (Beginner)", "Intermediate", "Advanced"]
16
  min_mcq, max_mcq = 5, 50
17
 
18
- # -------------------
19
- # Subjects and chapters by grade (1-12) according to National Curriculum 2006
20
- # -------------------
 
21
  chapters_by_subject_and_grade = {
22
- "Grade 1": {
23
- "Mathematics": ["Counting & Number Recognition", "Basic Addition", "Basic Subtraction", "Shapes & Space", "Measurement (Length, Weight)"],
24
- "English": ["Alphabet & Phonics", "Listening & Speaking", "Basic Vocabulary", "Simple Sentences", "Early Reading"],
25
- "Urdu": ["حروف اور آوازیں", "الفاظ", "سادہ جملے", "پڑھائی کا تعارف", "چھوٹی کہانیاں"],
26
- "Islamiyat": ["Iman Basics", "Prophets' Stories (selected)", "Good Manners", "Simple Prayers & Worship"],
27
- "General Knowledge": ["My Home & Family", "Plants & Animals", "Seasons & Weather", "My School"]
28
- },
29
- "Grade 2": {
30
- "Mathematics": ["Place Value", "Addition & Subtraction Facts", "Money", "Time (clock)", "Basic Shapes"],
31
- "English": ["Reading Short Texts", "Simple Grammar (nouns, verbs)", "Vocabulary Building", "Speaking Activities"],
32
- "Urdu": ["روزمرہ الفاظ", "مختصر کہانیاں", "قرأتِ آسان"],
33
- "Islamiyat": ["Stories of Prophets", "Good Deeds", "Worship Basics"],
34
- "General Knowledge": ["Local Community", "Transportation & Safety", "Plants & Animals"]
35
- },
36
- "Grade 3": {
37
- "Mathematics": ["Multiplication & Division", "Fractions (intro)", "Geometry Basics", "Measurement", "Patterns"],
38
- "English": ["Tenses (simple)", "Comprehension Passages", "Vocabulary Development", "Sentence Writing"],
39
- "Urdu": ["قواعد کا تعارف", "مختصر کہانیاں"],
40
- "Science": ["Plants & Animals", "Human Body (basic)", "Materials & Uses"],
41
- "Islamiyat": ["Seerat Stories & Morals", "Basic Akhlaq"],
42
- "General Knowledge": ["Local Environment", "Community Awareness"]
43
- },
44
- "Grade 4": {
45
- "Mathematics": ["Fractions & Decimals (intro)", "Geometry (angles, shapes)", "Data & Graphs", "Word Problems"],
46
- "English": ["Grammar (parts of speech)", "Paragraph Writing", "Comprehension", "Listening & Speaking"],
47
- "Urdu": ["نظم و نثر کا مطالعہ", "قواعد"],
48
- "Science": ["Ecosystems", "Forces & Simple Machines", "Heat & Energy"],
49
- "Islamiyat": ["Pillars of Islam", "Seerah Highlights"],
50
- "Social Studies": ["Local Geography", "Community & Careers", "Citizenship"]
51
- },
52
- "Grade 5": {
53
- "Mathematics": ["Number Operations", "Percentage & Ratio (intro)", "Geometry & Area", "Statistics (intro)"],
54
- "English": ["Advanced Comprehension", "Essay & Letter Writing", "Grammar Consolidation"],
55
- "Urdu": ["ادبی مطالعہ اور تحریر", "قواعد"],
56
- "Science": ["Cells (intro)", "Matter & its Properties", "Energy & Sound"],
57
- "Islamiyat": ["Quranic Stories & Morals"],
58
- "Social Studies": ["History (local & national)", "Map Skills", "Basic Economics"]
59
- },
60
- "Grade 6": {
61
- "Mathematics": ["Number System & Factors", "Algebraic Expressions (intro)", "Geometry Basics", "Data Handling"],
62
- "English": ["Grammar & Usage", "Comprehension", "Writing Paragraphs", "Poetry & Prose"],
63
- "Urdu": ["نثر و نظم", "قواعد ِاردو", "تحریر"],
64
- "Science": ["Atoms & Molecules (intro)", "Human Body Systems", "Plants & Ecology"],
65
- "Islamiyat": ["Seerah & Ahkam (intro)"],
66
- "Social Studies": ["Physical Geography", "Early Civilizations", "Citizenship"]
67
- },
68
- "Grade 7": {
69
- "Mathematics": ["Algebra (linear)", "Geometry (polygons, areas)", "Mensuration", "Graphs"],
70
- "English": ["Advanced Grammar", "Comprehension Passages", "Composition"],
71
- "Urdu": ["ادبی اور تنقیدی مطالعہ", "قواعد"],
72
- "Science": ["Cell Biology", "Electricity & Magnetism (basic)", "Properties of Matter"],
73
- "Islamiyat": ["Islamic History & Ethics"],
74
- "Social Studies": ["Regional Geography", "Historical Events & Movements"],
75
- "Computer": ["ICT Basics", "Introductory Coding Concepts"]
76
- },
77
- "Grade 8": {
78
- "Mathematics": ["Linear Equations & Inequalities", "Coordinate Geometry", "Pythagoras & Trigonometry (intro)", "Probability"],
79
- "English": ["Critical Reading", "Extended Writing", "Grammar Review"],
80
- "Urdu": ["ادبی تنقید", "تحریر"],
81
- "Science": ["Forces & Motion", "Heat & Temperature", "Waves & Optics (intro)"],
82
- "Islamiyat": ["Fiqh Basics & Seerah"],
83
- "Social Studies": ["Civics & Government", "Economic Concepts"],
84
- "Computer": ["Algorithms & Flowcharts", "Application Software"]
85
- },
86
- # ------------------ Secondary & Higher Secondary (9-12) ------------------
87
- "Grade 9": {
88
- "Mathematics": ["Number Systems & Algebra", "Coordinate Geometry", "Trigonometry", "Graphs"],
89
- "English": ["Advanced Grammar", "Comprehension", "Writing Skills"],
90
- "Urdu": ["ادب اور نثر", "نظم", "مضامین"],
91
- "Biology": ["INTRODUCTION TO BIOLOGY","SOLVING A BIOLOGICAL PROBLEM","BIODIVERSITY","CELLS AND TISSUES","CELL CYCLE","ENZYMES","BIOENERGETICS","NUTRITION","TRANSPORT"],
92
- "Chemistry": ["FUNDAMENTALS OF CHEMISTRY","STRUCTURE OF ATOMS","PERIODIC TABLE AND PERIODICITY OF PROPERTIES","STRUCTURE OF MOLECULES","PHYSICAL STATES OF MATTER","SOLUTIONS","ELECTROCHEMISTRY","CHEMICAL REACTIVITY"],
93
- "Physics": ["PHYSICAL QUANTITIES AND MEASUREMENT","KINEMATICS","DYNAMICS","TURNING EFFECT OF FORCES","GRAVITATION","WORK AND ENERGY","PROPERTIES OF MATTER","THERMAL PROPERTIES OF MATTER","TRANSFER OF HEAT"],
94
- "Islamiyat": ["Seerat of Prophet", "Faith & Beliefs", "Worship Practices"],
95
- "Pakistan Studies": ["IDEOLOGICAL BASIS OF PAKISTAN","MAKING OF PAKISTAN","LAND AND ENVIRONMENT","HISTORY OF PAKISTAN"],
96
- "Computer": ["Fundamentals of Computing", "ICT Applications"]
97
- },
98
- "Grade 10": {
99
- "Mathematics": ["Advanced Algebra", "Trigonometry", "Geometry", "Probability"],
100
- "English": ["Literature", "Advanced Composition", "Comprehension"],
101
- "Urdu": ["ادبِ جدید", "تحقیقی مضمون"],
102
- "Biology": ["GASEOUS EXCHANGE","HOMEOSTASIS","COORDINATION","SUPPORT AND MOVEMENT","REPRODUCTION","INHERITANCE","MAN AND HIS ENVIRONMENT","BIOTECHNOLOGY","PHARMA"],
103
- "Chemistry": ["CHEMICAL EQUILIBRIUM","ACIDS, BASES AND SALTS","ORGANIC CHEMISTRY","HYDROCARBONS","BIOCHEMISTRY","ENVIRONMENTAL CHEMISTRY I: THE ATMOSPHERE","ENVIRONMENTAL CHEMISTRY II: WATER","CHEMICAL INDUSTRIES"],
104
- "Physics": ["SIMPLE HARMONIC MOTION AND WAVES","SOUND","GEOMETRICAL OPTICS","ELECTROSTATICS","CURRENT ELECTRICITY","ELECTROMAGNETISM","INTRODUCTORY ELECTRONICS","INFORMATION AND COMMUNICATION TECHNOLOGY","RADIOACTIVITY"],
105
- "Islamiyat": ["Islamic Studies II", "Ethics & Society", "Fiqh Basics"],
106
- "Pakistan Studies": ["HISTORY OF PAKISTAN-II","PAKISTAN IN WORLD AFFAIRS","ECONOMIC DEVELOPMENTS","POPULATION, SOCIETY AND CULTURE OF PAKISTAN"],
107
- "Computer": ["Programming Basics", "ICT in Society"]
108
- },
109
- "Grade 11": {
110
- "Mathematics": ["Advanced Algebra & Calculus Intro", "Coordinate Geometry", "Trigonometry", "Vectors"],
111
- "English": ["Academic Writing", "Literature Studies", "Critical Reading"],
112
- "Urdu": ["ادبی مطالعہ", "نظم و نثر کی تشریح"],
113
- "Biology": ["Cell Structure and Functions","Biological Molecules","Enzymes","Bioenergetics","Acellular Life & Microorganisms","Diversity of Plants","Diversity of Animals","Plant Form and Function","Digestion and Nutrition","Circulation and Respiration","Immunity"],
114
- "Chemistry": ["Stoichiometry & Chemical Calculations","Atomic Structure & Periodicity","Bonding & Molecular Shape","States of Matter (Gases, Liquids, Solids)","Solutions & Colligative Properties","Thermochemistry","Chemical Kinetics","Electrochemistry & Redox"],
115
- "Physics": ["Measurement & Vectors","Forces & Motion","Work & Energy","Rotational Motion","Fluid Mechanics","Oscillations & Waves","Geometrical Optics","Thermodynamics","Electrostatics","Current Electricity"],
116
- "Computer": ["Programming Fundamentals", "Data Structures Intro", "Databases & File Systems"],
117
- "Islamiyat": ["Advanced Seerah", "Islamic Ethics"],
118
- "Pakistan Studies": ["Pakistan in Geographical Perspective","Resources & Economy","Historical Overview","Political & Constitutional Development","Human Rights & Citizenship"]
119
- },
120
- "Grade 12": {
121
- "Mathematics": ["Calculus", "Advanced Algebra", "Statistics", "Analytical Geometry"],
122
- "English": ["Research Writing", "Advanced Literature", "Critical Analysis"],
123
- "Urdu": ["تحقیق و تنقید", "ادبی شخصیات"],
124
- "Biology": ["Respiration & Exchange","Homeostasis & Coordination","Support, Movement & Musculoskeletal System","Reproduction & Development","Genetics & Inheritance","Evolution & Biodiversity","Man and His Environment","Biotechnology & Its Applications","Biology and Human Welfare"],
125
- "Chemistry": ["s and p Block Elements","d Block & Transition Elements","Organic Reaction Mechanisms","Hydrocarbons & Functional Groups","Alcohols, Phenols, Ethers","Aldehydes & Ketones","Carboxylic Acids & Derivatives","Biochemistry (Carbohydrates, Proteins, Lipids)","Analytical & Industrial Chemistry","Environmental Chemistry"],
126
- "Physics": ["Electromagnetism & EM Induction","Alternating Current Circuits","Electronics & Semiconductors","Atomic & Nuclear Physics","Modern Physics Topics","Optics & Waves (advanced)"],
127
- "Computer": ["Advanced Programming Concepts", "Web Technologies & Networks"],
128
- "Islamiyat": ["Islamic Jurisprudence (Fiqh)", "Contemporary Islamic Thought"],
129
- "Pakistan Studies": ["Society & Culture","Foreign Relations","Economic Policies & Development","Contemporary Challenges & National Identity"]
130
- }
131
  }
132
 
133
- # -------------------
134
- # MCQ generation and Word export (same as previous working code)
135
- # -------------------
136
  def generate_mcqs(grade, subject, chapter, difficulty, num_questions):
137
- mcqs = [f"Sample question {i} for {subject} chapter {chapter}" for i in range(1, num_questions+1)]
138
- answers = [random.choice(["A","B","C","D"]) for _ in mcqs]
139
- return mcqs, answers
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
- def export_to_word(mcqs, answers, grade, subject, chapter, difficulty, num_questions):
 
 
 
142
  doc = Document()
143
  heading = doc.add_paragraph("MONTHLY/ WEEKLY TEST")
144
  heading.alignment = WD_ALIGN_PARAGRAPH.CENTER
@@ -151,7 +75,7 @@ def export_to_word(mcqs, answers, grade, subject, chapter, difficulty, num_quest
151
  table.style = 'Table Grid'
152
  info = [
153
  ("Grade", grade),("Subject", subject),("Chapter", chapter),("Difficulty", difficulty),
154
- ("Number of Questions", str(num_questions)),("Date", datetime.now().strftime("%d-%m-%Y"))
155
  ]
156
  for row, (label, value) in zip(table.rows, info):
157
  row.cells[0].text = label
@@ -159,12 +83,14 @@ def export_to_word(mcqs, answers, grade, subject, chapter, difficulty, num_quest
159
  row.cells[0].paragraphs[0].runs[0].bold = True
160
 
161
  # MCQs
162
- for i, q in enumerate(mcqs, start=1):
163
- doc.add_paragraph(f"{i}. {q}")
 
 
164
 
165
- # Answer key table only
166
  doc.add_paragraph("\nAnswer Key:")
167
- ans_table = doc.add_table(rows=num_questions+1, cols=5)
168
  ans_table.style = 'Table Grid'
169
  headers = ["Q#", "A", "B", "C", "D"]
170
  for idx, text in enumerate(headers):
@@ -179,14 +105,17 @@ def export_to_word(mcqs, answers, grade, subject, chapter, difficulty, num_quest
179
  doc.save(file_path)
180
  return file_path
181
 
 
 
 
182
  def on_generate(grade, subject, chapter, difficulty, num_questions):
183
- mcqs, answers = generate_mcqs(grade, subject, chapter, difficulty, num_questions)
184
- file_path = export_to_word(mcqs, answers, grade, subject, chapter, difficulty, num_questions)
185
  return f"Test ready: {file_path}", file_path
186
 
187
- # -------------------
188
  # Gradio UI
189
- # -------------------
190
  with gr.Blocks() as demo:
191
  gr.Markdown("### **MCQ Test Generator - Developer: Najaf Ali Sharqi**")
192
  with gr.Row():
@@ -200,7 +129,7 @@ with gr.Blocks() as demo:
200
  output_text = gr.Textbox(label="Status")
201
  output_file = gr.File(label="Download Test")
202
 
203
- # Populate dropdowns
204
  def update_subjects(grade):
205
  return gr.update(choices=list(chapters_by_subject_and_grade.get(grade, {}).keys()), value=None)
206
  def update_chapters(subject, grade):
 
5
  from docx import Document
6
  from docx.shared import Pt
7
  from docx.enum.text import WD_ALIGN_PARAGRAPH
 
8
 
9
+ # -------------------------
10
  # Initialize GROQ client
11
+ # -------------------------
12
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
13
  client = Groq(api_key=GROQ_API_KEY)
14
 
 
16
  difficulty_levels = ["Pretest (Beginner)", "Intermediate", "Advanced"]
17
  min_mcq, max_mcq = 5, 50
18
 
19
+ # -------------------------
20
+ # Chapters by grade & subject
21
+ # Use your complete chapters_by_subject_and_grade dictionary here (same as previous code)
22
+ # -------------------------
23
  chapters_by_subject_and_grade = {
24
+ # Full dictionary from previous code including Grades 1-12
25
+ # ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  }
27
 
28
+ # -------------------------
29
+ # Function to generate MCQs from Groq LLaMA-3
30
+ # -------------------------
31
  def generate_mcqs(grade, subject, chapter, difficulty, num_questions):
32
+ prompt = f"""
33
+ Generate {num_questions} multiple-choice questions for {subject}, Grade {grade}, Chapter '{chapter}'.
34
+ Level: {difficulty}.
35
+ Each question should have 4 options (A, B, C, D) and indicate the correct answer.
36
+ Return the output in JSON format like:
37
+ [
38
+ {{"question": "Question text", "options": ["A text", "B text", "C text", "D text"], "answer": "A"}}
39
+ ]
40
+ """
41
+ response = client.generate(
42
+ model="llama3",
43
+ prompt=prompt,
44
+ max_tokens=1500
45
+ )
46
+
47
+ try:
48
+ import json
49
+ mcq_list = json.loads(response.text)
50
+ except:
51
+ # fallback: placeholder MCQs if Groq fails
52
+ mcq_list = [{"question": f"Sample question {i} for {subject} chapter {chapter}",
53
+ "options": ["Option A","Option B","Option C","Option D"],
54
+ "answer": "A"} for i in range(1, num_questions+1)]
55
+
56
+ questions = [q["question"] for q in mcq_list]
57
+ answers = [q["answer"] for q in mcq_list]
58
+ options_list = [q["options"] for q in mcq_list]
59
+
60
+ return questions, options_list, answers
61
 
62
+ # -------------------------
63
+ # Export to Word
64
+ # -------------------------
65
+ def export_to_word(mcqs, options_list, answers, grade, subject, chapter, difficulty):
66
  doc = Document()
67
  heading = doc.add_paragraph("MONTHLY/ WEEKLY TEST")
68
  heading.alignment = WD_ALIGN_PARAGRAPH.CENTER
 
75
  table.style = 'Table Grid'
76
  info = [
77
  ("Grade", grade),("Subject", subject),("Chapter", chapter),("Difficulty", difficulty),
78
+ ("Number of Questions", str(len(mcqs))),("Date", datetime.now().strftime("%d-%m-%Y"))
79
  ]
80
  for row, (label, value) in zip(table.rows, info):
81
  row.cells[0].text = label
 
83
  row.cells[0].paragraphs[0].runs[0].bold = True
84
 
85
  # MCQs
86
+ for i, (q, opts) in enumerate(zip(mcqs, options_list), start=1):
87
+ para = doc.add_paragraph(f"{i}. {q}")
88
+ for letter, text in zip(["A","B","C","D"], opts):
89
+ doc.add_paragraph(f"{letter}. {text}", style='List Number')
90
 
91
+ # Answer key table
92
  doc.add_paragraph("\nAnswer Key:")
93
+ ans_table = doc.add_table(rows=len(mcqs)+1, cols=5)
94
  ans_table.style = 'Table Grid'
95
  headers = ["Q#", "A", "B", "C", "D"]
96
  for idx, text in enumerate(headers):
 
105
  doc.save(file_path)
106
  return file_path
107
 
108
+ # -------------------------
109
+ # Generate test function
110
+ # -------------------------
111
  def on_generate(grade, subject, chapter, difficulty, num_questions):
112
+ mcqs, options_list, answers = generate_mcqs(grade, subject, chapter, difficulty, num_questions)
113
+ file_path = export_to_word(mcqs, options_list, answers, grade, subject, chapter, difficulty)
114
  return f"Test ready: {file_path}", file_path
115
 
116
+ # -------------------------
117
  # Gradio UI
118
+ # -------------------------
119
  with gr.Blocks() as demo:
120
  gr.Markdown("### **MCQ Test Generator - Developer: Najaf Ali Sharqi**")
121
  with gr.Row():
 
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
  return gr.update(choices=list(chapters_by_subject_and_grade.get(grade, {}).keys()), value=None)
135
  def update_chapters(subject, grade):