Turbiling commited on
Commit
d75d2fd
·
verified ·
1 Parent(s): d8d120d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -88
app.py CHANGED
@@ -1,116 +1,93 @@
1
  import os
2
- import requests
3
  import gradio as gr
4
  from docx import Document
5
- from docx.shared import Pt
6
  import datetime
 
7
 
8
- # Groq API Key (replace with your own if not using environment variable)
9
- GROQ_API_KEY = os.getenv("GROQ_API_KEY", "your_groq_api_key_here") # replace this before deploying
10
- GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
11
 
12
- def generate_lesson_plan(class_level, subject, topic, students, duration, date, teacher):
 
 
 
13
  prompt = f"""
14
- Create a complete lesson plan using the BOPPPS model.
15
-
16
- Details:
17
- - Class: {class_level}
18
- - Subject: {subject}
19
- - Topic: {topic}
20
- - Number of students: {students}
21
- - Duration: {duration} minutes
22
- - Date: {date}
23
- - Teacher Name: {teacher}
24
-
25
- Include the following in proper sequence:
26
- 1. **Bridge-In**: Introduction to grab students' attention related to the topic.
27
- 2. **Objectives**: Three specific learning objectives.
28
- 3. **Pre-Assessment**: Two questions to assess prior knowledge related to the topic.
29
- 4. **Participatory Learning**: Detailed instruction for interactive/participatory learning.
30
- 5. **Post-Assessment**: Questions or activities to evaluate understanding.
31
- 6. **Summary**: Wrap-up by the teacher, summarizing key points of the lesson.
32
-
33
- Output must be in proper English and suitable for inclusion in a Word document.
34
- """
35
 
36
- headers = {
37
- "Authorization": f"Bearer {GROQ_API_KEY}",
38
- "Content-Type": "application/json"
39
- }
40
 
41
- body = {
42
- "model": "llama3-8b-8192",
43
- "messages": [{"role": "user", "content": prompt}],
44
- "temperature": 0.7
45
- }
 
 
 
 
46
 
47
  try:
48
- response = requests.post(GROQ_API_URL, headers=headers, json=body)
49
- response.raise_for_status()
50
- result = response.json()
51
- lesson_plan = result["choices"][0]["message"]["content"]
 
 
52
 
53
- # Create Word document
54
  doc = Document()
55
- doc.add_heading("Lesson Plan (BOPPPS Model)", 0)
56
-
57
- # Add table at the top
58
- table = doc.add_table(rows=6, cols=2)
59
- table.style = 'Table Grid'
60
-
61
- entries = [
62
- ("Class Level", class_level),
63
- ("Subject", subject),
64
- ("Topic", topic),
65
- ("Number of Students", str(students)),
66
- ("Duration", f"{duration} minutes"),
67
- ("Date & Teacher", f"{date} | {teacher}")
68
- ]
69
-
70
- for i, (label, value) in enumerate(entries):
71
- table.cell(i, 0).text = label
72
- table.cell(i, 1).text = value
73
-
74
- # Optional styling
75
- for cell in table.row_cells(i):
76
- for paragraph in cell.paragraphs:
77
- for run in paragraph.runs:
78
- run.font.size = Pt(11)
79
-
80
- doc.add_paragraph("\n") # spacing
81
- doc.add_paragraph(lesson_plan)
82
-
83
- filename = f"LessonPlan_{topic.replace(' ', '_')}_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.docx"
84
- filepath = os.path.join("/tmp", filename)
85
  doc.save(filepath)
86
-
87
  return filepath
88
-
89
- except requests.exceptions.RequestException as e:
90
- return f"API request failed: {str(e)}"
91
- except Exception as ex:
92
- return f"Error generating lesson plan: {str(ex)}"
93
 
94
  # Gradio UI
95
  with gr.Blocks() as demo:
96
- gr.Markdown("## 📘 BOPPPS Lesson Plan Generator\nCreate complete lesson plans powered by Groq + LLaMA3.")
97
 
98
  with gr.Row():
99
- class_level = gr.Textbox(label="Class Level (e.g. Grade 6)")
100
- subject = gr.Textbox(label="Subject (e.g. Science)")
101
- topic = gr.Textbox(label="Topic (e.g. Water Cycle)")
102
- students = gr.Number(label="Number of Students", precision=0)
103
- duration = gr.Number(label="Duration (minutes)", precision=0)
104
- date = gr.Textbox(label="Date (e.g. 2025-05-25)")
 
 
105
  teacher = gr.Textbox(label="Teacher Name")
106
 
107
- generate_button = gr.Button("Generate Lesson Plan")
108
- output_file = gr.File(label="⬇️ Download Lesson Plan (Word)")
109
 
110
- generate_button.click(
111
  fn=generate_lesson_plan,
112
- inputs=[class_level, subject, topic, students, duration, date, teacher],
113
  outputs=output_file
114
  )
115
 
116
  demo.launch()
 
 
1
  import os
 
2
  import gradio as gr
3
  from docx import Document
 
4
  import datetime
5
+ from groq import Groq
6
 
7
+ # Load Groq API key
8
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY") # Set this in Hugging Face secrets
 
9
 
10
+ client = Groq(api_key=GROQ_API_KEY)
11
+
12
+ def generate_lesson_plan(class_, subject, topic, students, duration, date, teacher):
13
+ # Construct the prompt — instruct model NOT to repeat inputs
14
  prompt = f"""
15
+ You are an expert lesson plan developer.
16
+
17
+ Write ONLY the **lesson body** using the BOPPPS model for the topic: "{topic}".
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
+ Do NOT restate these inputs (class, subject, topic, date, teacher name, etc.) — only write the lesson content.
 
 
 
20
 
21
+ The plan must be in English and include the following:
22
+
23
+ 1. **Bridge-In**: A short paragraph that introduces the topic engagingly.
24
+ 2. **Learning Objectives**: List 3 clear objectives.
25
+ 3. **Pre-Assessment Questions**: Write 2 questions to assess prior knowledge.
26
+ 4. **Participatory Learning**: Describe an engaging activity.
27
+ 5. **Post-Assessment**: 2–3 questions to evaluate student understanding.
28
+ 6. **Summary**: A concluding paragraph by the teacher.
29
+ """
30
 
31
  try:
32
+ response = client.chat.completions.create(
33
+ model="llama3-8b-8192",
34
+ messages=[{"role": "user", "content": prompt}],
35
+ temperature=0.7,
36
+ )
37
+ lesson_text = response.choices[0].message.content
38
 
 
39
  doc = Document()
40
+ doc.add_heading(f"BOPPPS Lesson Plan - {topic}", 0)
41
+
42
+ # Table for metadata (not repeated in content)
43
+ table = doc.add_table(rows=0, cols=2)
44
+ fields = {
45
+ "Class": class_,
46
+ "Subject": subject,
47
+ "Topic": topic,
48
+ "No. of Students": students,
49
+ "Duration": duration,
50
+ "Date": date,
51
+ "Teacher Name": teacher
52
+ }
53
+ for key, value in fields.items():
54
+ row_cells = table.add_row().cells
55
+ row_cells[0].text = key
56
+ row_cells[1].text = value
57
+
58
+ doc.add_paragraph("\n") # space after table
59
+ doc.add_paragraph(lesson_text)
60
+
61
+ filename = f"lesson_plan_{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}.docx"
62
+ filepath = f"/tmp/{filename}"
 
 
 
 
 
 
 
63
  doc.save(filepath)
 
64
  return filepath
65
+ except Exception as e:
66
+ return f"Error: {e}"
 
 
 
67
 
68
  # Gradio UI
69
  with gr.Blocks() as demo:
70
+ gr.Markdown("## 📘 BOPPPS Lesson Plan Generator (English Only)")
71
 
72
  with gr.Row():
73
+ class_ = gr.Textbox(label="Class")
74
+ subject = gr.Textbox(label="Subject")
75
+ topic = gr.Textbox(label="Topic")
76
+
77
+ with gr.Row():
78
+ students = gr.Textbox(label="Number of Students")
79
+ duration = gr.Textbox(label="Duration (in minutes)")
80
+ date = gr.Textbox(label="Date")
81
  teacher = gr.Textbox(label="Teacher Name")
82
 
83
+ generate_btn = gr.Button("Generate Lesson Plan")
84
+ output_file = gr.File(label="Download Lesson Plan")
85
 
86
+ generate_btn.click(
87
  fn=generate_lesson_plan,
88
+ inputs=[class_, subject, topic, students, duration, date, teacher],
89
  outputs=output_file
90
  )
91
 
92
  demo.launch()
93
+