RozzaCreat commited on
Commit
fa7a127
·
verified ·
1 Parent(s): 5c2023a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +159 -90
app.py CHANGED
@@ -2,13 +2,42 @@ 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.
@@ -31,38 +60,39 @@ def generate_passover_coloring_pages(age: int) -> str:
31
 
32
  complexity = next(value for (low, high), value in complexity_levels.items() if low <= age <= high)
33
 
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 - printable versions on A4 size
66
  image_paths = []
67
 
68
  # Create a cover page with title
@@ -70,11 +100,18 @@ def generate_passover_coloring_pages(age: int) -> str:
70
  draw = ImageDraw.Draw(cover_img)
71
 
72
  # Add title to cover page
73
- draw.text((1240, 800), "Jewish Passover (Pesach)", fill='black', anchor='mm')
74
- draw.text((1240, 1000), "Coloring Pages", fill='black', anchor='mm')
75
- draw.text((1240, 1200), f"For Ages {age} Years", fill='black', anchor='mm')
76
- draw.text((1240, 1500), "Created for Jewish children and families", fill='black', anchor='mm')
77
- draw.text((1240, 1600), "to celebrate the story of Passover", fill='black', anchor='mm')
 
 
 
 
 
 
 
78
 
79
  # Save cover page
80
  timestamp = int(time.time())
@@ -83,86 +120,118 @@ def generate_passover_coloring_pages(age: int) -> str:
83
  cover_img.save(cover_path)
84
  image_paths.append((cover_path, cover_filename, "Cover Page"))
85
 
86
- # Create individual coloring pages
87
- for i, description in enumerate(selected_pages):
88
- # Create an A4 sized image (2480 x 3508 pixels at 300 DPI)
89
- img = Image.new('RGB', (2480, 3508), color='white')
90
- draw = ImageDraw.Draw(img)
91
-
92
- # Add a border
93
- draw.rectangle([(100, 100), (2380, 3408)], outline='black', width=4)
94
-
95
- # Add title at the top
96
- draw.text((1240, 200), description, fill='black', anchor='mm')
97
-
98
- # Add a content area for the coloring image
99
- draw.rectangle([(300, 400), (2180, 2800)], outline='black', width=2)
100
-
101
- # Add description text in the content area
102
- draw.text((1240, 1600), description, fill='black', anchor='mm')
103
- draw.text((1240, 1700), "Jewish Passover Coloring Page", fill='black', anchor='mm')
104
- draw.text((1240, 1800), f"For age: {age}", fill='black', anchor='mm')
105
-
106
- # Add footer
107
- draw.text((1240, 3300), f"Page {i+1} of {len(selected_pages)}", fill='black', anchor='mm')
108
-
109
- # Save the image with printable quality
110
- img_filename = f"passover_{age}_{i}_{timestamp}.png"
111
- img_path = os.path.join(IMAGES_DIR, img_filename)
112
- img.save(img_path, dpi=(300, 300))
113
- image_paths.append((img_path, img_filename, description))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
- # Create a simple HTML that combines all pages for easy printing
116
- html_path = os.path.join(IMAGES_DIR, f"passover_coloring_pages_{age}_{timestamp}.html")
 
117
 
118
  with open(html_path, 'w') as f:
119
- f.write("""
120
- <!DOCTYPE html>
121
- <html>
122
- <head>
123
- <title>Jewish Passover Coloring Pages</title>
124
- <style>
125
- body { font-family: Arial, sans-serif; }
126
- .page { page-break-after: always; text-align: center; }
127
- img { max-width: 100%; height: auto; }
128
- .no-print { display: block; }
129
- @media print {
130
- .no-print { display: none; }
131
- .page { margin: 0; padding: 0; }
132
- }
133
- </style>
134
- </head>
135
- <body>
136
- <div class="no-print" style="background: #f0f0f0; padding: 20px; margin-bottom: 20px; text-align: center;">
137
- <h1>Jewish Passover Coloring Pages</h1>
138
- <p>For best results, please use the print functionality of your browser to print these coloring pages.</p>
139
- <button onclick="window.print()">Print All Pages</button>
140
- </div>
141
- """)
 
 
 
 
 
 
142
 
143
- # Add each image as a page in the HTML
144
  for img_path, img_filename, description in image_paths:
145
  f.write(f"""
146
- <div class="page">
147
- <img src="{img_filename}" alt="{description}">
148
- </div>
149
- """)
 
150
 
151
  f.write("""
152
- </body>
153
- </html>
154
- """)
155
 
156
  # Create formatted response
157
  response = f"## Jewish Passover (Pesach) Coloring Pages for a {age}-year-old:\n\n"
158
- response += "\n".join([f"- {desc}" for desc in selected_pages])
159
 
160
- # Add information about the print-ready files
161
  response += f"\n\n**Coloring pages have been generated!**\n\n"
162
  response += f"To view and print the coloring pages, please open this HTML file in your web browser:\n\n"
163
  response += f"{html_path}\n\n"
164
- response += f"The individual image files are also available in the 'coloring_images' folder:\n"
165
- response += "\n".join([f"- {os.path.basename(path)}" for path, _, _ in image_paths[1:]]) # Skip cover in list
166
 
167
  # Add printing instructions
168
  response += f"\n\n**Printing Instructions:**\n"
 
2
  import os
3
  import yaml
4
  import time
5
+ import requests
6
  from PIL import Image, ImageDraw, ImageFont
7
+ from io import BytesIO
8
+ from tools.final_answer import FinalAnswerTool
9
 
10
+ # Создаем директорию для изображений
11
  IMAGES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "coloring_images")
12
  os.makedirs(IMAGES_DIR, exist_ok=True)
13
 
14
+ # Функция для генерации изображения через Hugging Face Stable Diffusion API
15
+ def generate_image_hf(prompt):
16
+ try:
17
+ # Используем Stable Diffusion XL модель через Hugging Face Inference API
18
+ API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0"
19
+ headers = {"Authorization": "Bearer hf_your_huggingface_token"} # Замените на свой токен
20
+
21
+ payload = {
22
+ "inputs": prompt,
23
+ "parameters": {
24
+ "negative_prompt": "color, colored, shading, realistic, photorealistic, detailed, 3d",
25
+ "guidance_scale": 9.0
26
+ }
27
+ }
28
+
29
+ response = requests.post(API_URL, headers=headers, json=payload)
30
+
31
+ if response.status_code == 200:
32
+ image = Image.open(BytesIO(response.content))
33
+ return image
34
+ else:
35
+ print(f"Error from HF API: {response.status_code} - {response.text}")
36
+ return None
37
+ except Exception as e:
38
+ print(f"Exception in HF image generation: {str(e)}")
39
+ return None
40
+
41
  @tool
42
  def generate_passover_coloring_pages(age: int) -> str:
43
  """Generates Jewish Passover/Pesach-themed coloring pages based on a child's age.
 
60
 
61
  complexity = next(value for (low, high), value in complexity_levels.items() if low <= age <= high)
62
 
63
+ # Enhanced prompts specifically for Jewish Passover/Pesach themes with detailed instructions for coloring pages
64
  passover_pages = {
65
  "simple": [
66
+ "Line drawing of matzah bread for a coloring page, simple black and white outline only, thick black lines on white background, no shading, no colors",
67
+ "Simple outline drawing of a Seder plate with six sections for Passover foods, black and white line art only, coloring book style, thick outlines",
68
+ "Black and white outline drawing of Afikoman (broken matzah) hidden in a napkin, simple clean lines, coloring page style",
69
+ "Simple outline drawing of a Kiddush cup for Passover, black and white line art only, coloring book style for children"
70
  ],
71
  "basic": [
72
+ "Line drawing of Moses parting the Red Sea for a coloring page, black and white outline only, simple lines, no shading",
73
+ "Black and white outline drawings of the Ten Plagues in separate boxes, coloring book style, thick lines, no shading",
74
+ "Outline drawing of the Four Questions from Haggadah with Hebrew letters, black and white line art only",
75
+ "Simple maze with Afikoman (hidden matzah) at center, black and white line drawing for coloring"
76
  ],
77
  "intermediate": [
78
+ "Black and white line drawing of a Jewish Seder table with symbolic foods, coloring book style, no shading",
79
+ "Hebrew letters spelling 'Pesach' (פסח) in decorative outline style, black and white for coloring",
80
+ "Line drawing of Israelites leaving Egypt, simple black outline on white background, coloring page style",
81
+ "Black and white outline of the Four Sons from Haggadah, simple line art for coloring"
82
  ],
83
  "advanced": [
84
+ "Intricate outline drawing of Haggadah page with Seder order, black and white line art for coloring",
85
+ "Black and white line drawing of Miriam and women with tambourines celebrating, coloring book style",
86
+ "Decorative Hebrew calligraphy outline of 'Next year in Jerusalem' (לשנה הבאה בירושלים) for coloring",
87
+ "Symbolic outline drawing of Passover journey from slavery to freedom, black and white line art only"
88
  ]
89
  }
90
 
91
  # Get descriptions for selected age group
92
  selected_pages = passover_pages[complexity]
93
+ descriptions = [prompt.split(',')[0] for prompt in selected_pages]
94
 
95
+ # Create placeholder images with descriptions
96
  image_paths = []
97
 
98
  # Create a cover page with title
 
100
  draw = ImageDraw.Draw(cover_img)
101
 
102
  # Add title to cover page
103
+ try:
104
+ font = ImageFont.truetype("Arial", 80)
105
+ small_font = ImageFont.truetype("Arial", 40)
106
+ except:
107
+ font = ImageFont.load_default()
108
+ small_font = ImageFont.load_default()
109
+
110
+ draw.text((1240, 800), "Jewish Passover (Pesach)", fill='black', anchor='mm', font=font)
111
+ draw.text((1240, 1000), "Coloring Pages", fill='black', anchor='mm', font=font)
112
+ draw.text((1240, 1200), f"For Ages {age} Years", fill='black', anchor='mm', font=font)
113
+ draw.text((1240, 1500), "Created for Jewish children and families", fill='black', anchor='mm', font=small_font)
114
+ draw.text((1240, 1600), "to celebrate the story of Passover", fill='black', anchor='mm', font=small_font)
115
 
116
  # Save cover page
117
  timestamp = int(time.time())
 
120
  cover_img.save(cover_path)
121
  image_paths.append((cover_path, cover_filename, "Cover Page"))
122
 
123
+ # Create or generate individual coloring pages
124
+ for i, (prompt, description) in enumerate(zip(selected_pages, descriptions)):
125
+ try:
126
+ # Try to use the alternative image generation API
127
+ # Add extra instructions to make sure we get proper coloring pages
128
+ full_prompt = prompt + ", coloring page style, black and white outlines only, no color, no shading, thick clean lines, suitable for children to color"
129
+
130
+ # Attempt to generate image through HF API
131
+ img = generate_image_hf(full_prompt)
132
+
133
+ if img is None:
134
+ raise Exception("Image generation failed")
135
+
136
+ # Convert to black and white line art if needed
137
+ img = img.convert('L') # Convert to grayscale
138
+ img = img.point(lambda x: 0 if x < 128 else 255, '1') # Convert to black and white
139
+
140
+ # Save the generated image
141
+ img_filename = f"passover_{age}_{i}_{timestamp}.png"
142
+ img_path = os.path.join(IMAGES_DIR, img_filename)
143
+ img.save(img_path)
144
+ image_paths.append((img_path, img_filename, description))
145
+ print(f"Generated image {i+1}/{len(selected_pages)}")
146
+
147
+ except Exception as e:
148
+ print(f"Error generating image {i}: {str(e)}")
149
+
150
+ # Create a placeholder with text if generation fails
151
+ img = Image.new('RGB', (2480, 3508), color='white') # A4 size
152
+ draw = ImageDraw.Draw(img)
153
+
154
+ # Add a border
155
+ draw.rectangle([(100, 100), (2380, 3408)], outline='black', width=4)
156
+
157
+ # Add title at the top
158
+ draw.text((1240, 200), description, fill='black', anchor='mm', font=font)
159
+
160
+ # Add a content area for the coloring image
161
+ draw.rectangle([(300, 400), (2180, 2800)], outline='black', width=2)
162
+
163
+ # Add description text in the content area
164
+ draw.text((1240, 1600), description, fill='black', anchor='mm', font=small_font)
165
+ draw.text((1240, 1700), "Jewish Passover Coloring Page", fill='black', anchor='mm', font=small_font)
166
+ draw.text((1240, 1800), f"For age: {age}", fill='black', anchor='mm', font=small_font)
167
+
168
+ # Add footer
169
+ draw.text((1240, 3300), f"Page {i+1} of {len(selected_pages)}", fill='black', anchor='mm', font=small_font)
170
+
171
+ # Save the placeholder
172
+ img_filename = f"passover_{age}_{i}_placeholder_{timestamp}.png"
173
+ img_path = os.path.join(IMAGES_DIR, img_filename)
174
+ img.save(img_path)
175
+ image_paths.append((img_path, img_filename, description))
176
 
177
+ # Create a printable HTML file
178
+ html_filename = f"passover_coloring_pages_{age}_{timestamp}.html"
179
+ html_path = os.path.join(IMAGES_DIR, html_filename)
180
 
181
  with open(html_path, 'w') as f:
182
+ f.write(f"""<!DOCTYPE html>
183
+ <html>
184
+ <head>
185
+ <title>Jewish Passover Coloring Pages - Age {age}</title>
186
+ <style>
187
+ body {{ font-family: Arial, sans-serif; max-width: 900px; margin: 0 auto; padding: 20px; }}
188
+ h1, h2 {{ color: #2c3e50; text-align: center; }}
189
+ .controls {{ background-color: #f8f9fa; padding: 15px; margin-bottom: 20px; text-align: center; border-radius: 5px; }}
190
+ .page {{ page-break-after: always; margin-bottom: 30px; }}
191
+ img {{ max-width: 100%; display: block; margin: 0 auto; border: 1px solid #ddd; }}
192
+ .page-title {{ text-align: center; margin-top: 10px; font-weight: bold; }}
193
+ .print-button {{ background-color: #3498db; color: white; border: none; padding: 10px 20px;
194
+ border-radius: 4px; cursor: pointer; font-size: 16px; }}
195
+ .print-button:hover {{ background-color: #2980b9; }}
196
+ @media print {{
197
+ .controls {{ display: none; }}
198
+ .page {{ margin-bottom: 0; }}
199
+ body {{ padding: 0; margin: 0; }}
200
+ }}
201
+ </style>
202
+ </head>
203
+ <body>
204
+ <div class="controls">
205
+ <h1>Jewish Passover (Pesach) Coloring Pages</h1>
206
+ <h2>For Ages {age} Years</h2>
207
+ <p>Click the button below to print all coloring pages.</p>
208
+ <button class="print-button" onclick="window.print()">Print All Pages</button>
209
+ </div>
210
+ """)
211
 
212
+ # Add each image to the HTML
213
  for img_path, img_filename, description in image_paths:
214
  f.write(f"""
215
+ <div class="page">
216
+ <img src="{img_filename}" alt="{description}">
217
+ <div class="page-title">{description}</div>
218
+ </div>
219
+ """)
220
 
221
  f.write("""
222
+ </body>
223
+ </html>
224
+ """)
225
 
226
  # Create formatted response
227
  response = f"## Jewish Passover (Pesach) Coloring Pages for a {age}-year-old:\n\n"
228
+ response += "\n".join([f"- {desc}" for desc in descriptions])
229
 
230
+ # Add information about the printable HTML file
231
  response += f"\n\n**Coloring pages have been generated!**\n\n"
232
  response += f"To view and print the coloring pages, please open this HTML file in your web browser:\n\n"
233
  response += f"{html_path}\n\n"
234
+ response += f"The individual image files are also available in the 'coloring_images' folder.\n"
 
235
 
236
  # Add printing instructions
237
  response += f"\n\n**Printing Instructions:**\n"