RozzaCreat commited on
Commit
ff6dc86
·
verified ·
1 Parent(s): c279bbd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +277 -307
app.py CHANGED
@@ -1,27 +1,191 @@
1
- from smolagents import CodeAgent, HfApiModel, tool
2
- import os
 
 
3
  import yaml
 
 
 
4
  import time
5
- import subprocess
6
- import shutil
7
  from PIL import Image, ImageDraw, ImageFont
8
  from tools.final_answer import FinalAnswerTool
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- # Create directories for images and PDFs
11
- IMAGES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "coloring_images")
12
- PDF_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "coloring_pdf")
13
- os.makedirs(IMAGES_DIR, exist_ok=True)
14
- os.makedirs(PDF_DIR, exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
  @tool
17
  def generate_passover_coloring_pages(age: int) -> str:
18
- """Generates Jewish Passover/Pesach-themed coloring pages based on a child's age.
19
-
20
  Args:
21
- age: The age of the child (1-12).
22
-
23
  Returns:
24
- A list of suggested Passover-themed coloring pages.
25
  """
26
  if not isinstance(age, int) or not (1 <= age <= 12):
27
  return "Error: Please provide a valid age between 1 and 12."
@@ -35,182 +199,76 @@ def generate_passover_coloring_pages(age: int) -> str:
35
 
36
  complexity = next(value for (low, high), value in complexity_levels.items() if low <= age <= high)
37
 
38
- # Enhanced prompts specifically for Jewish Passover/Pesach themes
39
  passover_pages = {
40
  "simple": [
41
- "Matzah for Passover",
42
- "Seder plate outline",
43
- "Afikoman hidden in fabric",
44
- "Kiddush cup for Passover"
45
  ],
46
  "basic": [
47
- "Moses parting the Red Sea",
48
- "Ten Plagues illustrations",
49
- "Four Questions from Haggadah",
50
- "Afikoman hunt maze"
51
  ],
52
  "intermediate": [
53
- "Jewish Seder table with symbolic foods",
54
- "Hebrew letters spelling 'Pesach'",
55
- "Israelites leaving Egypt scene",
56
- "Four Sons from the Haggadah"
57
  ],
58
  "advanced": [
59
- "Haggadah page with Seder order",
60
- "Miriam and women celebrating after Red Sea",
61
- "Hebrew calligraphy 'Next year in Jerusalem'",
62
- "Passover journey from slavery to freedom"
63
  ]
64
  }
65
 
66
- # Get descriptions for selected age group
67
  selected_pages = passover_pages[complexity]
 
68
 
69
- # Generate and save images
70
- timestamp = int(time.time())
71
-
72
- # Create a temporary directory for images that will be combined into PDF
73
- temp_dir = os.path.join(IMAGES_DIR, f"temp_{timestamp}")
74
- os.makedirs(temp_dir, exist_ok=True)
75
 
76
- # Create a cover page
77
- cover_img = Image.new('RGB', (2480, 3508), color='white') # A4 size at 300 DPI
78
- draw = ImageDraw.Draw(cover_img)
79
 
 
80
  try:
81
- # Try to load a font, use default if not available
82
- try:
83
- font = ImageFont.truetype("Arial", 80)
84
- small_font = ImageFont.truetype("Arial", 40)
85
- except:
86
- font = ImageFont.load_default()
87
- small_font = ImageFont.load_default()
88
 
89
- # Add title to cover page - FIXED ORDER OF ARGUMENTS
90
- draw.text((1240, 800), "Jewish Passover (Pesach)", fill='black', anchor='mm', font=font)
91
- draw.text((1240, 1000), "Coloring Pages", fill='black', anchor='mm', font=font)
92
- draw.text((1240, 1200), f"For Ages {age} Years", fill='black', anchor='mm', font=font)
93
- draw.text((1240, 1500), "Created for Jewish children and families", fill='black', anchor='mm', font=small_font)
94
- draw.text((1240, 1600), "to celebrate the story of Passover", fill='black', anchor='mm', font=small_font)
95
-
96
- # Save cover page with a sequential number for proper ordering
97
- cover_path = os.path.join(temp_dir, f"01_cover.png")
98
- cover_img.save(cover_path)
99
- except Exception as e:
100
- print(f"Error creating cover page: {str(e)}")
101
-
102
- # Create individual coloring pages
103
- page_paths = []
104
- for i, description in enumerate(selected_pages):
105
- try:
106
- # Create an A4 sized image
107
- img = Image.new('RGB', (2480, 3508), color='white')
108
- draw = ImageDraw.Draw(img)
109
-
110
- # Add a border
111
- draw.rectangle([(100, 100), (2380, 3408)], outline='black', width=4)
112
-
113
- # Add title at the top - FIXED ORDER OF ARGUMENTS
114
- draw.text((1240, 200), description, fill='black', anchor='mm', font=font)
115
 
116
- # Add a content area for the coloring image
117
- draw.rectangle([(300, 400), (2180, 2800)], outline='black', width=2)
 
 
 
118
 
119
- # Add description text in the content area - FIXED ORDER OF ARGUMENTS
120
- draw.text((1240, 1600), description, fill='black', anchor='mm', font=small_font)
121
- draw.text((1240, 1700), "Jewish Passover Coloring Page", fill='black', anchor='mm', font=small_font)
122
- draw.text((1240, 1800), f"For age: {age}", fill='black', anchor='mm', font=small_font)
 
123
 
124
- # Add footer - FIXED ORDER OF ARGUMENTS
125
- draw.text((1240, 3300), f"Page {i+1} of {len(selected_pages)}", fill='black', anchor='mm', font=small_font)
 
126
 
127
- # Save with sequential numbering for proper PDF ordering
128
- seq_num = i + 2 # Start from 2 after the cover page
129
- page_path = os.path.join(temp_dir, f"{seq_num:02d}_{i+1}.png")
130
- img.save(page_path)
131
- page_paths.append(page_path)
132
-
133
- # Also save a copy in the main images directory
134
- main_path = os.path.join(IMAGES_DIR, f"passover_{age}_{i}_{timestamp}.png")
135
- img.save(main_path)
136
- except Exception as e:
137
- print(f"Error creating page {i+1}: {str(e)}")
138
-
139
- # Now create a PDF using one of several methods
140
-
141
- # Method 1: Try using img2pdf (requires img2pdf to be installed)
142
- pdf_filename = f"passover_coloring_pages_age_{age}_{timestamp}.pdf"
143
- pdf_path = os.path.join(PDF_DIR, pdf_filename)
144
-
145
- # Get all image files in the temporary directory in correct order
146
- all_images = sorted([os.path.join(temp_dir, f) for f in os.listdir(temp_dir) if f.endswith('.png')])
147
-
148
- pdf_created = False
149
-
150
- # Try different methods to create the PDF
151
-
152
- # Method 1: Try using img2pdf via Python
153
- try:
154
- import img2pdf
155
- with open(pdf_path, "wb") as f:
156
- f.write(img2pdf.convert(all_images))
157
- pdf_created = True
158
- print(f"PDF created with img2pdf Python module: {pdf_path}")
159
- except ImportError:
160
- print("img2pdf Python module not available, trying alternative method...")
161
-
162
- # Method 2: Try using ImageMagick convert command
163
- if not pdf_created:
164
- try:
165
- convert_cmd = ["convert"]
166
- convert_cmd.extend(all_images)
167
- convert_cmd.append(pdf_path)
168
- subprocess.run(convert_cmd, check=True)
169
- pdf_created = True
170
- print(f"PDF created with ImageMagick: {pdf_path}")
171
- except (subprocess.SubprocessError, FileNotFoundError):
172
- print("ImageMagick not available, trying alternative method...")
173
-
174
- # Method 3: Try using the img2pdf command-line tool
175
- if not pdf_created:
176
- try:
177
- img2pdf_cmd = ["img2pdf"]
178
- img2pdf_cmd.extend(all_images)
179
- img2pdf_cmd.extend(["-o", pdf_path])
180
- subprocess.run(img2pdf_cmd, check=True)
181
- pdf_created = True
182
- print(f"PDF created with img2pdf command-line: {pdf_path}")
183
- except (subprocess.SubprocessError, FileNotFoundError):
184
- print("img2pdf command-line tool not available, trying alternative method...")
185
-
186
- # Method 4: Try using Python Pillow
187
- if not pdf_created:
188
- try:
189
- # Open the first image to get the size
190
- first_img = Image.open(all_images[0])
191
-
192
- # Create a list of images
193
- images = []
194
- for img_path in all_images[1:]: # Skip the first one as we already opened it
195
- images.append(Image.open(img_path))
196
-
197
- # Save as PDF
198
- first_img.save(
199
- pdf_path,
200
- "PDF",
201
- resolution=100.0,
202
- save_all=True,
203
- append_images=images
204
- )
205
- pdf_created = True
206
- print(f"PDF created with Pillow: {pdf_path}")
207
- except Exception as e:
208
- print(f"Pillow PDF creation failed: {str(e)}")
209
-
210
- # If PDF creation failed, use the HTML approach as a fallback
211
- if not pdf_created:
212
- # Create a simple HTML for viewing/printing
213
- html_path = os.path.join(IMAGES_DIR, f"passover_coloring_pages_{age}_{timestamp}.html")
214
  with open(html_path, 'w') as f:
215
  f.write(f"""<!DOCTYPE html>
216
  <html>
@@ -237,18 +295,18 @@ def generate_passover_coloring_pages(age: int) -> str:
237
  <div class="controls">
238
  <h1>Jewish Passover (Pesach) Coloring Pages</h1>
239
  <h2>For Ages {age} Years</h2>
240
- <p>PDF creation failed. Use this page to print instead.</p>
241
  <button class="print-button" onclick="window.print()">Print All Pages</button>
242
  </div>
243
  """)
244
 
245
- # Add each image from the main directory to the HTML
246
- for i, _ in enumerate(selected_pages):
247
  img_filename = f"passover_{age}_{i}_{timestamp}.png"
248
  f.write(f"""
249
  <div class="page">
250
- <img src="{img_filename}" alt="Coloring Page {i+1}">
251
- <div class="page-title">{selected_pages[i]}</div>
252
  </div>
253
  """)
254
 
@@ -256,68 +314,47 @@ def generate_passover_coloring_pages(age: int) -> str:
256
  </body>
257
  </html>
258
  """)
259
-
260
- # Clean up temp directory
261
- try:
262
- shutil.rmtree(temp_dir)
263
- except Exception as e:
264
- print(f"Error cleaning up temp directory: {str(e)}")
265
-
266
- # Create formatted response
267
- response = f"## Jewish Passover (Pesach) Coloring Pages for a {age}-year-old:\n\n"
268
- response += "\n".join([f"- {desc}" for desc in selected_pages])
269
-
270
- if pdf_created:
271
- # PDF was successfully created
272
- response += f"\n\n**PDF coloring pages have been generated!**\n\n"
273
- response += f"To view and print the coloring pages, please open this PDF file:\n\n"
274
- response += f"{pdf_path}\n\n"
275
- response += f"The individual image files are also available in the 'coloring_images' folder."
276
- else:
277
- # Fallback to HTML
278
- response += f"\n\n**Coloring pages have been generated! (PDF creation failed)**\n\n"
279
  response += f"To view and print the coloring pages, please open this HTML file in your web browser:\n\n"
280
  response += f"{html_path}\n\n"
281
- response += f"The individual image files are also available in the 'coloring_images' folder."
282
-
283
- # Add printing instructions
284
- response += f"\n\n**Printing Instructions:**\n"
285
-
286
- if pdf_created:
287
- response += f"1. Open the PDF file in Adobe Reader or any PDF viewer\n"
288
- response += f"2. Use the print function of your PDF viewer\n"
289
- response += f"3. Select your printer and print\n\n"
290
- else:
291
- response += f"1. Open the HTML file in a web browser\n"
292
- response += f"2. Click the 'Print All Pages' button\n"
293
- response += f"3. In the print dialog, make sure 'Background Graphics' is enabled\n"
294
- response += f"4. Select your printer and print\n\n"
295
-
296
- response += f"You can also print individual pages by opening the PNG files directly."
297
 
298
- return response
 
 
 
 
 
299
 
300
- # Setup agent
301
- final_answer = FinalAnswerTool()
 
 
 
 
 
 
 
 
302
 
303
- model = HfApiModel(
304
- max_tokens=2096,
305
- temperature=0.5,
306
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct'
307
- )
308
-
309
- # Prompt templates
310
  custom_prompt_templates = {
311
- "react-system": """You are a helpful agent that helps children learn about Jewish Passover/Pesach through coloring pages.
312
  You have access to the following tools:
313
 
314
  {tools_string}
315
 
316
- 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.
317
- 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.
318
-
319
- Important: Only generate authentic Jewish Passover (Pesach) symbols and imagery - including matzah, seder plate, haggadah, afikoman, four cups of wine, the exodus story, etc.
320
- Do NOT include any Christian symbols or imagery like crosses, Jesus, or other non-Jewish religious elements.
321
 
322
  To use a tool, output an action in this format:
323
  ```py
@@ -330,15 +367,25 @@ Always use Python syntax for calling tools. After using a tool, analyze the resu
330
  "react-assistant": "{agent_response}",
331
  }
332
 
333
- # Load or use custom prompts
 
 
 
 
 
 
 
 
 
334
  try:
335
  with open("prompts.yaml", 'r') as stream:
336
  prompt_templates = yaml.safe_load(stream)
 
337
  prompt_templates.update(custom_prompt_templates)
338
  except:
 
339
  prompt_templates = custom_prompt_templates
340
 
341
- # Create agent
342
  agent = CodeAgent(
343
  model=model,
344
  tools=[final_answer, generate_passover_coloring_pages],
@@ -347,82 +394,5 @@ agent = CodeAgent(
347
  prompt_templates=prompt_templates
348
  )
349
 
350
- # Simple custom interface function
351
- def run_with_simple_interface():
352
- print("===== Jewish Passover Coloring Pages Generator =====")
353
- print("Enter a child's age (1-12) to generate coloring pages")
354
-
355
- while True:
356
- try:
357
- input_text = input("\nEnter age (or 'q' to quit): ")
358
-
359
- if input_text.lower() == 'q':
360
- print("Goodbye!")
361
- break
362
-
363
- age = int(input_text.strip())
364
- if not (1 <= age <= 12):
365
- print("Please enter a valid age between 1 and 12.")
366
- continue
367
-
368
- print(f"Generating coloring pages for age {age}...")
369
- result = generate_passover_coloring_pages(age)
370
-
371
- print("\n" + result)
372
-
373
- except ValueError:
374
- print("Please enter a valid number for the child's age.")
375
- except Exception as e:
376
- print(f"Error: {str(e)}")
377
-
378
- # Launch Gradio UI if available, otherwise use simple interface
379
- try:
380
- from Gradio_UI import GradioUI
381
-
382
- class SimpleGradioUI(GradioUI):
383
- def launch(self, **kwargs):
384
- import gradio as gr
385
-
386
- with gr.Blocks() as demo:
387
- gr.Markdown("# Jewish Passover (Pesach) Coloring Pages Generator")
388
- gr.Markdown("### Generates print-ready coloring pages as PDF")
389
-
390
- with gr.Row():
391
- with gr.Column():
392
- input_box = gr.Number(label="Enter child's age (1-12)", minimum=1, maximum=12, step=1)
393
- submit_btn = gr.Button("Generate PDF Coloring Pages")
394
-
395
- with gr.Row():
396
- output_text = gr.Markdown()
397
-
398
- # Simple function to process input without complex logic
399
- def process_input(age):
400
- if not age or not (1 <= age <= 12):
401
- return "Please enter a valid age between 1 and 12."
402
-
403
- try:
404
- # Call the tool directly
405
- result = generate_passover_coloring_pages(int(age))
406
-
407
- # Add a clearer message
408
- result += f"\n\n**Note:** Gradio cannot display or download the PDF directly. Please navigate to the location shown above to open the PDF file."
409
-
410
- return result
411
- except Exception as e:
412
- return f"Error: {str(e)}"
413
-
414
- submit_btn.click(process_input, inputs=input_box, outputs=output_text)
415
-
416
- demo.launch(**kwargs)
417
-
418
- # Try to launch Gradio UI
419
- SimpleGradioUI(agent).launch()
420
-
421
- except ImportError:
422
- # Fall back to simple console interface
423
- print("Gradio not available, using simple console interface.")
424
- run_with_simple_interface()
425
- except Exception as e:
426
- print(f"Error launching Gradio UI: {str(e)}")
427
- print("Falling back to simple console interface.")
428
- run_with_simple_interface()
 
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 io
8
+ import base64
9
  import time
10
+ import json
11
+ import os
12
  from PIL import Image, ImageDraw, ImageFont
13
  from tools.final_answer import FinalAnswerTool
14
+ from Gradio_UI import GradioUI
15
+
16
+ # 1. Функция использования бесплатной демо-версии Hugging Face Inference API
17
+ def generate_image_hf_demo(prompt):
18
+ try:
19
+ # Используем публичную демо-версию без ключа API - имеет ограничения, но бесплатна
20
+ url = "https://api-inference.huggingface.co/models/runwayml/stable-diffusion-v1-5"
21
+
22
+ response = requests.post(
23
+ url,
24
+ json={
25
+ "inputs": prompt,
26
+ "parameters": {
27
+ "negative_prompt": "color, colored, shading, realistic, photorealistic, complex",
28
+ }
29
+ }
30
+ )
31
+
32
+ if response.status_code == 200:
33
+ img = Image.open(io.BytesIO(response.content))
34
+ # Преобразование в черно-белое для раскраски
35
+ img = img.convert('L') # В оттенки серого
36
+ img = img.point(lambda x: 0 if x < 128 else 255, '1') # Чистый чёрно-белый
37
+ return img
38
+ else:
39
+ print(f"HF Demo API error: {response.status_code} - {response.text}")
40
+ return None
41
+ except Exception as e:
42
+ print(f"HF Demo API error: {str(e)}")
43
+ return None
44
+
45
+ # 2. Функция использования Replicate (имеет бесплатную квоту)
46
+ def generate_image_replicate(prompt, api_token=None):
47
+ try:
48
+ # Если у вас есть токен API Replicate, вы можете использовать его здесь
49
+ # Бесплатная квота обычно составляет до 100 запросов в месяц
50
+ headers = {}
51
+ if api_token:
52
+ headers["Authorization"] = f"Token {api_token}"
53
+
54
+ # Создание задания
55
+ url = "https://api.replicate.com/v1/predictions"
56
+ payload = {
57
+ "version": "a9758cbfbd5f3c2094457d996681af52552901775aa2d6dd0b17fd15df959bef", # sd-1.5
58
+ "input": {
59
+ "prompt": prompt,
60
+ "negative_prompt": "color, colored, shading, realistic, photorealistic, complex, 3d",
61
+ "num_outputs": 1,
62
+ "guidance_scale": 10,
63
+ "num_inference_steps": 30
64
+ }
65
+ }
66
+
67
+ response = requests.post(url, json=payload, headers=headers)
68
+
69
+ if response.status_code != 201:
70
+ print(f"Replicate API error: {response.status_code} - {response.text}")
71
+ return None
72
+
73
+ data = response.json()
74
+ prediction_id = data.get("id")
75
+
76
+ # Ожидание завершения генерации
77
+ for _ in range(10): # Пробуем 10 раз (50 секунд)
78
+ time.sleep(5)
79
+ get_url = f"https://api.replicate.com/v1/predictions/{prediction_id}"
80
+ get_response = requests.get(get_url, headers=headers)
81
+
82
+ if get_response.status_code != 200:
83
+ continue
84
+
85
+ result = get_response.json()
86
+ if result.get("status") == "succeeded":
87
+ # Загрузка изображения
88
+ image_url = result.get("output", [])[0]
89
+ img_response = requests.get(image_url)
90
+ if img_response.status_code == 200:
91
+ img = Image.open(io.BytesIO(img_response.content))
92
+ # Преобразование в черно-белое для раскраски
93
+ img = img.convert('L')
94
+ img = img.point(lambda x: 0 if x < 128 else 255, '1')
95
+ return img
96
+
97
+ if result.get("status") == "failed":
98
+ print(f"Replicate generation failed: {result.get('error')}")
99
+ return None
100
+
101
+ return None
102
+ except Exception as e:
103
+ print(f"Replicate API error: {str(e)}")
104
+ return None
105
 
106
+ # 3. Функция создания простых изображений локально
107
+ def generate_local_image(description, age):
108
+ try:
109
+ # Создаем локальное изображение с текстовым описанием
110
+ width, height = 1024, 1024
111
+ img = Image.new('RGB', (width, height), color='white')
112
+ draw = ImageDraw.Draw(img)
113
+
114
+ # Добавляем рамку
115
+ draw.rectangle([(20, 20), (width-20, height-20)], outline='black', width=3)
116
+
117
+ # Пробуем загрузить шрифт, используем дефолтный при ошибке
118
+ try:
119
+ font = ImageFont.truetype("Arial", 40)
120
+ small_font = ImageFont.truetype("Arial", 20)
121
+ except:
122
+ font = ImageFont.load_default()
123
+ small_font = ImageFont.load_default()
124
+
125
+ # Заголовок - описание раскраски
126
+ text = description.split(',')[0] if ',' in description else description
127
+ draw.text((width//2, 100), text, fill='black', anchor='mm', font=font)
128
+
129
+ # Подзаголовок
130
+ draw.text((width//2, 150), "Passover Coloring Page", fill='black', anchor='mm', font=small_font)
131
+ draw.text((width//2, 180), f"For age: {age}", fill='black', anchor='mm', font=small_font)
132
+
133
+ # Добавляем некоторые базовые элементы в зависимости от описания
134
+ if "matzah" in description.lower():
135
+ # Рисуем простую мацу
136
+ draw.ellipse([(300, 400), (700, 600)], outline='black', width=3)
137
+ for i in range(10):
138
+ x1, y1 = 300 + i*40, 400 + (i % 3) * 30
139
+ x2, y2 = x1 + 50, y1 + 10
140
+ draw.ellipse([(x1, y1), (x2, y2)], outline='black', width=1)
141
+
142
+ elif "seder plate" in description.lower():
143
+ # Рисуем тарелку Седер
144
+ draw.ellipse([(250, 350), (750, 850)], outline='black', width=3)
145
+ # Разделы на тарелке
146
+ draw.line([(500, 350), (500, 850)], fill='black', width=2)
147
+ draw.line([(250, 600), (750, 600)], fill='black', width=2)
148
+ # Добавляем метки разделов
149
+ sections = ["Karpas", "Charoset", "Maror", "Zeroa", "Beitzah", "Chazeret"]
150
+ positions = [(375, 475), (625, 475), (375, 725), (625, 725), (500, 500), (500, 700)]
151
+ for section, pos in zip(sections, positions):
152
+ draw.text(pos, section, fill='black', anchor='mm', font=small_font)
153
+
154
+ elif "red sea" in description.lower():
155
+ # Рисуем Красное море
156
+ # Волны слева
157
+ for i in range(5):
158
+ y = 400 + i*80
159
+ draw.arc([(100, y-40), (300, y+40)], 0, 180, fill='black', width=3)
160
+
161
+ # Волны справа
162
+ for i in range(5):
163
+ y = 400 + i*80
164
+ draw.arc([(700, y-40), (900, y+40)], 0, 180, fill='black', width=3)
165
+
166
+ # Дорожка посередине
167
+ draw.rectangle([(400, 300), (600, 900)], outline='black', width=3)
168
+
169
+ # Добавляем инструкции внизу
170
+ draw.text((width//2, height-50), "Color and learn about Passover!", fill='black', anchor='mm', font=small_font)
171
+
172
+ return img
173
+ except Exception as e:
174
+ print(f"Local image generation error: {str(e)}")
175
+ # Возвращаем просто белый фон с рамкой при ошибке
176
+ img = Image.new('RGB', (1024, 1024), color='white')
177
+ draw = ImageDraw.Draw(img)
178
+ draw.rectangle([(20, 20), (1004, 1004)], outline='black', width=3)
179
+ return img
180
 
181
  @tool
182
  def generate_passover_coloring_pages(age: int) -> str:
183
+ """
184
+ Generates Passover-themed coloring pages based on a child's age.
185
  Args:
186
+ age (int): The age of the child (1-12).
 
187
  Returns:
188
+ str: A list of suggested Passover-themed coloring pages.
189
  """
190
  if not isinstance(age, int) or not (1 <= age <= 12):
191
  return "Error: Please provide a valid age between 1 and 12."
 
199
 
200
  complexity = next(value for (low, high), value in complexity_levels.items() if low <= age <= high)
201
 
202
+ # Enhanced prompts for better coloring pages
203
  passover_pages = {
204
  "simple": [
205
+ "Line drawing of a matzah for a simple coloring page, thick black outlines, white background, perfect for a child's coloring book",
206
+ "Simple black and white outline of a Seder plate with clear divisions, coloring book style, thick lines",
207
+ "Black and white line art of baby Moses in a basket for a child's coloring book, simple outlines",
208
+ "Simple black and white outline of a frog (plague) for children's coloring book, thick lines, no shading"
209
  ],
210
  "basic": [
211
+ "Black and white outline of the Parting of the Red Sea scene for a coloring book, clear distinct lines",
212
+ "Coloring book page with Ten Plagues illustrations, black outline on white background, no shading",
213
+ "Black and white outline illustrations of the Four Questions for a Passover coloring book",
214
+ "Afikoman hunt maze in black and white outline for a coloring book, thick lines"
215
  ],
216
  "intermediate": [
217
+ "Detailed black and white outline of a Seder table for a coloring book, clear distinct elements",
218
+ "Black and white outline of Exodus story scenes for coloring book, clear lines",
219
+ "Hebrew letter decorations for 'Pesach' in black and white outline style for coloring book",
220
+ "Black and white outline of Egyptian pyramids with Israelites for a coloring book"
221
  ],
222
  "advanced": [
223
+ "Intricate black and white line art of Haggadah illustrations for a coloring book, detailed outlines",
224
+ "Detailed symbolism scene in black and white outline for an advanced coloring book",
225
+ "Combined Passover story panels in black and white line art for coloring book",
226
+ "Hebrew calligraphy art in black and white outline for a coloring book, intricate details"
227
  ]
228
  }
229
 
 
230
  selected_pages = passover_pages[complexity]
231
+ descriptions = [f"- {page.split(',')[0]}" for page in selected_pages]
232
 
233
+ # Создаем директорию для сохранения изображений
234
+ images_dir = "coloring_images"
235
+ os.makedirs(images_dir, exist_ok=True)
 
 
 
236
 
237
+ timestamp = int(time.time())
238
+ image_paths = []
 
239
 
240
+ # Пробуем сгенерировать изображения используя бесплатные опции
241
  try:
242
+ images = []
 
 
 
 
 
 
243
 
244
+ for i, prompt in enumerate(selected_pages):
245
+ img = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246
 
247
+ # Попробуем разные мето��ы создания изображений
248
+ if i % 3 == 0:
249
+ # Пробуем Hugging Face Demo API
250
+ enhanced_prompt = f"{prompt}, coloring book style, black and white line drawing only, no color, no shading"
251
+ img = generate_image_hf_demo(enhanced_prompt)
252
 
253
+ elif i % 3 == 1:
254
+ # Пробуем Replicate (требует токен API, но имеет бесплатную квоту)
255
+ enhanced_prompt = f"{prompt}, coloring book style, black and white line drawing only, no color, no shading"
256
+ # Оставляем token=None для тестирования, или добавьте свой
257
+ img = generate_image_replicate(enhanced_prompt, api_token=None)
258
 
259
+ # Если онлайн-API не сработали, создаем локальное изображение
260
+ if img is None:
261
+ img = generate_local_image(prompt, age)
262
 
263
+ # Сохраняем изображение
264
+ img_path = os.path.join(images_dir, f"passover_{age}_{i}_{timestamp}.png")
265
+ img.save(img_path)
266
+ image_paths.append(img_path)
267
+ images.append(img)
268
+
269
+ # Создаем HTML для просмотра и печати
270
+ html_path = os.path.join(images_dir, f"passover_coloring_pages_{age}_{timestamp}.html")
271
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
272
  with open(html_path, 'w') as f:
273
  f.write(f"""<!DOCTYPE html>
274
  <html>
 
295
  <div class="controls">
296
  <h1>Jewish Passover (Pesach) Coloring Pages</h1>
297
  <h2>For Ages {age} Years</h2>
298
+ <p>Click the button below to print all coloring pages.</p>
299
  <button class="print-button" onclick="window.print()">Print All Pages</button>
300
  </div>
301
  """)
302
 
303
+ # Добавляем каждое изображение в HTML
304
+ for i, desc in enumerate([p.split(',')[0] for p in selected_pages]):
305
  img_filename = f"passover_{age}_{i}_{timestamp}.png"
306
  f.write(f"""
307
  <div class="page">
308
+ <img src="{img_filename}" alt="{desc}">
309
+ <div class="page-title">{desc}</div>
310
  </div>
311
  """)
312
 
 
314
  </body>
315
  </html>
316
  """)
317
+
318
+ # Создаем форматированный ответ с описаниями
319
+ response = f"## Passover Coloring Pages for a {age}-year-old:\n\n"
320
+ response += "\n".join(descriptions)
321
+
322
+ # Добавляем информацию о HTML файле для просмотра/печати
323
+ response += f"\n\n**Coloring pages have been generated!**\n\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
324
  response += f"To view and print the coloring pages, please open this HTML file in your web browser:\n\n"
325
  response += f"{html_path}\n\n"
326
+ response += f"The individual image files are also available in the '{images_dir}' folder."
327
+
328
+ # Return both the text and images to final_answer
329
+ return {"text": response, "images": images}
 
 
 
 
 
 
 
 
 
 
 
 
330
 
331
+ except Exception as e:
332
+ # If image generation fails, return text description
333
+ response = f"## Passover Coloring Pages for a {age}-year-old:\n\n"
334
+ response += "\n".join(descriptions)
335
+ response += f"\n\nError generating images: {str(e)}"
336
+ return response
337
 
338
+ # Modified final answer function to handle image objects
339
+ class EnhancedFinalAnswerTool(FinalAnswerTool):
340
+ def __call__(self, answer):
341
+ # If answer is a dictionary with text and images
342
+ if isinstance(answer, dict) and "text" in answer and "images" in answer:
343
+ # Process images here if needed
344
+ # For GradioUI, we can return the dictionary directly
345
+ return answer
346
+ # Otherwise use the original behavior
347
+ return super().__call__(answer)
348
 
349
+ # Modified prompt templates to handle simple age input
 
 
 
 
 
 
350
  custom_prompt_templates = {
351
+ "react-system": """You are an helpful agent that helps children learn about Passover through coloring pages.
352
  You have access to the following tools:
353
 
354
  {tools_string}
355
 
356
+ 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.
357
+ 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.
 
 
 
358
 
359
  To use a tool, output an action in this format:
360
  ```py
 
367
  "react-assistant": "{agent_response}",
368
  }
369
 
370
+ # Setup agent
371
+ final_answer = EnhancedFinalAnswerTool()
372
+
373
+ model = HfApiModel(
374
+ max_tokens=2096,
375
+ temperature=0.5,
376
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct'
377
+ )
378
+
379
+ # Check if custom prompts should be used or merged with existing ones
380
  try:
381
  with open("prompts.yaml", 'r') as stream:
382
  prompt_templates = yaml.safe_load(stream)
383
+ # Merge the templates, giving priority to our custom ones
384
  prompt_templates.update(custom_prompt_templates)
385
  except:
386
+ # If file doesn't exist or has issues, use our custom templates
387
  prompt_templates = custom_prompt_templates
388
 
 
389
  agent = CodeAgent(
390
  model=model,
391
  tools=[final_answer, generate_passover_coloring_pages],
 
394
  prompt_templates=prompt_templates
395
  )
396
 
397
+ # Launch Gradio UI
398
+ GradioUI(agent).launch()