Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,45 +1,202 @@
|
|
| 1 |
-
from smolagents import CodeAgent, HfApiModel, load_tool, tool
|
|
|
|
|
|
|
|
|
|
| 2 |
import yaml
|
|
|
|
|
|
|
|
|
|
| 3 |
from tools.final_answer import FinalAnswerTool
|
| 4 |
from Gradio_UI import GradioUI
|
| 5 |
|
| 6 |
@tool
|
| 7 |
-
def
|
| 8 |
-
"""
|
|
|
|
| 9 |
Args:
|
| 10 |
-
|
| 11 |
Returns:
|
| 12 |
-
A
|
| 13 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
try:
|
| 15 |
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
except Exception as e:
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
|
|
|
| 21 |
final_answer = FinalAnswerTool()
|
| 22 |
|
| 23 |
model = HfApiModel(
|
| 24 |
max_tokens=2096,
|
| 25 |
temperature=0.5,
|
| 26 |
-
model_id='Qwen/Qwen2.5-Coder-32B-Instruct'
|
| 27 |
-
custom_role_conversions=None,
|
| 28 |
)
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
agent = CodeAgent(
|
| 34 |
model=model,
|
| 35 |
-
tools=[final_answer,
|
| 36 |
max_steps=6,
|
| 37 |
verbosity_level=1,
|
| 38 |
-
grammar=None,
|
| 39 |
-
planning_interval=None,
|
| 40 |
-
name=None,
|
| 41 |
-
description=None,
|
| 42 |
prompt_templates=prompt_templates
|
| 43 |
)
|
| 44 |
|
| 45 |
-
|
|
|
|
|
|
| 1 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
|
| 2 |
+
import datetime
|
| 3 |
+
import requests
|
| 4 |
+
import pytz
|
| 5 |
import yaml
|
| 6 |
+
import re
|
| 7 |
+
import tempfile
|
| 8 |
+
import os
|
| 9 |
from tools.final_answer import FinalAnswerTool
|
| 10 |
from Gradio_UI import GradioUI
|
| 11 |
|
| 12 |
@tool
|
| 13 |
+
def generate_passover_coloring_pages(age: int) -> str:
|
| 14 |
+
"""
|
| 15 |
+
Generates Passover-themed coloring pages based on a child's age.
|
| 16 |
Args:
|
| 17 |
+
age (int): The age of the child (1-12).
|
| 18 |
Returns:
|
| 19 |
+
str: A list of suggested Passover-themed coloring pages.
|
| 20 |
"""
|
| 21 |
+
if not isinstance(age, int) or not (1 <= age <= 12):
|
| 22 |
+
return "Error: Please provide a valid age between 1 and 12."
|
| 23 |
+
|
| 24 |
+
complexity_levels = {
|
| 25 |
+
(1, 3): "simple",
|
| 26 |
+
(4, 6): "basic",
|
| 27 |
+
(7, 9): "intermediate",
|
| 28 |
+
(10, 12): "advanced"
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
complexity = next(value for (low, high), value in complexity_levels.items() if low <= age <= high)
|
| 32 |
+
|
| 33 |
+
# Enhanced prompts for better coloring pages
|
| 34 |
+
passover_pages = {
|
| 35 |
+
"simple": [
|
| 36 |
+
"Line drawing of a matzah for a simple coloring page, thick black outlines, white background, perfect for a child's coloring book",
|
| 37 |
+
"Simple black and white outline of a Seder plate with clear divisions, coloring book style, thick lines",
|
| 38 |
+
"Black and white line art of baby Moses in a basket for a child's coloring book, simple outlines",
|
| 39 |
+
"Simple black and white outline of a frog (plague) for children's coloring book, thick lines, no shading"
|
| 40 |
+
],
|
| 41 |
+
"basic": [
|
| 42 |
+
"Black and white outline of the Parting of the Red Sea scene for a coloring book, clear distinct lines",
|
| 43 |
+
"Coloring book page with Ten Plagues illustrations, black outline on white background, no shading",
|
| 44 |
+
"Black and white outline illustrations of the Four Questions for a Passover coloring book",
|
| 45 |
+
"Afikoman hunt maze in black and white outline for a coloring book, thick lines"
|
| 46 |
+
],
|
| 47 |
+
"intermediate": [
|
| 48 |
+
"Detailed black and white outline of a Seder table for a coloring book, clear distinct elements",
|
| 49 |
+
"Black and white outline of Exodus story scenes for coloring book, clear lines",
|
| 50 |
+
"Hebrew letter decorations for 'Pesach' in black and white outline style for coloring book",
|
| 51 |
+
"Black and white outline of Egyptian pyramids with Israelites for a coloring book"
|
| 52 |
+
],
|
| 53 |
+
"advanced": [
|
| 54 |
+
"Intricate black and white line art of Haggadah illustrations for a coloring book, detailed outlines",
|
| 55 |
+
"Detailed symbolism scene in black and white outline for an advanced coloring book",
|
| 56 |
+
"Combined Passover story panels in black and white line art for coloring book",
|
| 57 |
+
"Hebrew calligraphy art in black and white outline for a coloring book, intricate details"
|
| 58 |
+
]
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
selected_pages = passover_pages[complexity]
|
| 62 |
+
descriptions = [f"- {page.split(',')[0]}" for page in selected_pages]
|
| 63 |
+
|
| 64 |
+
# Try to generate images with improved prompts
|
| 65 |
try:
|
| 66 |
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
| 67 |
+
|
| 68 |
+
# Use more specific prompts for coloring pages
|
| 69 |
+
enhanced_prompts = []
|
| 70 |
+
for page in selected_pages:
|
| 71 |
+
enhanced_prompts.append(f"{page}, suitable for printing as a coloring page")
|
| 72 |
+
|
| 73 |
+
images = [image_generation_tool(prompt) for prompt in enhanced_prompts]
|
| 74 |
+
|
| 75 |
+
# Save images to temporary files
|
| 76 |
+
image_paths = []
|
| 77 |
+
for i, img in enumerate(images):
|
| 78 |
+
# Create a temporary file with a .png extension
|
| 79 |
+
with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as temp_file:
|
| 80 |
+
temp_path = temp_file.name
|
| 81 |
+
img.save(temp_path)
|
| 82 |
+
image_paths.append(temp_path)
|
| 83 |
+
|
| 84 |
+
# Create a formatted response with descriptions
|
| 85 |
+
response = f"## Passover Coloring Pages for a {age}-year-old:\n\n"
|
| 86 |
+
response += "\n".join(descriptions)
|
| 87 |
+
|
| 88 |
+
# Return the response with image paths
|
| 89 |
+
return f"{response}\n\nImages are saved and ready for display."
|
| 90 |
except Exception as e:
|
| 91 |
+
# If image generation fails, return text description
|
| 92 |
+
response = f"## Passover Coloring Pages for a {age}-year-old:\n\n"
|
| 93 |
+
response += "\n".join(descriptions)
|
| 94 |
+
return f"{response}\n\nError generating images: {str(e)}"
|
| 95 |
+
|
| 96 |
+
# Custom UI wrapper to handle image display
|
| 97 |
+
class CustomGradioUI(GradioUI):
|
| 98 |
+
def __init__(self, agent):
|
| 99 |
+
super().__init__(agent)
|
| 100 |
+
|
| 101 |
+
def launch(self, **kwargs):
|
| 102 |
+
import gradio as gr
|
| 103 |
+
|
| 104 |
+
# Create a custom interface that can display images
|
| 105 |
+
with gr.Blocks() as demo:
|
| 106 |
+
with gr.Row():
|
| 107 |
+
with gr.Column(scale=1):
|
| 108 |
+
gr.Markdown("# Passover Coloring Pages Generator")
|
| 109 |
+
|
| 110 |
+
with gr.Row():
|
| 111 |
+
with gr.Column(scale=1):
|
| 112 |
+
input_box = gr.Textbox(label="Enter child's age (1-12)")
|
| 113 |
+
submit_btn = gr.Button("Generate Coloring Pages")
|
| 114 |
+
|
| 115 |
+
with gr.Row():
|
| 116 |
+
with gr.Column(scale=1):
|
| 117 |
+
output_text = gr.Markdown(label="Generated Pages")
|
| 118 |
+
|
| 119 |
+
with gr.Row():
|
| 120 |
+
gallery = gr.Gallery(label="Coloring Pages", show_label=True)
|
| 121 |
+
|
| 122 |
+
def process_input(input_text):
|
| 123 |
+
try:
|
| 124 |
+
# Try to convert the input to an integer
|
| 125 |
+
age = int(input_text.strip())
|
| 126 |
+
if not (1 <= age <= 12):
|
| 127 |
+
return "Please enter a valid age between 1 and 12.", []
|
| 128 |
+
|
| 129 |
+
# Generate the coloring pages
|
| 130 |
+
result = generate_passover_coloring_pages(age)
|
| 131 |
+
|
| 132 |
+
# Get the image paths from the temporary files
|
| 133 |
+
image_paths = []
|
| 134 |
+
for file in os.listdir(tempfile.gettempdir()):
|
| 135 |
+
if file.endswith('.png'):
|
| 136 |
+
image_paths.append(os.path.join(tempfile.gettempdir(), file))
|
| 137 |
+
|
| 138 |
+
# Display the most recent images (last 4 if there are more)
|
| 139 |
+
image_paths = sorted(image_paths, key=os.path.getmtime, reverse=True)[:4]
|
| 140 |
+
|
| 141 |
+
# Return the result and image paths
|
| 142 |
+
return result, image_paths
|
| 143 |
+
except ValueError:
|
| 144 |
+
return "Please enter a valid number for the child's age.", []
|
| 145 |
+
except Exception as e:
|
| 146 |
+
return f"Error: {str(e)}", []
|
| 147 |
+
|
| 148 |
+
submit_btn.click(process_input, inputs=input_box, outputs=[output_text, gallery])
|
| 149 |
+
|
| 150 |
+
# Launch the demo
|
| 151 |
+
demo.launch(**kwargs)
|
| 152 |
+
|
| 153 |
+
# Modified prompt templates to handle simple age input
|
| 154 |
+
custom_prompt_templates = {
|
| 155 |
+
"react-system": """You are an helpful agent that helps children learn about Passover through coloring pages.
|
| 156 |
+
You have access to the following tools:
|
| 157 |
+
|
| 158 |
+
{tools_string}
|
| 159 |
+
|
| 160 |
+
When a user enters a number between 1 and 12, interpret it as the age of a child and generate Passover coloring pages suitable for that age using the generate_passover_coloring_pages tool.
|
| 161 |
+
If you're asked to generate coloring pages or if the input is just a number, assume the user wants Passover coloring pages for a child of that age.
|
| 162 |
+
|
| 163 |
+
To use a tool, output an action in this format:
|
| 164 |
+
```py
|
| 165 |
+
action = tool_name(arg1=value1, arg2=value2, ...)
|
| 166 |
+
```
|
| 167 |
+
|
| 168 |
+
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.
|
| 169 |
+
""",
|
| 170 |
+
"react-human": "{input_string}",
|
| 171 |
+
"react-assistant": "{agent_response}",
|
| 172 |
+
}
|
| 173 |
|
| 174 |
+
# Setup agent
|
| 175 |
final_answer = FinalAnswerTool()
|
| 176 |
|
| 177 |
model = HfApiModel(
|
| 178 |
max_tokens=2096,
|
| 179 |
temperature=0.5,
|
| 180 |
+
model_id='Qwen/Qwen2.5-Coder-32B-Instruct'
|
|
|
|
| 181 |
)
|
| 182 |
|
| 183 |
+
# Check if custom prompts should be used or merged with existing ones
|
| 184 |
+
try:
|
| 185 |
+
with open("prompts.yaml", 'r') as stream:
|
| 186 |
+
prompt_templates = yaml.safe_load(stream)
|
| 187 |
+
# Merge the templates, giving priority to our custom ones
|
| 188 |
+
prompt_templates.update(custom_prompt_templates)
|
| 189 |
+
except:
|
| 190 |
+
# If file doesn't exist or has issues, use our custom templates
|
| 191 |
+
prompt_templates = custom_prompt_templates
|
| 192 |
|
| 193 |
agent = CodeAgent(
|
| 194 |
model=model,
|
| 195 |
+
tools=[final_answer, generate_passover_coloring_pages],
|
| 196 |
max_steps=6,
|
| 197 |
verbosity_level=1,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
prompt_templates=prompt_templates
|
| 199 |
)
|
| 200 |
|
| 201 |
+
# Launch custom Gradio UI
|
| 202 |
+
CustomGradioUI(agent).launch()
|