Repository navigation
Expand file tree
/
Copy pathlevel_generator.py
More file actions
300 lines (249 loc) · 11.1 KB
/
Copy pathlevel_generator.py
File metadata and controls
300 lines (249 loc) · 11.1 KB
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import os
import json
import requests
# import google.generativeai as genai
from google import genai # Updated import for Google Gemini API
import xml.etree.ElementTree as ET # Added for XML parsing
import copy # Added for deep copying templates
import datetime # Added for setting new timestamps
from dotenv import load_dotenv
from google.genai import types
from pydantic import BaseModel, Field
from typing import List
# Load environment variables from backend/.env file
load_dotenv(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'backend', '.env'))
# --- Configuration ---
# IMPORTANT: Set your API Key
# For security, it's best to set this as an environment variable.
# You can get your key from Google AI Studio: https://aistudio.google.com/app/apikey
try:
# Attempt to get the API key from an environment variable
GEMINI_API_KEY = os.environ['GEMINI_API_KEY']
#genai.configure(api_key=GEMINI_API_KEY)
client = genai.Client(api_key=GEMINI_API_KEY)
#print("API Key successfully configured.")
except KeyError:
print("="*80)
print("ERROR: GEMINI_API_KEY environment variable not set.")
print("Please set this variable with your Google AI Studio API key.")
print("Example (Linux/macOS): export GEMINI_API_KEY='your_key_here'")
print("Example (Windows CMD): set GEMINI_API_KEY=your_key_here")
print("Example (Windows PowerShell): $env:GEMINI_API_KEY='your_key_here'")
print("="*80)
exit(1) # Exit if key is not found
MODEL_ID = "gemini-2.5-flash"
# --- Structured Output ---
# 1. Define the structure for a single JSON object (an item in the list)
class CodeProblem(BaseModel):
"""A single coding problem containing instructions and starter code."""
instructions: str = Field(description="The full, detailed instructions for the coding problem in markdown format.")
starter_code: str = Field(description="The initial, partial code that the user needs to complete.")
# 2. Define the overall structure (a list of CodeProblem objects)
class CodeProblemList(BaseModel):
"""A list of one or more coding problems."""
problems: List[CodeProblem]
# --- Core Functions ---
def fetch_all_levels(levels: list[dict]) -> list[dict]:
all_levels_data = []
all_levels = []
for level in levels:
name = level.get("name")
type = level.get("type", "level")
if(type.lower() == "bubble_choice"):
# fetch the content of the bubble choice level,
# iterate through each line,
# if a line starts with "level":
# extract the text in '' after level,
# then append that level name to the levels array with type "level"
lines = fetch_file_content(name, type).splitlines()
for line in lines:
if line.strip().startswith("level"):
start = line.find("'") + 1
end = line.find("'", start)
sub_level_name = line[start:end].strip()
print(sub_level_name)
all_levels.append({"name": sub_level_name, "type": "level"})
else:
all_levels.append(level)
print(all_levels)
for level in all_levels:
name = level.get("name")
type = level.get("type", "level")
content = fetch_file_content(name, type)
if content:
level_data = extract_json_properties(content)
if level_data:
all_levels_data.append(level_data)
return all_levels_data
def fetch_file_content(name: str, type: str) -> str | None:
"""
Given the level name from a level on levelbuilder and the type (either "level" or "bubble_choice"):
- If a level, retrieves the instructions and starter code
- If the level is a choice level, iterates through sub-levels and retrieves instructions and starter code
Args:
name: name of level. If bubble_choice, convert all dashes to underscores
type: level or bubble_choice
Returns:
instructions and starter code pairs in array
"""
# LEVELURL: "https://raw.githubusercontent.com/code-dot-org/code-dot-org/refs/heads/staging/dashboard/config/levels/custom/pythonlab/{level_name}.level"
# BUBBLEURL: "https://raw.githubusercontent.com/code-dot-org/code-dot-org/refs/heads/staging/dashboard/config/scripts/{level_name_with_dashes_removed}.bubble_choice"
if type.lower() == "level":
url = f"https://raw.githubusercontent.com/code-dot-org/code-dot-org/refs/heads/staging/dashboard/config/levels/custom/pythonlab/{name}.level"
elif type.lower() == "bubble_choice":
# Convert dashes to underscores
name_no_dashes = name.replace("-", "_")
url = f"https://raw.githubusercontent.com/code-dot-org/code-dot-org/refs/heads/staging/dashboard/config/scripts/{name_no_dashes}.bubble_choice"
else:
print("Invalid type specified. Must be 'level' or 'bubble_choice'.")
return None
print(f"Fetching file from: {url}")
try:
response = requests.get(url)
# Raise an exception for bad status codes (4xx or 5xx)
response.raise_for_status()
return response.text
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
except requests.exceptions.RequestException as err:
print(f"An error occurred: {err}")
return None
def extract_json_properties(content: str) -> dict | None:
"""
Parses an XML string, finds the <config> tag, extracts the
CDATA JSON content, and returns it as a parsed dictionary.
Args:
content: A string containing the .pythonlab XML data.
Returns:
A dictionary parsed from the inner JSON, or None if parsing fails.
"""
try:
# Parse the XML
root = ET.fromstring(content)
# Find the <config> tag
config_tag = root.find('config')
if config_tag is None:
print("Error: No <config> tag found in XML.")
return None
# The text inside the tag is the CDATA content
cdata_content = config_tag.text
if cdata_content is None:
print("Error: <config> tag is empty.")
return None
# Parse the JSON content
full_json_data = json.loads(cdata_content)
#return data
try:
#get long instructions
props = full_json_data.get("properties", {})
instructions = props.get("long_instructions", "")
#find the main.py file key
files_dict = props.get("start_sources", {}).get("files", {})
main_key = None
for key, file_data in files_dict.items():
if isinstance(file_data, dict) and file_data.get("name") == "main.py":
main_key = key
#get the code from the main.py file
code = None
if main_key and main_key in files_dict:
code = files_dict[main_key].get("contents", "")
if instructions and code:
return {
"instructions": instructions,
"starter_code": code
}
else:
return None
except Exception as e:
print(f"Error extracting specific properties: {e}")
except ET.ParseError as xml_err:
print(f"Error: Failed to parse XML: {xml_err}")
except json.JSONDecodeError as json_err:
print(f"Error: Failed to decode JSON from CDATA: {json_err}")
return None
def analyze_and_generate_file(all_levels: list[dict]) -> str | None:
"""
Uses the Gemini API to analyze example JSONs and generate a new, similar one.
Args:
example_json_objects: A list of dictionaries, each representing
a parsed JSON file.
Returns:
A string containing the new, generated JSON, or None if an error occurs.
"""
#print("Connecting to Gemini API to generate new file...")
#json_strings = json.dumps(all_levels, indent=2)
# --- The Prompt ---
# This is where you instruct the model.
# We provide the examples and ask it to generate a new one.
prompt_parts = [
"You are helping generate student tasks for an introductory programming course in Python",
"I am providing examples of existing tasks. Each example is in a JSON format containing both 'instructions' that students see, and 'starter_code' that they are given to begin the task ",
"You are to generate three new examples using the same style and addressing the same concept, but in a different context"
"Your response should be structured similarly as a JSON object with 'instructions' and 'starter_code'"
"\n--- EXAMPLES ---",
]
# Add each example to the prompt
prompt_parts.append(json.dumps(all_levels, indent=2))
prompt_parts.append("\n--- END OF EXAMPLES ---")
prompt = "\n".join(prompt_parts)
print(prompt)
contents = [
types.Content(
role="user",
parts=[
types.Part.from_text(text=prompt),
],
),
]
try:
# --- API Call ---
# We use the 'gemini-2.5-flash-preview-09-2025' model as requested
#model = genai.GenerativeModel('gemini-2.5-flash')
#response = model.generate_content(prompt)
response = client.models.generate_content(
model=MODEL_ID,
contents=contents,
config=types.GenerateContentConfig(
response_mime_type="application/json",
response_schema=CodeProblemList
)
)
generated_text = response.text #string
# print(generated_text)
try:
data = CodeProblemList.model_validate_json(generated_text)
# json.loads(generated_text)
print("Gemini API returned valid JSON.")
return generated_text
except Exception as e:
print(f"\nError parsing JSON: {e}")
return None
except Exception as e:
print(f"An error occurred while calling the Gemini API: {e}")
return None
def save_file(folder_name: str, file_name: str, content: str):
"""
Saves the given content to a file in the specified folder.
Args:
folder_name: The name of the folder (will be created if it doesn't exist).
file_name: The name for the new file.
content: The text content to write to the file.
"""
try:
# Create the folder if it doesn't exist
os.makedirs(folder_name, exist_ok=True)
# Create the full file path
full_path = os.path.join(folder_name, file_name)
# Write the content to the file
with open(full_path, 'w', encoding='utf-8') as f:
f.write(content)
print(f"Successfully saved new file to: {full_path}")
except OSError as e:
print(f"Error creating directory or saving file: {e}")
except Exception as e:
print(f"An unexpected error occurred during file save: {e}")
# --- Main Application Logic ---
def main():
exit(1)
if __name__ == "__main__":
main()