RozzaCreat commited on
Commit
e88a3e8
·
verified ·
1 Parent(s): 7d3bdd8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -52
app.py CHANGED
@@ -6,13 +6,20 @@ 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:
@@ -30,68 +37,104 @@ def generate_passover_coloring_pages(age: int) -> str:
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):
@@ -105,7 +148,8 @@ class CustomGradioUI(GradioUI):
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):
@@ -117,7 +161,7 @@ class CustomGradioUI(GradioUI):
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:
@@ -129,17 +173,25 @@ class CustomGradioUI(GradioUI):
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:
@@ -152,13 +204,16 @@ class CustomGradioUI(GradioUI):
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
 
6
  import re
7
  import tempfile
8
  import os
9
+ import time
10
+ import shutil
11
+ from PIL import Image
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
+ Generates Jewish Passover/Pesach-themed coloring pages based on a child's age.
23
  Args:
24
  age (int): The age of the child (1-12).
25
  Returns:
 
37
 
38
  complexity = next(value for (low, high), value in complexity_levels.items() if low <= age <= high)
39
 
40
+ # Enhanced prompts specifically for Jewish Passover/Pesach themes
41
  passover_pages = {
42
  "simple": [
43
+ "Line drawing of matzah for Jewish Passover coloring page, thick black outlines, white background, child-friendly",
44
+ "Simple black outline of a Seder plate with spaces for the six items (karpas, charoset, maror, zeroa, beitzah, chazeret), coloring book style, thick lines",
45
+ "Simple outline drawing of the Afikoman (broken piece of matzah) hidden in fabric, black and white for coloring",
46
+ "Simple outline of a Kiddush cup for Passover seder, black and white for coloring"
47
  ],
48
  "basic": [
49
+ "Black and white outline of Moses parting the Red Sea, traditional Jewish Pesach story, no Christian symbols, coloring book style",
50
+ "Outline drawing of the Ten Plagues (blood, frogs, lice, wild animals, cattle disease, boils, hail, locusts, darkness, death of firstborn) in separated panels, Jewish Passover theme",
51
+ "Haggadah Four Questions illustrations in Hebrew and English for coloring, Jewish Passover tradition",
52
+ "Afikoman hunt maze with matzah at the center, black and white outline for Jewish Passover coloring"
53
  ],
54
  "intermediate": [
55
+ "Detailed black and white outline of a traditional Jewish Seder table with all symbolic foods and Haggadah, no crosses or Christian symbols",
56
+ "Hebrew letter decorations spelling 'Pesach' (פסח) for coloring, traditional Jewish style",
57
+ "Outline drawing of ancient Israelites leaving Egypt, Jewish Passover story, historically accurate depiction",
58
+ "Black and white outline of the Four Sons from the Haggadah, traditional Jewish Passover story characters"
59
  ],
60
  "advanced": [
61
+ "Intricate Haggadah page illustrations in black and white, showing the order of the Seder, traditional Jewish style",
62
+ "Detailed scene of Miriam and women celebrating after crossing the Red Sea with tambourines, Jewish Passover story",
63
+ "Intricate Hebrew calligraphy spelling 'Next year in Jerusalem' (לשנה הבאה בירושלים) for coloring",
64
+ "Detailed symbolic Jewish Passover illustrations showing the journey from slavery to freedom, with proper Jewish symbols only"
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
+ for file in os.listdir(IMAGES_DIR):
73
+ if file.endswith(".png"):
74
+ file_path = os.path.join(IMAGES_DIR, file)
75
+ try:
76
+ os.remove(file_path)
77
+ except:
78
+ pass
79
+
80
+ # Создаем заглушки для изображений на случай сбоя в генерации
81
+ def create_placeholder_image(description, index):
82
+ img = Image.new('RGB', (800, 600), color='white')
83
+ return img
84
 
85
+ # Попытка сгенерировать изображения
86
  try:
87
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
88
 
89
+ # Используем улучшенные подсказки для раскрасок
90
  enhanced_prompts = []
91
  for page in selected_pages:
92
+ enhanced_prompts.append(f"{page}, Jewish traditional Passover symbols only, no Christian imagery, suitable for printing as a coloring page")
93
 
94
+ # Сохраняем пути к изображениям
 
 
95
  image_paths = []
 
 
 
 
 
 
96
 
97
+ # Генерируем и сохраняем изображения
98
+ for i, prompt in enumerate(enhanced_prompts):
99
+ try:
100
+ img = image_generation_tool(prompt)
101
+ # Сохраняем в постоянную директорию с уникальным именем
102
+ timestamp = int(time.time())
103
+ img_path = os.path.join(IMAGES_DIR, f"passover_{age}_{i}_{timestamp}.png")
104
+ img.save(img_path)
105
+ image_paths.append(img_path)
106
+ except Exception as e:
107
+ # При ошибке создаем заглушку
108
+ placeholder = create_placeholder_image(descriptions[i], i)
109
+ img_path = os.path.join(IMAGES_DIR, f"passover_{age}_{i}_placeholder.png")
110
+ placeholder.save(img_path)
111
+ image_paths.append(img_path)
112
+ print(f"Error generating image {i}: {str(e)}")
113
+
114
+ # Создаем форматированный ответ с описаниями
115
+ response = f"## Jewish Passover (Pesach) Coloring Pages for a {age}-year-old:\n\n"
116
+ response += "\n".join([f"- {desc}" for desc in descriptions])
117
 
118
+ # Сохраняем пути к изображениям в ответе в специальном формате
119
+ image_paths_str = "||".join(image_paths)
120
+ return f"{response}\n\nIMAGE_PATHS:{image_paths_str}"
121
+
122
  except Exception as e:
123
+ # Если генерация изображений полностью не удалась, вернуть только текстовое описание
124
+ response = f"## Jewish Passover (Pesach) Coloring Pages for a {age}-year-old:\n\n"
125
+ response += "\n".join([f"- {desc}" for desc in descriptions])
126
+
127
+ # Создаем заглушки для каждого описания
128
+ image_paths = []
129
+ for i, desc in enumerate(descriptions):
130
+ placeholder = create_placeholder_image(desc, i)
131
+ img_path = os.path.join(IMAGES_DIR, f"passover_{age}_{i}_placeholder.png")
132
+ placeholder.save(img_path)
133
+ image_paths.append(img_path)
134
+
135
+ # Сохраняем пути к заглушкам
136
+ image_paths_str = "||".join(image_paths)
137
+ return f"{response}\n\nIMAGE_PATHS:{image_paths_str}"
138
 
139
  # Custom UI wrapper to handle image display
140
  class CustomGradioUI(GradioUI):
 
148
  with gr.Blocks() as demo:
149
  with gr.Row():
150
  with gr.Column(scale=1):
151
+ gr.Markdown("# Jewish Passover (Pesach) Coloring Pages Generator")
152
+ gr.Markdown("Generate traditional Jewish Passover coloring pages for children")
153
 
154
  with gr.Row():
155
  with gr.Column(scale=1):
 
161
  output_text = gr.Markdown(label="Generated Pages")
162
 
163
  with gr.Row():
164
+ gallery = gr.Gallery(label="Jewish Passover Coloring Pages", show_label=True)
165
 
166
  def process_input(input_text):
167
  try:
 
173
  # Generate the coloring pages
174
  result = generate_passover_coloring_pages(age)
175
 
176
+ # Extract image paths from the result
177
  image_paths = []
178
+ if "IMAGE_PATHS:" in result:
179
+ paths_part = result.split("IMAGE_PATHS:")[1]
180
+ image_paths = paths_part.split("||")
181
+ # Удаляем маркер путей из результата
182
+ result = result.split("\n\nIMAGE_PATHS:")[0]
183
 
184
+ # Если нет путей к изображениям, ищем в директории
185
+ if not image_paths:
186
+ for file in os.listdir(IMAGES_DIR):
187
+ if file.endswith('.png') and f"passover_{age}_" in file:
188
+ image_paths.append(os.path.join(IMAGES_DIR, file))
189
+
190
+ # Проверяем, что пути ведут к реальным файлам
191
+ valid_image_paths = [path for path in image_paths if os.path.exists(path)]
192
 
193
  # Return the result and image paths
194
+ return result, valid_image_paths
195
  except ValueError:
196
  return "Please enter a valid number for the child's age.", []
197
  except Exception as e:
 
204
 
205
  # Modified prompt templates to handle simple age input
206
  custom_prompt_templates = {
207
+ "react-system": """You are a helpful agent that helps children learn about Jewish Passover/Pesach through coloring pages.
208
  You have access to the following tools:
209
 
210
  {tools_string}
211
 
212
+ 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.
213
+ 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.
214
+
215
+ Important: Only generate authentic Jewish Passover (Pesach) symbols and imagery - including matzah, seder plate, haggadah, afikoman, four cups of wine, the exodus story, etc.
216
+ Do NOT include any Christian symbols or imagery like crosses, Jesus, or other non-Jewish religious elements.
217
 
218
  To use a tool, output an action in this format:
219
  ```py