Turbiling commited on
Commit
20f02d5
·
verified ·
1 Parent(s): b8d6820

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +156 -156
app.py CHANGED
@@ -1,203 +1,203 @@
1
- import os
2
  import gradio as gr
3
- import datetime
4
- from tempfile import NamedTemporaryFile
5
- from docx import Document
6
  from groq import Groq
 
 
 
7
 
8
- # ✅ Initialize Groq client
9
- client = Groq(api_key=os.getenv("GROQ_API_KEY"))
10
 
11
- URDU_MODEL = "openai/gpt-oss-120b"
12
- ENGLISH_MODEL = "llama-3.1-8b-instant"
13
 
 
 
 
 
 
 
14
 
15
- # ✅ Function: Generate SMART Lesson Plan
16
- def generate_lesson_plan(language, grade, subject, topic, duration, student_level):
17
- if language == "Urdu":
18
- model = URDU_MODEL
19
- prompt = f"""
20
- آپ ایک ماہر استاد ہیں۔ دی گئی معلومات کی بنیاد پر ایک SMART طرز کا تدریسی منصوبہ تیار کریں۔
21
- درج ذیل حصے شامل ہوں:
22
- 1. معلوماتی جدول (Input Table)
23
- 2. SMART تعلیمی مقاصد (SLOs)
24
- 3. "پڑھایا جانے والا مواد" (Content to be delivered): تعریفیں، کلیدی اصطلاحات اور تصورات۔
25
- 4. گھریلو کام (Home Assignment) — جو SLOs سے مطابقت رکھتا ہو۔
26
- 5. سرپرست یا پرنسپل کی رائے کے لیے خالی جگہ (Feedback by Mentor/Principal)
27
 
28
- جماعت: {grade}
29
- مضمون: {subject}
30
- موضوع: {topic}
31
- دورانیہ: {duration} منٹ
32
- طلباء کی سطح: {student_level}
33
- """
34
- else:
35
- model = ENGLISH_MODEL
36
- prompt = f"""
37
- You are an expert Pakistani school teacher. Create a SMART-style lesson plan with the following structure:
38
 
39
- 1. Input Table
40
- 2. SMART Learning Outcomes (SLOs)
41
- 3. Content to be Delivered — include definitions, key terms, and key concepts related to the topic.
42
- 4. Home Assignment — must directly align with the SLOs.
43
- 5. Feedback by Mentor/Principal (leave blank space for handwritten notes)
44
 
 
 
 
 
 
45
  Grade: {grade}
46
  Subject: {subject}
47
- Topic: {topic}
48
- Duration: {duration} minutes
49
- Student Level: {student_level}
 
 
 
 
 
 
 
 
 
 
50
  """
 
 
 
 
 
 
 
 
51
 
52
- response = client.chat.completions.create(
53
- model=model,
54
- messages=[{"role": "user", "content": prompt}],
55
- temperature=0.7,
56
- max_tokens=1800
57
- )
58
- content = response.choices[0].message.content.strip()
 
 
 
 
59
 
60
- # ✅ Create downloadable file
 
61
  if language == "English":
62
- doc = Document()
63
- doc.add_heading("SMART LESSON PLAN", level=1)
64
-
65
- table = doc.add_table(rows=5, cols=2)
66
- headers = ["Grade", "Subject", "Topic", "Duration", "Student Level"]
67
- values = [grade, subject, topic, f"{duration} minutes", student_level]
68
- for i in range(5):
69
- table.cell(i, 0).text = headers[i]
70
- table.cell(i, 1).text = str(values[i])
71
-
72
- doc.add_paragraph("\n" + content)
73
- doc.add_paragraph("\nDeveloped by: Najaf Ali")
74
-
75
- temp = NamedTemporaryFile(delete=False, suffix=".docx")
76
- doc.save(temp.name)
77
- file_path = temp.name
78
- message = f"✅ English SMART Lesson Plan generated successfully for {subject} ({grade})."
79
-
80
  else:
81
- md_text = f"""
82
- <div dir="rtl" align="right">
83
 
84
- # 📘 SMART LESSON PLAN
85
 
86
- | کلیدی معلومات | تفصیل |
87
- |----------------|--------|
88
- | جماعت | {grade} |
89
- | مضمون | {subject} |
90
- | عنوان | {topic} |
91
- | دورانیہ | {duration} منٹ |
92
- | طلبہ کی سطح | {student_level} |
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
- ---
 
 
 
 
 
 
95
 
96
- {content}
97
 
98
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
- **مرتب کردہ: نجف علی**
101
- </div>
102
- """
103
- temp = NamedTemporaryFile(delete=False, suffix=".md", mode="w", encoding="utf-8")
104
- temp.write(md_text)
105
- temp.close()
106
- file_path = temp.name
107
- message = f"✅ اردو تدریسی منصوبہ ({subject}) کامیابی سے تیار ہو گیا۔"
108
 
109
- return message, file_path, content
110
 
 
111
 
112
- # ✅ Function: Generate Flashcards
113
- def generate_flashcards(language, topic, slos_text):
114
- model = URDU_MODEL if language == "Urdu" else ENGLISH_MODEL
 
115
 
116
- prompt = f"""
117
- Based on the topic "{topic}" and the following SLOs:
118
- {slos_text}
119
- Generate 5 short and clear **Flashcards** (Question/Term on one side and Answer/Definition on the other side).
120
- Ensure alignment with the SLOs and curriculum context of Pakistan.
121
- """
122
- response = client.chat.completions.create(
123
- model=model,
124
- messages=[{"role": "user", "content": prompt}],
125
- temperature=0.6,
126
- max_tokens=800
127
- )
128
- return response.choices[0].message.content.strip()
129
 
 
 
 
130
 
131
- # ✅ Function: Generate Quiz
132
- def generate_quiz(language, topic, slos_text):
133
- model = URDU_MODEL if language == "Urdu" else ENGLISH_MODEL
134
 
135
- prompt = f"""
136
- Based on the topic "{topic}" and these SLOs:
137
- {slos_text}
138
- Create a short quiz including:
139
- - 5 Multiple Choice Questions (MCQs)
140
- - 2 Short Answer Questions
141
- - 2 Fill-in-the-Blank Questions
142
- Ensure all are aligned with the SLOs and Pakistani curriculum.
143
- """
144
- response = client.chat.completions.create(
145
- model=model,
146
- messages=[{"role": "user", "content": prompt}],
147
- temperature=0.7,
148
- max_tokens=800
149
- )
150
- return response.choices[0].message.content.strip()
151
 
 
152
 
153
- # ✅ Build Gradio Interface
154
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="teal")) as demo:
155
- gr.Markdown("## 🧠 SMART LESSON PLAN GENERATOR (Bilingual)")
156
- gr.Markdown("**Developed by: Najaf Ali**")
157
 
158
  with gr.Row():
159
  language = gr.Dropdown(["English", "Urdu"], label="Select Language", value="English")
 
 
 
160
  grade = gr.Dropdown(
161
- [f"Grade {i}" for i in range(1, 13)], label="Select Grade", value="Grade 9"
 
 
162
  )
163
  subject = gr.Dropdown(
164
- [
165
- "English", "Urdu", "Mathematics", "Science", "Computer",
166
- "Islamiyat", "Pakistan Studies", "Physics", "Chemistry",
167
- "Biology", "Civics", "History", "Geography"
168
- ],
169
- label="Select Subject",
170
- value="Science"
171
  )
172
 
173
  with gr.Row():
174
- topic = gr.Textbox(label="Enter Topic (e.g., Photosynthesis, Fractions, Noun Types)")
175
- duration = gr.Number(label="Duration (minutes)", value=40)
176
- student_level = gr.Dropdown(["Beginner", "Average", "Advanced"], label="Student Level", value="Average")
177
 
178
- generate_btn = gr.Button("🚀 Generate SMART Lesson Plan")
179
- output_message = gr.HTML(label="Status")
180
- file_output = gr.File(label="⬇️ Download Lesson Plan")
181
- lesson_textbox = gr.Textbox(label="Generated Lesson Plan Text", lines=20, visible=False)
182
 
183
- # ✅ Flashcards and Quiz buttons
184
- gr.Markdown("### 🎯 Generate Additional Materials (Aligned with Lesson Plan)")
185
- with gr.Row():
186
- flash_btn = gr.Button("🃏 Generate Flashcards")
187
- quiz_btn = gr.Button("📝 Generate Quiz")
188
 
189
- flash_output = gr.Textbox(label="Generated Flashcards", lines=10)
190
- quiz_output = gr.Textbox(label="Generated Quiz", lines=12)
 
191
 
192
- # ✅ Button connections
193
  generate_btn.click(
194
- generate_lesson_plan,
195
- inputs=[language, grade, subject, topic, duration, student_level],
196
- outputs=[output_message, file_output, lesson_textbox]
197
  )
198
 
199
- flash_btn.click(generate_flashcards, inputs=[language, topic, lesson_textbox], outputs=flash_output)
200
- quiz_btn.click(generate_quiz, inputs=[language, topic, lesson_textbox], outputs=quiz_output)
201
-
202
- # ✅ Launch App
203
- demo.launch()
 
 
1
  import gradio as gr
 
 
 
2
  from groq import Groq
3
+ from docx import Document
4
+ import datetime
5
+ import os
6
 
7
+ # ✅ Initialize Groq Client
8
+ client = Groq(api_key="YOUR_GROQ_API_KEY")
9
 
10
+ # ================== Helper Functions ==================
 
11
 
12
+ def generate_text(prompt, model_name):
13
+ response = client.chat.completions.create(
14
+ messages=[{"role": "user", "content": prompt}],
15
+ model=model_name,
16
+ )
17
+ return response.choices[0].message.content.strip()
18
 
19
+ def save_docx(content, filename):
20
+ doc = Document()
21
+ doc.add_paragraph(content)
22
+ filepath = f"/tmp/{filename}.docx"
23
+ doc.save(filepath)
24
+ return filepath
 
 
 
 
 
 
25
 
26
+ def save_md(content, filename):
27
+ content = content.replace("✨", "").replace("🌟", "").replace("✅", "")
28
+ filepath = f"/tmp/{filename}.md"
29
+ with open(filepath, "w", encoding="utf-8") as f:
30
+ f.write(content)
31
+ return filepath
 
 
 
 
32
 
33
+ # ================== Core Generation Functions ==================
 
 
 
 
34
 
35
+ def generate_lesson_plan(language, grade, subject, num_students, date, slo, content):
36
+ if language == "English":
37
+ model = "llama-3.1-8b-instant"
38
+ prompt = f"""
39
+ Create a SMART Lesson Plan in English for:
40
  Grade: {grade}
41
  Subject: {subject}
42
+ Number of Students: {num_students}
43
+ Date: {date}
44
+
45
+ Include the following sections:
46
+ 1. Input Table
47
+ 2. SLOs
48
+ 3. Content to be Delivered
49
+ 4. Home Assignment (aligned with SLOs)
50
+ 5. Feedback by Mentor/Principal
51
+
52
+ Use this context:
53
+ - SLOs: {slo}
54
+ - Content: {content}
55
  """
56
+ else:
57
+ model = "openai/gpt-oss-120b"
58
+ prompt = f"""
59
+ درج ذیل معلومات کی بنیاد پر ایک SMART سبق کا منصوبہ اردو میں تیار کریں۔
60
+ جماعت: {grade}
61
+ مضمون: {subject}
62
+ طلبہ کی تعداد: {num_students}
63
+ تاریخ: {date}
64
 
65
+ درج ذیل حصے شامل ہوں:
66
+ 1. ان پٹ جدول
67
+ 2. سیکھنے کے مقاصد (SLOs)
68
+ 3. پڑھائی جانے والا مواد
69
+ 4. گھریلو مشق (جو SLOs سے ہم آہنگ ہو)
70
+ 5. سرپرست / پرنسپل کی رائے
71
+
72
+ سیاق و سباق:
73
+ - سیکھنے کے مقاصد: {slo}
74
+ - مواد: {content}
75
+ """
76
 
77
+ output = generate_text(prompt, model)
78
+ filename = f"SMART_Lesson_Plan_{language}_{grade}_{subject}"
79
  if language == "English":
80
+ filepath = save_docx(output, filename)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  else:
82
+ filepath = save_md(output, filename)
83
+ return output, filepath
84
 
 
85
 
86
+ def generate_flashcards(language, grade, subject, slo, content):
87
+ if language == "English":
88
+ model = "llama-3.1-8b-instant"
89
+ prompt = f"""
90
+ Create concise classroom flashcards in English for Grade {grade}, Subject {subject}.
91
+ Align flashcards with the following SLOs and lesson content:
92
+ SLOs: {slo}
93
+ Content: {content}
94
+ Format as Q&A flashcards.
95
+ """
96
+ else:
97
+ model = "openai/gpt-oss-120b"
98
+ prompt = f"""
99
+ درج ذیل سیکھنے کے مقاصد اور مواد کی بنیاد پر جماعت {grade} کے لیے فلیش کارڈز تیار کریں۔
100
+ مضمون: {subject}
101
+ ہر کارڈ میں سوال اور مختصر جواب شامل ہو۔
102
+ سیکھنے کے مقاصد: {slo}
103
+ مواد: {content}
104
+ """
105
 
106
+ output = generate_text(prompt, model)
107
+ filename = f"Flashcards_{language}_{grade}_{subject}"
108
+ if language == "English":
109
+ filepath = save_docx(output, filename)
110
+ else:
111
+ filepath = save_md(output, filename)
112
+ return output, filepath
113
 
 
114
 
115
+ def generate_quiz(language, grade, subject, slo, content):
116
+ if language == "English":
117
+ model = "llama-3.1-8b-instant"
118
+ prompt = f"""
119
+ Create a short quiz in English for Grade {grade}, Subject {subject}.
120
+ Align questions with the following SLOs and lesson content.
121
+ SLOs: {slo}
122
+ Content: {content}
123
+ Include 5 multiple-choice questions with answers.
124
+ """
125
+ else:
126
+ model = "openai/gpt-oss-120b"
127
+ prompt = f"""
128
+ جماعت {grade}، مضمون {subject} کے لیے ایک مختصر کوئز اردو میں تیار کریں۔
129
+ کوئز کے سوالات درج ذیل سیکھنے کے مقاصد اور مواد سے ہم آہنگ ہوں۔
130
+ سیکھنے کے مقاصد: {slo}
131
+ مواد: {content}
132
+ پانچ کثیرالاختیاری سوالات (MCQs) شامل کریں اور جوابات بھی دیں۔
133
+ """
134
 
135
+ output = generate_text(prompt, model)
136
+ filename = f"Quiz_{language}_{grade}_{subject}"
137
+ if language == "English":
138
+ filepath = save_docx(output, filename)
139
+ else:
140
+ filepath = save_md(output, filename)
141
+ return output, filepath
 
142
 
 
143
 
144
+ # ================== Gradio App ==================
145
 
146
+ def main_app(language, feature, grade, subject, num_students, date, slo, content):
147
+ if feature == "Lesson Plan":
148
+ result, file = generate_lesson_plan(language, grade, subject, num_students, date, slo, content)
149
+ return result, file, None, None
150
 
151
+ elif feature == "Flashcards":
152
+ result, file = generate_flashcards(language, grade, subject, slo, content)
153
+ return result, None, file, None
 
 
 
 
 
 
 
 
 
 
154
 
155
+ elif feature == "Quiz":
156
+ result, file = generate_quiz(language, grade, subject, slo, content)
157
+ return result, None, None, file
158
 
159
+ else:
160
+ return "Please select a valid feature.", None, None, None
 
161
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
 
163
+ # ================== UI Layout ==================
164
 
165
+ with gr.Blocks(title="SMART Lesson Plan Generator") as app:
166
+ gr.Markdown("<h1 style='text-align:center;'>📘 SMART LESSON PLAN GENERATOR</h1>")
 
 
167
 
168
  with gr.Row():
169
  language = gr.Dropdown(["English", "Urdu"], label="Select Language", value="English")
170
+ feature = gr.Dropdown(["Lesson Plan", "Flashcards", "Quiz"], label="Select Feature", value="Lesson Plan")
171
+
172
+ with gr.Row():
173
  grade = gr.Dropdown(
174
+ ["Grade 1", "Grade 2", "Grade 3", "Grade 4", "Grade 5", "Grade 6",
175
+ "Grade 7", "Grade 8", "Grade 9", "Grade 10", "Grade 11", "Grade 12"],
176
+ label="Select Class/Grade"
177
  )
178
  subject = gr.Dropdown(
179
+ ["English", "Urdu", "Mathematics", "Science", "Islamiyat", "Social Studies", "Computer Science"],
180
+ label="Select Subject"
 
 
 
 
 
181
  )
182
 
183
  with gr.Row():
184
+ num_students = gr.Number(label="Number of Students", value=30)
185
+ date = gr.Textbox(label="Date (YYYY-MM-DD)", value=str(datetime.date.today()))
 
186
 
187
+ slo = gr.Textbox(label="Enter SLOs (Learning Outcomes)", lines=3)
188
+ content = gr.Textbox(label="Enter Lesson Content Summary", lines=3)
 
 
189
 
190
+ generate_btn = gr.Button("🚀 Generate")
191
+ output_text = gr.Textbox(label="Generated Output", lines=20)
 
 
 
192
 
193
+ lesson_plan_file = gr.File(label="📄 Download Lesson Plan")
194
+ flashcard_file = gr.File(label="📘 Download Flashcards")
195
+ quiz_file = gr.File(label="🧾 Download Quiz")
196
 
 
197
  generate_btn.click(
198
+ main_app,
199
+ inputs=[language, feature, grade, subject, num_students, date, slo, content],
200
+ outputs=[output_text, lesson_plan_file, flashcard_file, quiz_file]
201
  )
202
 
203
+ app.launch()