RozzaCreat commited on
Commit
d1a1972
·
verified ·
1 Parent(s): 5610eaf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +158 -174
app.py CHANGED
@@ -1,29 +1,23 @@
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
  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:
26
- str: A list of suggested Passover-themed coloring pages.
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,169 +34,73 @@ def generate_passover_coloring_pages(age: int) -> str:
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):
141
- def __init__(self, agent):
142
- super().__init__(agent)
143
-
144
- def launch(self, **kwargs):
145
- import gradio as gr
146
-
147
- # Create a custom interface that can display images
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):
156
- input_box = gr.Textbox(label="Enter child's age (1-12)")
157
- submit_btn = gr.Button("Generate Coloring Pages")
158
-
159
- with gr.Row():
160
- 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:
168
- # Try to convert the input to an integer
169
- age = int(input_text.strip())
170
- if not (1 <= age <= 12):
171
- return "Please enter a valid age between 1 and 12.", []
172
-
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:
198
- return f"Error: {str(e)}", []
199
-
200
- submit_btn.click(process_input, inputs=input_box, outputs=[output_text, gallery])
201
-
202
- # Launch the demo
203
- demo.launch(**kwargs)
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:
@@ -226,25 +124,15 @@ Always use Python syntax for calling tools. After using a tool, analyze the resu
226
  "react-assistant": "{agent_response}",
227
  }
228
 
229
- # Setup agent
230
- final_answer = FinalAnswerTool()
231
-
232
- model = HfApiModel(
233
- max_tokens=2096,
234
- temperature=0.5,
235
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct'
236
- )
237
-
238
- # Check if custom prompts should be used or merged with existing ones
239
  try:
240
  with open("prompts.yaml", 'r') as stream:
241
  prompt_templates = yaml.safe_load(stream)
242
- # Merge the templates, giving priority to our custom ones
243
  prompt_templates.update(custom_prompt_templates)
244
  except:
245
- # If file doesn't exist or has issues, use our custom templates
246
  prompt_templates = custom_prompt_templates
247
 
 
248
  agent = CodeAgent(
249
  model=model,
250
  tools=[final_answer, generate_passover_coloring_pages],
@@ -253,5 +141,101 @@ agent = CodeAgent(
253
  prompt_templates=prompt_templates
254
  )
255
 
256
- # Launch custom Gradio UI
257
- CustomGradioUI(agent).launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from smolagents import CodeAgent, HfApiModel, tool
 
 
 
 
 
 
2
  import os
3
+ import yaml
4
  import time
 
 
5
  from tools.final_answer import FinalAnswerTool
6
+ from PIL import Image, ImageDraw, ImageFont
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
+ # Create placeholder images with descriptions
66
+ image_paths = []
67
+ for i, description in enumerate(selected_pages):
68
+ # Create a simple placeholder image with text
69
  img = Image.new('RGB', (800, 600), color='white')
70
+ draw = ImageDraw.Draw(img)
 
 
 
 
71
 
72
+ # Add a border
73
+ draw.rectangle([(10, 10), (790, 590)], outline='black', width=2)
 
 
74
 
75
+ # Write the description
76
+ draw.text((400, 300), description, fill='black', anchor='mm')
77
+ draw.text((400, 350), "Jewish Passover Coloring Page", fill='black', anchor='mm')
78
+ draw.text((400, 400), f"For age: {age}", fill='black', anchor='mm')
79
 
80
+ # Save the image
81
+ timestamp = int(time.time())
82
+ img_path = os.path.join(IMAGES_DIR, f"passover_{age}_{i}_{timestamp}.png")
83
+ img.save(img_path)
84
+ image_paths.append(img_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
+ # Create formatted response
87
+ response = f"## Jewish Passover (Pesach) Coloring Pages for a {age}-year-old:\n\n"
88
+ response += "\n".join([f"- {desc}" for desc in selected_pages])
89
+
90
+ # Return paths in a special format for the UI to find
91
+ image_paths_str = "||".join(image_paths)
92
+ return f"{response}\n\nIMAGE_PATHS:{image_paths_str}"
 
 
 
 
 
 
 
 
 
93
 
94
+ # Setup agent
95
+ final_answer = FinalAnswerTool()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
+ model = HfApiModel(
98
+ max_tokens=2096,
99
+ temperature=0.5,
100
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct'
101
+ )
102
+
103
+ # Prompt templates
104
  custom_prompt_templates = {
105
  "react-system": """You are a helpful agent that helps children learn about Jewish Passover/Pesach through coloring pages.
106
  You have access to the following tools:
 
124
  "react-assistant": "{agent_response}",
125
  }
126
 
127
+ # Load or use custom prompts
 
 
 
 
 
 
 
 
 
128
  try:
129
  with open("prompts.yaml", 'r') as stream:
130
  prompt_templates = yaml.safe_load(stream)
 
131
  prompt_templates.update(custom_prompt_templates)
132
  except:
 
133
  prompt_templates = custom_prompt_templates
134
 
135
+ # Create agent
136
  agent = CodeAgent(
137
  model=model,
138
  tools=[final_answer, generate_passover_coloring_pages],
 
141
  prompt_templates=prompt_templates
142
  )
143
 
144
+ # Simple custom interface function
145
+ def run_with_simple_interface():
146
+ print("===== Jewish Passover Coloring Pages Generator =====")
147
+ print("Enter a child's age (1-12) to generate coloring pages")
148
+
149
+ while True:
150
+ try:
151
+ input_text = input("\nEnter age (or 'q' to quit): ")
152
+
153
+ if input_text.lower() == 'q':
154
+ print("Goodbye!")
155
+ break
156
+
157
+ age = int(input_text.strip())
158
+ if not (1 <= age <= 12):
159
+ print("Please enter a valid age between 1 and 12.")
160
+ continue
161
+
162
+ print(f"Generating coloring pages for age {age}...")
163
+ result = generate_passover_coloring_pages(age)
164
+
165
+ # Remove paths for display
166
+ if "IMAGE_PATHS:" in result:
167
+ display_result = result.split("\n\nIMAGE_PATHS:")[0]
168
+ else:
169
+ display_result = result
170
+
171
+ print("\n" + display_result)
172
+
173
+ # Extract image paths
174
+ image_paths = []
175
+ if "IMAGE_PATHS:" in result:
176
+ paths_part = result.split("IMAGE_PATHS:")[1]
177
+ image_paths = paths_part.split("||")
178
+
179
+ print(f"\nCreated {len(image_paths)} coloring pages:")
180
+ for path in image_paths:
181
+ print(f"- {path}")
182
+
183
+ print("\nOpen these image files to view and print the coloring pages.")
184
+
185
+ except ValueError:
186
+ print("Please enter a valid number for the child's age.")
187
+ except Exception as e:
188
+ print(f"Error: {str(e)}")
189
+
190
+ # Launch Gradio UI if available, otherwise use simple interface
191
+ try:
192
+ from Gradio_UI import GradioUI
193
+
194
+ class SimpleGradioUI(GradioUI):
195
+ def launch(self, **kwargs):
196
+ import gradio as gr
197
+
198
+ with gr.Blocks() as demo:
199
+ gr.Markdown("# Jewish Passover (Pesach) Coloring Pages Generator")
200
+
201
+ with gr.Row():
202
+ with gr.Column():
203
+ input_box = gr.Number(label="Enter child's age (1-12)", minimum=1, maximum=12, step=1)
204
+ submit_btn = gr.Button("Generate Coloring Pages")
205
+
206
+ with gr.Row():
207
+ output_text = gr.Markdown()
208
+
209
+ # Simple function to process input without complex logic
210
+ def process_input(age):
211
+ if not age or not (1 <= age <= 12):
212
+ return "Please enter a valid age between 1 and 12."
213
+
214
+ try:
215
+ # Call the tool directly
216
+ result = generate_passover_coloring_pages(int(age))
217
+
218
+ # Remove the image paths for display
219
+ if "IMAGE_PATHS:" in result:
220
+ result = result.split("\n\nIMAGE_PATHS:")[0]
221
+
222
+ result += "\n\n*Coloring pages have been generated. Look in the 'coloring_images' folder for the files.*"
223
+ return result
224
+ except Exception as e:
225
+ return f"Error: {str(e)}"
226
+
227
+ submit_btn.click(process_input, inputs=input_box, outputs=output_text)
228
+
229
+ demo.launch(**kwargs)
230
+
231
+ # Try to launch Gradio UI
232
+ SimpleGradioUI(agent).launch()
233
+
234
+ except ImportError:
235
+ # Fall back to simple console interface
236
+ print("Gradio not available, using simple console interface.")
237
+ run_with_simple_interface()
238
+ except Exception as e:
239
+ print(f"Error launching Gradio UI: {str(e)}")
240
+ print("Falling back to simple console interface.")
241
+ run_with_simple_interface()