RozzaCreat commited on
Commit
cbb8f5d
·
verified ·
1 Parent(s): b4e3e0c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -333
app.py CHANGED
@@ -1,338 +1,45 @@
1
- import os
2
- import sys
3
- import time
4
- from PIL import Image, ImageDraw, ImageFont
5
 
6
- # Create directories
7
- IMAGES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "coloring_images")
8
- PDF_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "coloring_pdf")
9
- os.makedirs(IMAGES_DIR, exist_ok=True)
10
- os.makedirs(PDF_DIR, exist_ok=True)
11
-
12
- def generate_passover_coloring_pages(age):
13
- """Generate Passover-themed coloring pages based on a child's age."""
14
- if not isinstance(age, int) or not (1 <= age <= 12):
15
- print("Error: Please provide a valid age between 1 and 12.")
16
- return None
17
-
18
- complexity_levels = {
19
- (1, 3): "simple",
20
- (4, 6): "basic",
21
- (7, 9): "intermediate",
22
- (10, 12): "advanced"
23
- }
24
-
25
- complexity = next(value for (low, high), value in complexity_levels.items() if low <= age <= high)
26
-
27
- passover_pages = {
28
- "simple": [
29
- "Matzah for Passover",
30
- "Seder plate outline",
31
- "Afikoman hidden in fabric",
32
- "Kiddush cup for Passover"
33
- ],
34
- "basic": [
35
- "Moses parting the Red Sea",
36
- "Ten Plagues illustrations",
37
- "Four Questions from Haggadah",
38
- "Afikoman hunt maze"
39
- ],
40
- "intermediate": [
41
- "Jewish Seder table with symbolic foods",
42
- "Hebrew letters spelling Pesach",
43
- "Israelites leaving Egypt scene",
44
- "Four Sons from the Haggadah"
45
- ],
46
- "advanced": [
47
- "Haggadah page with Seder order",
48
- "Miriam and women celebrating after Red Sea",
49
- "Hebrew calligraphy Next year in Jerusalem",
50
- "Passover journey from slavery to freedom"
51
- ]
52
- }
53
-
54
- selected_pages = passover_pages[complexity]
55
-
56
- # Generate and save images
57
- timestamp = int(time.time())
58
- temp_dir = os.path.join(IMAGES_DIR, f"temp_{timestamp}")
59
- os.makedirs(temp_dir, exist_ok=True)
60
-
61
- # Always use default font to avoid font loading issues
62
- font = ImageFont.load_default()
63
-
64
- # Create a cover page
65
- cover_img = Image.new('RGB', (2480, 3508), color='white') # A4 size at 300 DPI
66
- draw = ImageDraw.Draw(cover_img)
67
-
68
- # Add title to cover page - using simple text placement
69
- draw_centered_text(draw, "Jewish Passover (Pesach)", 1240, 800, font)
70
- draw_centered_text(draw, "Coloring Pages", 1240, 1000, font)
71
- draw_centered_text(draw, f"For Ages {age} Years", 1240, 1200, font)
72
- draw_centered_text(draw, "Created for Jewish children and families", 1240, 1500, font)
73
- draw_centered_text(draw, "to celebrate the story of Passover", 1240, 1600, font)
74
-
75
- # Save cover page
76
- cover_path = os.path.join(temp_dir, f"01_cover.png")
77
- cover_img.save(cover_path)
78
-
79
- # Create individual coloring pages
80
- page_paths = [cover_path]
81
- for i, description in enumerate(selected_pages):
82
- # Create an A4 sized image
83
- img = Image.new('RGB', (2480, 3508), color='white')
84
- draw = ImageDraw.Draw(img)
85
-
86
- # Add a border
87
- draw.rectangle([(100, 100), (2380, 3408)], outline='black', width=4)
88
-
89
- # Add title at the top
90
- draw_centered_text(draw, description, 1240, 200, font)
91
-
92
- # Add a content area for the coloring image
93
- draw.rectangle([(300, 400), (2180, 2800)], outline='black', width=2)
94
-
95
- # Add specific elements based on the description
96
- if "matzah" in description.lower():
97
- # Draw a simple matzah
98
- draw.ellipse([(700, 1000), (1500, 1600)], outline='black', width=3)
99
- for j in range(20):
100
- x1, y1 = 700 + j*40, 1000 + (j % 5) * 30
101
- x2, y2 = x1 + 50, y1 + 10
102
- draw.ellipse([(x1, y1), (x2, y2)], outline='black', width=1)
103
-
104
- elif "seder plate" in description.lower():
105
- # Draw a Seder plate
106
- draw.ellipse([(700, 800), (1800, 1900)], outline='black', width=3)
107
- # Sections on the plate
108
- draw.line([(1250, 800), (1250, 1900)], fill='black', width=2)
109
- draw.line([(700, 1350), (1800, 1350)], fill='black', width=2)
110
- # Add section labels
111
- sections = ["Karpas", "Charoset", "Maror", "Zeroa", "Beitzah", "Chazeret"]
112
- positions = [(975, 1075), (1525, 1075), (975, 1625), (1525, 1625), (1250, 1075), (1250, 1625)]
113
- for section, pos in zip(sections, positions):
114
- draw_centered_text(draw, section, pos[0], pos[1], font)
115
-
116
- elif "red sea" in description.lower():
117
- # Draw the Red Sea
118
- # Waves on left
119
- for j in range(8):
120
- y = 800 + j*100
121
- draw.arc([(400, y-50), (700, y+50)], 0, 180, fill='black', width=3)
122
-
123
- # Waves on right
124
- for j in range(8):
125
- y = 800 + j*100
126
- draw.arc([(1700, y-50), (2000, y+50)], 0, 180, fill='black', width=3)
127
-
128
- # Path in middle
129
- draw.rectangle([(1050, 600), (1350, 2600)], outline='black', width=3)
130
-
131
- elif "hebrew" in description.lower() and "pesach" in description.lower():
132
- # Draw a simple symbol instead of Hebrew text to avoid font issues
133
- draw.rectangle([(900, 1300), (1100, 1500)], outline='black', width=3)
134
- draw.rectangle([(1200, 1300), (1400, 1500)], outline='black', width=3)
135
- draw.rectangle([(1500, 1300), (1700, 1500)], outline='black', width=3)
136
-
137
- # Add text labels
138
- draw_centered_text(draw, "P", 1000, 1400, font)
139
- draw_centered_text(draw, "E", 1300, 1400, font)
140
- draw_centered_text(draw, "S", 1600, 1400, font)
141
- draw_centered_text(draw, "PESACH", 1300, 1600, font)
142
-
143
- # Add description
144
- draw_centered_text(draw, description, 1240, 1600, font)
145
- draw_centered_text(draw, "Jewish Passover Coloring Page", 1240, 1700, font)
146
- draw_centered_text(draw, f"For age: {age}", 1240, 1800, font)
147
-
148
- # Add footer
149
- draw_centered_text(draw, f"Page {i+1} of {len(selected_pages)}", 1240, 3300, font)
150
-
151
- # Save with sequential numbering for proper PDF ordering
152
- seq_num = i + 2 # Start from 2 after the cover page
153
- page_path = os.path.join(temp_dir, f"{seq_num:02d}_{i+1}.png")
154
- img.save(page_path)
155
- page_paths.append(page_path)
156
-
157
- # Also save a copy in the main images directory
158
- main_path = os.path.join(IMAGES_DIR, f"passover_{age}_{i}_{timestamp}.png")
159
- img.save(main_path)
160
-
161
- # Try to create a PDF using Pillow
162
- pdf_filename = f"passover_coloring_pages_age_{age}_{timestamp}.pdf"
163
- pdf_path = os.path.join(PDF_DIR, pdf_filename)
164
-
165
  try:
166
- # Open the first image to get the size
167
- first_img = Image.open(page_paths[0]).convert('RGB')
168
-
169
- # Create a list of RGB images
170
- images = []
171
- for img_path in page_paths[1:]: # Skip the first one as we already opened it
172
- images.append(Image.open(img_path).convert('RGB'))
173
-
174
- # Save as PDF
175
- first_img.save(
176
- pdf_path,
177
- "PDF",
178
- resolution=100.0,
179
- save_all=True,
180
- append_images=images
181
- )
182
- print(f"\nPDF created successfully: {pdf_path}")
183
-
184
- # Create HTML as backup
185
- html_path = os.path.join(IMAGES_DIR, f"passover_coloring_pages_{age}_{timestamp}.html")
186
-
187
- with open(html_path, 'w') as f:
188
- f.write(f"""<!DOCTYPE html>
189
- <html>
190
- <head>
191
- <title>Jewish Passover Coloring Pages - Age {age}</title>
192
- <style>
193
- body {{ font-family: Arial, sans-serif; max-width: 900px; margin: 0 auto; padding: 20px; }}
194
- h1, h2 {{ color: #2c3e50; text-align: center; }}
195
- .controls {{ background-color: #f8f9fa; padding: 15px; margin-bottom: 20px; text-align: center; border-radius: 5px; }}
196
- .page {{ page-break-after: always; margin-bottom: 30px; }}
197
- img {{ max-width: 100%; display: block; margin: 0 auto; border: 1px solid #ddd; }}
198
- .page-title {{ text-align: center; margin-top: 10px; font-weight: bold; }}
199
- .print-button {{ background-color: #3498db; color: white; border: none; padding: 10px 20px;
200
- border-radius: 4px; cursor: pointer; font-size: 16px; }}
201
- .print-button:hover {{ background-color: #2980b9; }}
202
- @media print {{
203
- .controls {{ display: none; }}
204
- .page {{ margin-bottom: 0; }}
205
- body {{ padding: 0; margin: 0; }}
206
- }}
207
- </style>
208
- </head>
209
- <body>
210
- <div class="controls">
211
- <h1>Jewish Passover (Pesach) Coloring Pages</h1>
212
- <h2>For Ages {age} Years</h2>
213
- <p>Printable coloring pages are available below. You can also open the PDF directly.</p>
214
- <p>PDF path: {pdf_path}</p>
215
- <button class="print-button" onclick="window.print()">Print All Pages</button>
216
- </div>
217
- """)
218
-
219
- # Add relative paths to the saved images in the main directory
220
- for i, desc in enumerate(selected_pages):
221
- img_filename = f"passover_{age}_{i}_{timestamp}.png"
222
- f.write(f"""
223
- <div class="page">
224
- <img src="{img_filename}" alt="Coloring Page {i+1}">
225
- <div class="page-title">{desc}</div>
226
- </div>
227
- """)
228
-
229
- f.write("""
230
- </body>
231
- </html>
232
- """)
233
-
234
- print(f"HTML backup created: {html_path}")
235
- print(f"\nIndividual coloring pages saved in: {IMAGES_DIR}")
236
-
237
- return pdf_path
238
-
239
  except Exception as e:
240
- print(f"Error creating PDF: {str(e)}")
241
-
242
- # Create HTML as fallback
243
- html_path = os.path.join(IMAGES_DIR, f"passover_coloring_pages_{age}_{timestamp}.html")
244
-
245
- with open(html_path, 'w') as f:
246
- f.write(f"""<!DOCTYPE html>
247
- <html>
248
- <head>
249
- <title>Jewish Passover Coloring Pages - Age {age}</title>
250
- <style>
251
- body {{ font-family: Arial, sans-serif; max-width: 900px; margin: 0 auto; padding: 20px; }}
252
- h1, h2 {{ color: #2c3e50; text-align: center; }}
253
- .controls {{ background-color: #f8f9fa; padding: 15px; margin-bottom: 20px; text-align: center; border-radius: 5px; }}
254
- .page {{ page-break-after: always; margin-bottom: 30px; }}
255
- img {{ max-width: 100%; display: block; margin: 0 auto; border: 1px solid #ddd; }}
256
- .page-title {{ text-align: center; margin-top: 10px; font-weight: bold; }}
257
- .print-button {{ background-color: #3498db; color: white; border: none; padding: 10px 20px;
258
- border-radius: 4px; cursor: pointer; font-size: 16px; }}
259
- .print-button:hover {{ background-color: #2980b9; }}
260
- @media print {{
261
- .controls {{ display: none; }}
262
- .page {{ margin-bottom: 0; }}
263
- body {{ padding: 0; margin: 0; }}
264
- }}
265
- </style>
266
- </head>
267
- <body>
268
- <div class="controls">
269
- <h1>Jewish Passover (Pesach) Coloring Pages</h1>
270
- <h2>For Ages {age} Years</h2>
271
- <p>PDF creation failed. Please use your browser's print function to save as PDF.</p>
272
- <p>Choose "Save as PDF" in the print dialog.</p>
273
- <button class="print-button" onclick="window.print()">Print / Save as PDF</button>
274
- </div>
275
- """)
276
-
277
- # Add relative paths to the saved images in the main directory
278
- for i, desc in enumerate(selected_pages):
279
- img_filename = f"passover_{age}_{i}_{timestamp}.png"
280
- f.write(f"""
281
- <div class="page">
282
- <img src="{img_filename}" alt="Coloring Page {i+1}">
283
- <div class="page-title">{desc}</div>
284
- </div>
285
- """)
286
-
287
- f.write("""
288
- </body>
289
- </html>
290
- """)
291
-
292
- print(f"\nPDF creation failed, but HTML created: {html_path}")
293
- print("You can open this HTML file in your browser and use 'Print' to save as PDF.")
294
- print(f"\nIndividual coloring pages saved in: {IMAGES_DIR}")
295
-
296
- return html_path
297
 
298
- # Helper function to draw centered text without relying on font-specific anchor points
299
- def draw_centered_text(draw, text, x, y, font):
300
- # Get the text size
301
- try:
302
- text_width, text_height = draw.textsize(text, font=font)
303
- except:
304
- # Estimate text size for older PIL versions or if textsize fails
305
- text_width = len(text) * 7 # Rough estimate
306
- text_height = 12
307
-
308
- # Calculate position for centered text
309
- text_x = x - (text_width // 2)
310
- text_y = y - (text_height // 2)
311
-
312
- # Draw the text
313
- draw.text((text_x, text_y), text, fill='black', font=font)
314
 
315
- if __name__ == "__main__":
316
- print("===== Jewish Passover Coloring Pages Generator =====")
317
-
318
- # Default age
319
- default_age = 7
320
-
321
- # Look for age in command-line arguments
322
- if len(sys.argv) > 1:
323
- try:
324
- default_age = int(sys.argv[1])
325
- if not (1 <= default_age <= 12):
326
- print("Invalid age provided. Using default age 7.")
327
- default_age = 7
328
- except ValueError:
329
- print("Invalid age format. Using default age 7.")
330
-
331
- print(f"Generating coloring pages for age {default_age}...")
332
- output_path = generate_passover_coloring_pages(default_age)
333
-
334
- if output_path:
335
- print("\nGeneration complete!")
336
- print(f"Files saved to: {output_path}")
337
- else:
338
- print("\nGeneration failed.")
 
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 generate_darwin_coloring_page(theme: str) -> str:
8
+ """Generates a Darwin-themed coloring page based on the given theme.
9
+ Args:
10
+ theme: The theme for the coloring page.
11
+ Returns:
12
+ A generated image URL.
13
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  try:
15
+ image_generation_tool = load_tool("black-forest-labs/FLUX.1-schnell", trust_remote_code=True)
16
+ image = image_generation_tool(theme)
17
+ return image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  except Exception as e:
19
+ return f"Error generating coloring page: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ with open("prompts.yaml", 'r') as stream:
31
+ prompt_templates = yaml.safe_load(stream)
32
+
33
+ agent = CodeAgent(
34
+ model=model,
35
+ tools=[final_answer, generate_darwin_coloring_page],
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
+ GradioUI(agent).launch()