File size: 10,232 Bytes
8f44461
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8a68fe
8f44461
 
 
 
 
 
c8a68fe
 
 
 
 
 
 
 
 
 
8f44461
 
c8a68fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f44461
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e9ae72
8f44461
 
 
 
c2db989
8f44461
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import gradio as gr
import PyPDF2
from pptx import Presentation
from PIL import Image
import io
from google import genai
from jinja2 import Template
import fitz  # PyMuPDF
import os
import logging
import re
import time

# Set up logging
logging.basicConfig(level=logging.INFO)

# Function to extract content from PDF
def extract_content_from_pdf(file_path):
    try:
        text = ""
        images = []
        doc = fitz.open(file_path)
        for page in doc:
            text += page.get_text() + "\n"
            for img in page.get_images():
                xref = img[0]
                base_image = doc.extract_image(xref)
                image_bytes = base_image["image"]
                image = Image.open(io.BytesIO(image_bytes))
                images.append(image)
        return text, images
    except Exception as e:
        logging.error(f"Error extracting content from PDF: {e}")
        return "", []

# Function to extract content from PPTX
def extract_content_from_pptx(file_path):
    try:
        text = ""
        images = []
        prs = Presentation(file_path)
        for slide in prs.slides:
            for shape in slide.shapes:
                if hasattr(shape, 'text'):
                    text += shape.text + "\n"
                if shape.shape_type == 13:  # Picture
                    image = shape.image
                    image_bytes = image.blob
                    image = Image.open(io.BytesIO(image_bytes))
                    images.append(image)
        return text, images
    except Exception as e:
        logging.error(f"Error extracting content from PPTX: {e}")
        return "", []

# Function to process file
def process_file(file_path):
    if file_path is None:
        return "No file uploaded", []

    try:
        if file_path.lower().endswith('.pdf'):
            return extract_content_from_pdf(file_path)
        elif file_path.lower().endswith('.pptx'):
            return extract_content_from_pptx(file_path)
        else:
            return "Unsupported file format", []
    except Exception as e:
        logging.error(f"Error processing file: {e}")
        return f"An error occurred while processing the file: {str(e)}", []

# Function to clean response
def clean_response(response_text):
    # Remove code block markers if present
    cleaned = re.sub(r'```python|```', '', response_text).strip()
    # Handle newlines and indentation
    cleaned = re.sub(r'\n\s*\n', '\n\n', cleaned)
    return cleaned

# Function to understand text and images using Gemini V2 API
def understand_content(api_key, text, images, progress=gr.Progress()):
    try:
        # Initialize the Gemini client
        client = genai.Client(api_key=api_key)

        progress(0.3, desc="Preparing content...")
        # Prepare content for Gemini
        content = [text]
        for image in images[:10]:  # Limit to 10 images
            content.append(image)

        progress(0.5, desc="Generating unit plan...")
        # Generate response from Gemini
        prompt = """
You are an expert instructional designer.
Below are materials shared by a teacher. Your role is to reverse-engineer the unit planner for this content.
To do so:
1) Read the content carefully
2) Create a unit planner for this content that follows this exact structure:
# Standards
- If the subject is English, use Common Core
- If the subject is Spanish use Common Core
- If the subject is Social Studies, use AERO
- If the subject is Mathematics, use AERO
- If the subject is Science, use NGSS
# Transfer Goal (This answers: "Why are we learning this?" How will students transfer their learning in "real-life" and in the future?)
# Essential Questions (What are the key questions that students will be  asking, exploring, and answering, through this unit?)
# Enduring Understandings (This is the "U" in KUD and helps students answer the essential questions by connecting concepts.Students will understand that [connections between key concepts] and why [connections between key concepts])
# Students will know (This is the "K" in KUD, the content that students will use and process to construct concepts (the building blocks of understandings). Students will know [fact, formula, definition…])
# Students will be able to (This is the "D" in KUD, the skills that students will develop and use to process knowledge, concepts, understandings, and answer the essential questions. These skills should be connected to the command terms.)
# Formative Assessments
# Summative Assessments
# Scope and Sequence (This is a description of the overall flow of the unit. It includes an assessment plan and brief lesson objectives (along the learning scale and towards the summative)
# Unit Overview (This is a brief summation of everything above. What will students be learning, and why? How will they progressively develop and demonstrate their learning?)
# Potential barriers (This dentifies potential barriers to student learning)
# Connections 
## Connections to ISP Core Values
- Commitment to Excellence
- Strength in Diversity
- Compassion and Integrity
- Innovative Spirit
- Lasting Impact
## Connections to IB Theory of Knowledge
## Connections to IB Approaches to Learning (when relevant)
- Collaboration
- Communication
- Affective skills
- Reflection skills
- Information and media literacy skills
- Critical thinking skills
- Creative thinking skills
# Authentic Assessment : In addition to existing assessments, propose a potential GRASPS assessment:
Goal - Assign an authentic (real-life), exciting (challenging), and meaningful (relatable, impactful) project or problem to solve
Role - Give students an authentic, exciting, and meaningful role to play (e.g., acting as a journalist, a business consultant…)
Audience - Identify an authentic, exciting, and meaningful audience that students can serve and/or that can experience their product or performance
Situation - Create an authentic, exciting, and meaningful scenario or context for the project, product, or performance
Project/Product/Performance and Progress - Clarify what students are expected to do and how. This includes a plan that matches the learning scale and structures the scope and sequence of the unit (below). This also includes milestones and practice (formatives), as well as feedback and opportunities for reflection and revision.
Success Criteria - Provide a task-specific version of the learning scales, along with benchmark sheets
"""

        response = client.models.generate_content(
            model="gemini-2.0-flash-exp",
            contents=prompt + text
        )

        progress(0.8, desc="Finalizing output...")
        # Log the raw response for debugging
        response_text = response.text
        logging.info(f"Raw response from Gemini: {response_text}")

        # Clean the response
        cleaned_response = clean_response(response_text)
        logging.info(f"Cleaned response: {cleaned_response}")

        progress(1.0, desc="Complete!")
        return cleaned_response

    except Exception as e:
        logging.error(f"Error in content understanding: {e}")
        return f"Error in processing the content: {str(e)}. Please check your API key and try again."

# Function to reverse engineer unit plan
def generate_elt_plan(api_key, file, progress=gr.Progress()):
    if not api_key:
        return "Please enter your Gemini API key", None

    try:
        progress(0.1, desc="Starting file processing...")
        logging.info(f"Processing file: {file.name}")
        content, images = process_file(file.name)
        if isinstance(content, str) and content.startswith("An error occurred"):
            return content, None
        logging.info(f"Extracted content length: {len(content)}, Number of images: {len(images)}")
        progress(0.2, desc="Content extracted, generating plan...")
        elt_plan = understand_content(api_key, content, images, progress)

        # Create a downloadable text file
        timestamp = time.strftime("%Y%m%d-%H%M%S")
        filename = f"unit_plan_{timestamp}.txt"
        with open(filename, "w", encoding="utf-8") as f:
            f.write(elt_plan)

        return elt_plan, filename
    except Exception as e:
        logging.error(f"Error in generate_elt_plan: {e}")
        return f"An error occurred: {str(e)}", None

# Set up Gradio Blocks
with gr.Blocks() as demo:
    gr.Markdown("# 🔄 Reverse Unit Planner 2.0")

    with gr.Row():
        with gr.Column():
            api_key = gr.Textbox(label="Enter your Gemini API key", type="password")
            file_input = gr.Files(label="Upload PPTX or PDF")
            submit_btn = gr.Button("Reverse engineer a unit plan", variant="primary")

        with gr.Column():
            output = gr.Markdown(label="Draft Unit Planner")
            copy_btn = gr.Button("📋 Copy to Clipboard")
            download_btn = gr.File(label="Download Unit Plan")

    # Handle the main processing
    result = submit_btn.click(
        generate_elt_plan,
        inputs=[api_key, file_input],
        outputs=[output, download_btn]
    )

    # Add copy to clipboard functionality
    copy_btn.click(
        fn=None,
        inputs=output,
        outputs=None,
        js="""
        async (text) => {
            await navigator.clipboard.writeText(text);
            await new Promise(resolve => {
                const notification = document.createElement('div');
                notification.textContent = 'Copied to clipboard!';
                notification.style.position = 'fixed';
                notification.style.bottom = '20px';
                notification.style.left = '50%';
                notification.style.transform = 'translateX(-50%)';
                notification.style.backgroundColor = '#4CAF50';
                notification.style.color = 'white';
                notification.style.padding = '10px 20px';
                notification.style.borderRadius = '5px';
                notification.style.zIndex = '1000';
                document.body.appendChild(notification);
                setTimeout(() => {
                    notification.remove();
                    resolve();
                }, 2000);
            });
        }
    """)

# Launch the app
demo.launch()