RozzaCreat commited on
Commit
ce24dcc
·
verified ·
1 Parent(s): d779116

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +103 -18
app.py CHANGED
@@ -1,8 +1,8 @@
1
  import os
2
  import sys
3
  import time
 
4
  from PIL import Image, ImageDraw, ImageFont
5
- import img2pdf # Make sure to install: pip install img2pdf
6
 
7
  # Create directories
8
  IMAGES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "coloring_images")
@@ -102,8 +102,8 @@ def generate_passover_coloring_pages(age):
102
  if "matzah" in description.lower():
103
  # Draw a simple matzah
104
  draw.ellipse([(700, 1000), (1500, 1600)], outline='black', width=3)
105
- for i in range(20):
106
- x1, y1 = 700 + i*40, 1000 + (i % 5) * 30
107
  x2, y2 = x1 + 50, y1 + 10
108
  draw.ellipse([(x1, y1), (x2, y2)], outline='black', width=1)
109
 
@@ -122,13 +122,13 @@ def generate_passover_coloring_pages(age):
122
  elif "red sea" in description.lower():
123
  # Draw the Red Sea
124
  # Waves on left
125
- for i in range(8):
126
- y = 800 + i*100
127
  draw.arc([(400, y-50), (700, y+50)], 0, 180, fill='black', width=3)
128
 
129
  # Waves on right
130
- for i in range(8):
131
- y = 800 + i*100
132
  draw.arc([(1700, y-50), (2000, y+50)], 0, 180, fill='black', width=3)
133
 
134
  # Path in middle
@@ -161,22 +161,107 @@ def generate_passover_coloring_pages(age):
161
  main_path = os.path.join(IMAGES_DIR, f"passover_{age}_{i}_{timestamp}.png")
162
  img.save(main_path)
163
 
164
- # Create a PDF using img2pdf
165
  pdf_filename = f"passover_coloring_pages_age_{age}_{timestamp}.pdf"
166
  pdf_path = os.path.join(PDF_DIR, pdf_filename)
 
167
 
 
168
  try:
169
- # Create PDF
170
- with open(pdf_path, "wb") as f:
171
- f.write(img2pdf.convert(page_paths))
172
 
173
- print(f"\nPDF successfully created at: {pdf_path}")
174
- print(f"Individual coloring pages saved in: {IMAGES_DIR}")
 
 
175
 
176
- return pdf_path
 
 
 
 
 
 
 
 
 
177
  except Exception as e:
178
- print(f"Error creating PDF: {str(e)}")
179
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
 
181
  def main():
182
  """Main function for CLI interface."""
@@ -208,9 +293,9 @@ def main():
208
  continue
209
 
210
  print(f"\nGenerating coloring pages for age {age}...")
211
- pdf_path = generate_passover_coloring_pages(age)
212
 
213
- if pdf_path:
214
  print("\nGeneration complete!")
215
 
216
  except ValueError:
 
1
  import os
2
  import sys
3
  import time
4
+ import subprocess
5
  from PIL import Image, ImageDraw, ImageFont
 
6
 
7
  # Create directories
8
  IMAGES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "coloring_images")
 
102
  if "matzah" in description.lower():
103
  # Draw a simple matzah
104
  draw.ellipse([(700, 1000), (1500, 1600)], outline='black', width=3)
105
+ for j in range(20):
106
+ x1, y1 = 700 + j*40, 1000 + (j % 5) * 30
107
  x2, y2 = x1 + 50, y1 + 10
108
  draw.ellipse([(x1, y1), (x2, y2)], outline='black', width=1)
109
 
 
122
  elif "red sea" in description.lower():
123
  # Draw the Red Sea
124
  # Waves on left
125
+ for j in range(8):
126
+ y = 800 + j*100
127
  draw.arc([(400, y-50), (700, y+50)], 0, 180, fill='black', width=3)
128
 
129
  # Waves on right
130
+ for j in range(8):
131
+ y = 800 + j*100
132
  draw.arc([(1700, y-50), (2000, y+50)], 0, 180, fill='black', width=3)
133
 
134
  # Path in middle
 
161
  main_path = os.path.join(IMAGES_DIR, f"passover_{age}_{i}_{timestamp}.png")
162
  img.save(main_path)
163
 
164
+ # Try different methods to create a PDF
165
  pdf_filename = f"passover_coloring_pages_age_{age}_{timestamp}.pdf"
166
  pdf_path = os.path.join(PDF_DIR, pdf_filename)
167
+ pdf_created = False
168
 
169
+ # Method 1: Try using PIL/Pillow (built-in)
170
  try:
171
+ # Open the first image to get the size
172
+ first_img = Image.open(page_paths[0]).convert('RGB')
 
173
 
174
+ # Create a list of RGB images
175
+ images = []
176
+ for img_path in page_paths[1:]: # Skip the first one as we already opened it
177
+ images.append(Image.open(img_path).convert('RGB'))
178
 
179
+ # Save as PDF
180
+ first_img.save(
181
+ pdf_path,
182
+ "PDF",
183
+ resolution=100.0,
184
+ save_all=True,
185
+ append_images=images
186
+ )
187
+ pdf_created = True
188
+ print(f"\nPDF created with Pillow: {pdf_path}")
189
  except Exception as e:
190
+ print(f"Pillow PDF creation failed: {str(e)}")
191
+
192
+ # Method 2: Try using ImageMagick if available
193
+ if not pdf_created:
194
+ try:
195
+ convert_cmd = ["convert"]
196
+ convert_cmd.extend(page_paths)
197
+ convert_cmd.append(pdf_path)
198
+ subprocess.run(convert_cmd, check=True)
199
+ pdf_created = True
200
+ print(f"\nPDF created with ImageMagick: {pdf_path}")
201
+ except (subprocess.SubprocessError, FileNotFoundError):
202
+ print("ImageMagick not available, trying alternative method...")
203
+
204
+ # Create an alternative HTML file that can be printed to PDF by the user
205
+ if not pdf_created:
206
+ html_path = os.path.join(IMAGES_DIR, f"passover_coloring_pages_{age}_{timestamp}.html")
207
+
208
+ with open(html_path, 'w') as f:
209
+ f.write(f"""<!DOCTYPE html>
210
+ <html>
211
+ <head>
212
+ <title>Jewish Passover Coloring Pages - Age {age}</title>
213
+ <style>
214
+ body {{ font-family: Arial, sans-serif; max-width: 900px; margin: 0 auto; padding: 20px; }}
215
+ h1, h2 {{ color: #2c3e50; text-align: center; }}
216
+ .controls {{ background-color: #f8f9fa; padding: 15px; margin-bottom: 20px; text-align: center; border-radius: 5px; }}
217
+ .page {{ page-break-after: always; margin-bottom: 30px; }}
218
+ img {{ max-width: 100%; display: block; margin: 0 auto; border: 1px solid #ddd; }}
219
+ .page-title {{ text-align: center; margin-top: 10px; font-weight: bold; }}
220
+ .print-button {{ background-color: #3498db; color: white; border: none; padding: 10px 20px;
221
+ border-radius: 4px; cursor: pointer; font-size: 16px; }}
222
+ .print-button:hover {{ background-color: #2980b9; }}
223
+ @media print {{
224
+ .controls {{ display: none; }}
225
+ .page {{ margin-bottom: 0; }}
226
+ body {{ padding: 0; margin: 0; }}
227
+ }}
228
+ </style>
229
+ </head>
230
+ <body>
231
+ <div class="controls">
232
+ <h1>Jewish Passover (Pesach) Coloring Pages</h1>
233
+ <h2>For Ages {age} Years</h2>
234
+ <p>PDF creation failed. Please use your browser's print function to save as PDF.</p>
235
+ <p>Choose "Save as PDF" in the print dialog.</p>
236
+ <button class="print-button" onclick="window.print()">Print / Save as PDF</button>
237
+ </div>
238
+ """)
239
+
240
+ # Add relative paths to the saved images in the main directory
241
+ for i, _ in enumerate(selected_pages):
242
+ img_filename = f"passover_{age}_{i}_{timestamp}.png"
243
+ f.write(f"""
244
+ <div class="page">
245
+ <img src="{img_filename}" alt="Coloring Page {i+1}">
246
+ <div class="page-title">{selected_pages[i]}</div>
247
+ </div>
248
+ """)
249
+
250
+ f.write("""
251
+ </body>
252
+ </html>
253
+ """)
254
+
255
+ print(f"\nPDF creation failed, but HTML created: {html_path}")
256
+ print("You can open this HTML file in your browser and use 'Print' to save as PDF.")
257
+
258
+ # Print summary
259
+ print(f"\nIndividual coloring pages saved in: {IMAGES_DIR}")
260
+
261
+ if pdf_created:
262
+ return pdf_path
263
+ else:
264
+ return html_path
265
 
266
  def main():
267
  """Main function for CLI interface."""
 
293
  continue
294
 
295
  print(f"\nGenerating coloring pages for age {age}...")
296
+ output_path = generate_passover_coloring_pages(age)
297
 
298
+ if output_path:
299
  print("\nGeneration complete!")
300
 
301
  except ValueError: