Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,29 +1,23 @@
|
|
| 1 |
-
from smolagents import CodeAgent,
|
| 2 |
import datetime
|
| 3 |
-
import requests
|
| 4 |
-
import pytz
|
| 5 |
-
import yaml
|
| 6 |
-
import re
|
| 7 |
-
import tempfile
|
| 8 |
import os
|
| 9 |
import time
|
| 10 |
-
import shutil
|
| 11 |
from PIL import Image, ImageDraw, ImageFont
|
| 12 |
from tools.final_answer import FinalAnswerTool
|
| 13 |
-
from Gradio_UI import GradioUI
|
| 14 |
|
| 15 |
-
#
|
| 16 |
IMAGES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "coloring_images")
|
| 17 |
os.makedirs(IMAGES_DIR, exist_ok=True)
|
| 18 |
|
| 19 |
@tool
|
| 20 |
def generate_passover_coloring_pages(age: int) -> str:
|
| 21 |
-
"""
|
| 22 |
-
|
| 23 |
Args:
|
| 24 |
-
age
|
|
|
|
| 25 |
Returns:
|
| 26 |
-
|
| 27 |
"""
|
| 28 |
if not isinstance(age, int) or not (1 <= age <= 12):
|
| 29 |
return "Error: Please provide a valid age between 1 and 12."
|
|
@@ -40,87 +34,80 @@ def generate_passover_coloring_pages(age: int) -> str:
|
|
| 40 |
# Enhanced prompts specifically for Jewish Passover/Pesach themes
|
| 41 |
passover_pages = {
|
| 42 |
"simple": [
|
| 43 |
-
"
|
| 44 |
-
"
|
| 45 |
-
"
|
| 46 |
-
"
|
| 47 |
],
|
| 48 |
"basic": [
|
| 49 |
-
"
|
| 50 |
-
"
|
| 51 |
-
"
|
| 52 |
-
"Afikoman hunt maze
|
| 53 |
],
|
| 54 |
"intermediate": [
|
| 55 |
-
"
|
| 56 |
-
"Hebrew
|
| 57 |
-
"
|
| 58 |
-
"
|
| 59 |
],
|
| 60 |
"advanced": [
|
| 61 |
-
"
|
| 62 |
-
"
|
| 63 |
-
"
|
| 64 |
-
"
|
| 65 |
]
|
| 66 |
}
|
| 67 |
|
|
|
|
| 68 |
selected_pages = passover_pages[complexity]
|
| 69 |
-
descriptions = [page.split(',')[0] if ',' in page else page for page in selected_pages]
|
| 70 |
|
| 71 |
-
#
|
| 72 |
-
def create_placeholder_image(description, index):
|
| 73 |
-
img = Image.new('RGB', (800, 600), color='white')
|
| 74 |
-
draw = ImageDraw.Draw(img)
|
| 75 |
-
draw.rectangle([(10, 10), (790, 590)], outline='black', width=2)
|
| 76 |
-
|
| 77 |
-
# Add text
|
| 78 |
-
draw.text((400, 300), description.split(',')[0] if ',' in description else description,
|
| 79 |
-
fill='black', anchor='mm')
|
| 80 |
-
draw.text((400, 350), "Jewish Passover Coloring Page", fill='black', anchor='mm')
|
| 81 |
-
draw.text((400, 400), f"For age: {age}", fill='black', anchor='mm')
|
| 82 |
-
|
| 83 |
-
return img
|
| 84 |
-
|
| 85 |
-
# Generate and save images
|
| 86 |
image_paths = []
|
| 87 |
-
actual_files = []
|
| 88 |
timestamp = int(time.time())
|
| 89 |
|
| 90 |
try:
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
-
# Generate images
|
| 94 |
-
for i,
|
| 95 |
try:
|
| 96 |
-
|
|
|
|
| 97 |
img_filename = f"passover_{age}_{i}_{timestamp}.png"
|
| 98 |
img_path = os.path.join(IMAGES_DIR, img_filename)
|
| 99 |
img.save(img_path)
|
| 100 |
-
image_paths.append(img_path)
|
| 101 |
-
actual_files.append((img_filename, desc))
|
| 102 |
-
|
| 103 |
except Exception as e:
|
| 104 |
-
# Create placeholder if image generation fails
|
| 105 |
-
placeholder = create_placeholder_image(desc, i)
|
| 106 |
-
img_filename = f"passover_{age}_{i}_placeholder_{timestamp}.png"
|
| 107 |
-
img_path = os.path.join(IMAGES_DIR, img_filename)
|
| 108 |
-
placeholder.save(img_path)
|
| 109 |
-
image_paths.append(img_path)
|
| 110 |
-
actual_files.append((img_filename, desc))
|
| 111 |
print(f"Error generating image {i}: {str(e)}")
|
| 112 |
-
|
| 113 |
-
except
|
| 114 |
-
#
|
| 115 |
-
for i,
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
img_path = os.path.join(IMAGES_DIR, img_filename)
|
| 119 |
-
|
| 120 |
-
image_paths.append(img_path)
|
| 121 |
-
actual_files.append((img_filename, desc))
|
| 122 |
|
| 123 |
-
# Create a
|
| 124 |
html_filename = f"passover_coloring_pages_{age}_{timestamp}.html"
|
| 125 |
html_path = os.path.join(IMAGES_DIR, html_filename)
|
| 126 |
|
|
@@ -168,12 +155,12 @@ def generate_passover_coloring_pages(age: int) -> str:
|
|
| 168 |
</div>
|
| 169 |
""")
|
| 170 |
|
| 171 |
-
# Add each
|
| 172 |
-
for filename,
|
| 173 |
f.write(f"""
|
| 174 |
<div class="page">
|
| 175 |
-
<img src="{filename}" alt="{
|
| 176 |
-
<div class="page-title">{
|
| 177 |
</div>
|
| 178 |
""")
|
| 179 |
|
|
@@ -182,136 +169,55 @@ def generate_passover_coloring_pages(age: int) -> str:
|
|
| 182 |
</html>
|
| 183 |
""")
|
| 184 |
|
| 185 |
-
#
|
| 186 |
response = f"## Jewish Passover (Pesach) Coloring Pages for a {age}-year-old:\n\n"
|
| 187 |
-
response += "\n".join([f"- {desc}" for desc in
|
| 188 |
|
| 189 |
-
# Add information about the
|
| 190 |
response += f"\n\n**Coloring pages have been generated!**\n\n"
|
| 191 |
-
response += f"To print the coloring pages, please open this file in your web browser:\n\n"
|
| 192 |
response += f"{html_path}\n\n"
|
| 193 |
-
response += f"The individual image files are also available in the 'coloring_images' folder
|
|
|
|
| 194 |
|
| 195 |
-
|
| 196 |
-
image_paths_str = "||".join(image_paths)
|
| 197 |
-
return f"{response}\n\nIMAGE_PATHS:{image_paths_str}"
|
| 198 |
|
| 199 |
-
#
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
input_box = gr.Textbox(label="Enter child's age (1-12)")
|
| 217 |
-
submit_btn = gr.Button("Generate Coloring Pages")
|
| 218 |
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
output_text = gr.Markdown(label="Generated Pages")
|
| 222 |
-
|
| 223 |
-
with gr.Row():
|
| 224 |
-
gallery = gr.Gallery(label="Jewish Passover Coloring Pages", show_label=True)
|
| 225 |
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
if not (1 <= age <= 12):
|
| 231 |
-
return "Please enter a valid age between 1 and 12.", []
|
| 232 |
-
|
| 233 |
-
# Generate the coloring pages
|
| 234 |
-
result = generate_passover_coloring_pages(age)
|
| 235 |
-
|
| 236 |
-
# Extract image paths from the result
|
| 237 |
-
image_paths = []
|
| 238 |
-
if "IMAGE_PATHS:" in result:
|
| 239 |
-
paths_part = result.split("IMAGE_PATHS:")[1]
|
| 240 |
-
image_paths = paths_part.split("||")
|
| 241 |
-
# Remove the paths marker from the result
|
| 242 |
-
result = result.split("\n\nIMAGE_PATHS:")[0]
|
| 243 |
-
|
| 244 |
-
# If no paths found, look in the directory
|
| 245 |
-
if not image_paths:
|
| 246 |
-
for file in os.listdir(IMAGES_DIR):
|
| 247 |
-
if file.endswith('.png') and f"passover_{age}_" in file:
|
| 248 |
-
image_paths.append(os.path.join(IMAGES_DIR, file))
|
| 249 |
-
|
| 250 |
-
# Check that paths lead to real files
|
| 251 |
-
valid_image_paths = [path for path in image_paths if os.path.exists(path)]
|
| 252 |
-
|
| 253 |
-
# Return the result and image paths
|
| 254 |
-
return result, valid_image_paths
|
| 255 |
-
except ValueError:
|
| 256 |
-
return "Please enter a valid number for the child's age.", []
|
| 257 |
-
except Exception as e:
|
| 258 |
-
return f"Error: {str(e)}", []
|
| 259 |
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
# Modified prompt templates to handle simple age input
|
| 266 |
-
custom_prompt_templates = {
|
| 267 |
-
"react-system": """You are a helpful agent that helps children learn about Jewish Passover/Pesach through coloring pages.
|
| 268 |
-
You have access to the following tools:
|
| 269 |
-
|
| 270 |
-
{tools_string}
|
| 271 |
-
|
| 272 |
-
When a user enters a number between 1 and 12, interpret it as the age of a child and generate Jewish Passover coloring pages suitable for that age using the generate_passover_coloring_pages tool.
|
| 273 |
-
If you're asked to generate coloring pages or if the input is just a number, assume the user wants Jewish Passover coloring pages for a child of that age.
|
| 274 |
-
|
| 275 |
-
Important: Only generate authentic Jewish Passover (Pesach) symbols and imagery - including matzah, seder plate, haggadah, afikoman, four cups of wine, the exodus story, etc.
|
| 276 |
-
Do NOT include any Christian symbols or imagery like crosses, Jesus, or other non-Jewish religious elements.
|
| 277 |
-
|
| 278 |
-
To use a tool, output an action in this format:
|
| 279 |
-
```py
|
| 280 |
-
action = tool_name(arg1=value1, arg2=value2, ...)
|
| 281 |
-
```
|
| 282 |
-
|
| 283 |
-
Always use Python syntax for calling tools. After using a tool, analyze the result to determine what to do next. Use final_answer to return your answer when complete.
|
| 284 |
-
""",
|
| 285 |
-
"react-human": "{input_string}",
|
| 286 |
-
"react-assistant": "{agent_response}",
|
| 287 |
-
}
|
| 288 |
-
|
| 289 |
-
# Setup agent
|
| 290 |
-
final_answer = FinalAnswerTool()
|
| 291 |
-
|
| 292 |
-
model = HfApiModel(
|
| 293 |
-
max_tokens=2096,
|
| 294 |
-
temperature=0.5,
|
| 295 |
-
model_id='Qwen/Qwen2.5-Coder-32B-Instruct'
|
| 296 |
-
)
|
| 297 |
-
|
| 298 |
-
# Check if custom prompts should be used or merged with existing ones
|
| 299 |
-
try:
|
| 300 |
-
with open("prompts.yaml", 'r') as stream:
|
| 301 |
-
prompt_templates = yaml.safe_load(stream)
|
| 302 |
-
# Merge the templates, giving priority to our custom ones
|
| 303 |
-
prompt_templates.update(custom_prompt_templates)
|
| 304 |
-
except:
|
| 305 |
-
# If file doesn't exist or has issues, use our custom templates
|
| 306 |
-
prompt_templates = custom_prompt_templates
|
| 307 |
-
|
| 308 |
-
agent = CodeAgent(
|
| 309 |
-
model=model,
|
| 310 |
-
tools=[final_answer, generate_passover_coloring_pages],
|
| 311 |
-
max_steps=6,
|
| 312 |
-
verbosity_level=1,
|
| 313 |
-
prompt_templates=prompt_templates
|
| 314 |
-
)
|
| 315 |
|
| 316 |
-
|
| 317 |
-
|
|
|
|
| 1 |
+
from smolagents import CodeAgent, HfApiModel, tool
|
| 2 |
import datetime
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import os
|
| 4 |
import time
|
|
|
|
| 5 |
from PIL import Image, ImageDraw, ImageFont
|
| 6 |
from tools.final_answer import FinalAnswerTool
|
|
|
|
| 7 |
|
| 8 |
+
# Create directory for images
|
| 9 |
IMAGES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "coloring_images")
|
| 10 |
os.makedirs(IMAGES_DIR, exist_ok=True)
|
| 11 |
|
| 12 |
@tool
|
| 13 |
def generate_passover_coloring_pages(age: int) -> str:
|
| 14 |
+
"""Generates Jewish Passover/Pesach-themed coloring pages based on a child's age.
|
| 15 |
+
|
| 16 |
Args:
|
| 17 |
+
age: The age of the child (1-12).
|
| 18 |
+
|
| 19 |
Returns:
|
| 20 |
+
A list of suggested Passover-themed coloring pages.
|
| 21 |
"""
|
| 22 |
if not isinstance(age, int) or not (1 <= age <= 12):
|
| 23 |
return "Error: Please provide a valid age between 1 and 12."
|
|
|
|
| 34 |
# Enhanced prompts specifically for Jewish Passover/Pesach themes
|
| 35 |
passover_pages = {
|
| 36 |
"simple": [
|
| 37 |
+
"Matzah for Passover",
|
| 38 |
+
"Seder plate outline",
|
| 39 |
+
"Afikoman hidden in fabric",
|
| 40 |
+
"Kiddush cup for Passover"
|
| 41 |
],
|
| 42 |
"basic": [
|
| 43 |
+
"Moses parting the Red Sea",
|
| 44 |
+
"Ten Plagues illustrations",
|
| 45 |
+
"Four Questions from Haggadah",
|
| 46 |
+
"Afikoman hunt maze"
|
| 47 |
],
|
| 48 |
"intermediate": [
|
| 49 |
+
"Jewish Seder table with symbolic foods",
|
| 50 |
+
"Hebrew letters spelling 'Pesach'",
|
| 51 |
+
"Israelites leaving Egypt scene",
|
| 52 |
+
"Four Sons from the Haggadah"
|
| 53 |
],
|
| 54 |
"advanced": [
|
| 55 |
+
"Haggadah page with Seder order",
|
| 56 |
+
"Miriam and women celebrating after Red Sea",
|
| 57 |
+
"Hebrew calligraphy 'Next year in Jerusalem'",
|
| 58 |
+
"Passover journey from slavery to freedom"
|
| 59 |
]
|
| 60 |
}
|
| 61 |
|
| 62 |
+
# Get descriptions for selected age group
|
| 63 |
selected_pages = passover_pages[complexity]
|
|
|
|
| 64 |
|
| 65 |
+
# Generate placeholder images
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
image_paths = []
|
|
|
|
| 67 |
timestamp = int(time.time())
|
| 68 |
|
| 69 |
try:
|
| 70 |
+
# Try to import image generation tool if available
|
| 71 |
+
try:
|
| 72 |
+
from smolagents import load_tool
|
| 73 |
+
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
| 74 |
+
except:
|
| 75 |
+
# If tool can't be loaded, raise exception to use placeholders
|
| 76 |
+
raise ImportError("Image generation tool not available")
|
| 77 |
|
| 78 |
+
# Generate images with tool
|
| 79 |
+
for i, description in enumerate(selected_pages):
|
| 80 |
try:
|
| 81 |
+
prompt = f"{description}, Jewish traditional Passover symbols only, no Christian imagery, suitable for printing as a coloring page, black and white outline"
|
| 82 |
+
img = image_generation_tool(prompt)
|
| 83 |
img_filename = f"passover_{age}_{i}_{timestamp}.png"
|
| 84 |
img_path = os.path.join(IMAGES_DIR, img_filename)
|
| 85 |
img.save(img_path)
|
| 86 |
+
image_paths.append((img_path, img_filename, description))
|
|
|
|
|
|
|
| 87 |
except Exception as e:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
print(f"Error generating image {i}: {str(e)}")
|
| 89 |
+
raise
|
| 90 |
+
except:
|
| 91 |
+
# Create placeholder images
|
| 92 |
+
for i, description in enumerate(selected_pages):
|
| 93 |
+
img = Image.new('RGB', (800, 600), color='white')
|
| 94 |
+
draw = ImageDraw.Draw(img)
|
| 95 |
+
|
| 96 |
+
# Add a border
|
| 97 |
+
draw.rectangle([(10, 10), (790, 590)], outline='black', width=2)
|
| 98 |
+
|
| 99 |
+
# Write the description
|
| 100 |
+
draw.text((400, 300), description, fill='black', anchor='mm')
|
| 101 |
+
draw.text((400, 350), "Jewish Passover Coloring Page", fill='black', anchor='mm')
|
| 102 |
+
draw.text((400, 400), f"For age: {age}", fill='black', anchor='mm')
|
| 103 |
+
|
| 104 |
+
# Save the image
|
| 105 |
+
img_filename = f"passover_{age}_{i}_{timestamp}.png"
|
| 106 |
img_path = os.path.join(IMAGES_DIR, img_filename)
|
| 107 |
+
img.save(img_path)
|
| 108 |
+
image_paths.append((img_path, img_filename, description))
|
|
|
|
| 109 |
|
| 110 |
+
# Create a standalone HTML file to view images
|
| 111 |
html_filename = f"passover_coloring_pages_{age}_{timestamp}.html"
|
| 112 |
html_path = os.path.join(IMAGES_DIR, html_filename)
|
| 113 |
|
|
|
|
| 155 |
</div>
|
| 156 |
""")
|
| 157 |
|
| 158 |
+
# Add each image to the HTML
|
| 159 |
+
for _, filename, description in image_paths:
|
| 160 |
f.write(f"""
|
| 161 |
<div class="page">
|
| 162 |
+
<img src="{filename}" alt="{description}">
|
| 163 |
+
<div class="page-title">{description}</div>
|
| 164 |
</div>
|
| 165 |
""")
|
| 166 |
|
|
|
|
| 169 |
</html>
|
| 170 |
""")
|
| 171 |
|
| 172 |
+
# Return formatted response
|
| 173 |
response = f"## Jewish Passover (Pesach) Coloring Pages for a {age}-year-old:\n\n"
|
| 174 |
+
response += "\n".join([f"- {desc}" for desc in selected_pages])
|
| 175 |
|
| 176 |
+
# Add information about the HTML viewer
|
| 177 |
response += f"\n\n**Coloring pages have been generated!**\n\n"
|
| 178 |
+
response += f"To view and print the coloring pages, please open this file in your web browser:\n\n"
|
| 179 |
response += f"{html_path}\n\n"
|
| 180 |
+
response += f"The individual image files are also available in the 'coloring_images' folder:\n"
|
| 181 |
+
response += "\n".join([f"- {os.path.basename(path)}" for path, _, _ in image_paths])
|
| 182 |
|
| 183 |
+
return response
|
|
|
|
|
|
|
| 184 |
|
| 185 |
+
# Create a simple standalone command-line application
|
| 186 |
+
def main():
|
| 187 |
+
print("===== Jewish Passover Coloring Pages Generator =====")
|
| 188 |
+
print("\nThis program creates coloring pages for children to learn about Passover")
|
| 189 |
+
|
| 190 |
+
while True:
|
| 191 |
+
try:
|
| 192 |
+
print("\nEnter a child's age (1-12) or 'q' to quit:")
|
| 193 |
+
user_input = input("> ").strip().lower()
|
| 194 |
+
|
| 195 |
+
if user_input == 'q':
|
| 196 |
+
print("\nThank you for using the Passover Coloring Pages Generator!")
|
| 197 |
+
break
|
| 198 |
+
|
| 199 |
+
try:
|
| 200 |
+
age = int(user_input)
|
| 201 |
+
if not (1 <= age <= 12):
|
| 202 |
+
print("Please enter a valid age between 1 and 12.")
|
| 203 |
+
continue
|
| 204 |
|
| 205 |
+
print(f"\nGenerating coloring pages for age {age}...")
|
| 206 |
+
result = generate_passover_coloring_pages(age)
|
|
|
|
|
|
|
| 207 |
|
| 208 |
+
print("\n" + result)
|
| 209 |
+
print("\nGeneration complete! Please check the 'coloring_images' folder.")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
|
| 211 |
+
except ValueError:
|
| 212 |
+
print("Please enter a valid number for the age.")
|
| 213 |
+
except Exception as e:
|
| 214 |
+
print(f"Error: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
|
| 216 |
+
except KeyboardInterrupt:
|
| 217 |
+
print("\n\nProgram terminated by user.")
|
| 218 |
+
break
|
| 219 |
+
except Exception as e:
|
| 220 |
+
print(f"\nUnexpected error: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
|
| 222 |
+
if __name__ == "__main__":
|
| 223 |
+
main()
|