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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -74
app.py CHANGED
@@ -4,15 +4,10 @@ import yaml
4
  import time
5
  from tools.final_answer import FinalAnswerTool
6
  from PIL import Image, ImageDraw, ImageFont
7
- from reportlab.lib.pagesizes import letter, A4
8
- from reportlab.pdfgen import canvas
9
- from reportlab.lib.utils import ImageReader
10
 
11
- # Создаем директории для изображений и PDF
12
  IMAGES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "coloring_images")
13
- PDF_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "coloring_pdf")
14
  os.makedirs(IMAGES_DIR, exist_ok=True)
15
- os.makedirs(PDF_DIR, exist_ok=True)
16
 
17
  @tool
18
  def generate_passover_coloring_pages(age: int) -> str:
@@ -67,90 +62,115 @@ def generate_passover_coloring_pages(age: int) -> str:
67
  # Get descriptions for selected age group
68
  selected_pages = passover_pages[complexity]
69
 
70
- # Create placeholder images with descriptions
71
  image_paths = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  for i, description in enumerate(selected_pages):
73
- # Create a simple placeholder image with text
74
- img = Image.new('RGB', (800, 600), color='white')
75
  draw = ImageDraw.Draw(img)
76
 
77
  # Add a border
78
- draw.rectangle([(10, 10), (790, 590)], outline='black', width=2)
79
 
80
- # Write the description
81
- draw.text((400, 300), description, fill='black', anchor='mm')
82
- draw.text((400, 350), "Jewish Passover Coloring Page", fill='black', anchor='mm')
83
- draw.text((400, 400), f"For age: {age}", fill='black', anchor='mm')
84
 
85
- # Save the image
86
- timestamp = int(time.time())
 
 
 
 
 
 
 
 
 
 
87
  img_filename = f"passover_{age}_{i}_{timestamp}.png"
88
  img_path = os.path.join(IMAGES_DIR, img_filename)
89
- img.save(img_path)
90
  image_paths.append((img_path, img_filename, description))
91
 
92
- # Create a PDF with all coloring pages
93
- timestamp = int(time.time())
94
- pdf_filename = f"passover_coloring_pages_age_{age}_{timestamp}.pdf"
95
- pdf_path = os.path.join(PDF_DIR, pdf_filename)
96
-
97
- # Create PDF
98
- c = canvas.Canvas(pdf_path, pagesize=A4)
99
- width, height = A4 # A4 размер для PDF
100
-
101
- # Добавляем титульную страницу
102
- c.setFont("Helvetica-Bold", 24)
103
- c.drawCentredString(width/2, height-100, f"Jewish Passover (Pesach)")
104
- c.drawCentredString(width/2, height-130, f"Coloring Pages")
105
- c.setFont("Helvetica", 18)
106
- c.drawCentredString(width/2, height-170, f"For Ages {age} Years")
107
- c.setFont("Helvetica", 12)
108
- c.drawCentredString(width/2, height-220, "Created with love for Jewish children and families")
109
- c.drawCentredString(width/2, height-240, "to celebrate the story of Passover.")
110
 
111
- # Add each coloring page as a separate page in the PDF
112
- for img_path, _, description in image_paths:
113
- c.showPage() # Start a new page
114
-
115
- # Add a descriptive title
116
- c.setFont("Helvetica-Bold", 16)
117
- c.drawCentredString(width/2, height-50, description)
118
-
119
- # Calculate image size to fit on page with margins
120
- page_width = width - 100 # 50px margin on each side
121
- page_height = height - 150 # 100px top margin, 50px bottom margin
122
-
123
- # Open the image with PIL
124
- img = Image.open(img_path)
125
- img_width, img_height = img.size
 
 
 
 
 
 
 
 
 
126
 
127
- # Calculate scale to fit within page
128
- width_ratio = page_width / img_width
129
- height_ratio = page_height / img_height
130
- scale = min(width_ratio, height_ratio)
 
 
 
131
 
132
- new_width = img_width * scale
133
- new_height = img_height * scale
134
-
135
- # Calculate position to center image on page
136
- x = (width - new_width) / 2
137
- y = height - 100 - new_height # 100px from top of page
138
-
139
- # Draw the image
140
- c.drawImage(ImageReader(img), x, y, width=new_width, height=new_height)
141
-
142
- # Save the PDF
143
- c.save()
144
 
145
  # Create formatted response
146
  response = f"## Jewish Passover (Pesach) Coloring Pages for a {age}-year-old:\n\n"
147
  response += "\n".join([f"- {desc}" for desc in selected_pages])
148
 
149
- # Add information about the PDF
150
- response += f"\n\n**Coloring pages have been generated as a PDF!**\n\n"
151
- response += f"To view and print the coloring pages, please open this PDF file:\n\n"
152
- response += f"{pdf_path}\n\n"
153
- response += f"The individual image files are also available in the 'coloring_images' folder."
 
 
 
 
 
 
 
 
 
154
 
155
  return response
156
 
@@ -242,12 +262,12 @@ try:
242
 
243
  with gr.Blocks() as demo:
244
  gr.Markdown("# Jewish Passover (Pesach) Coloring Pages Generator")
245
- gr.Markdown("### Generates coloring pages as a convenient PDF file")
246
 
247
  with gr.Row():
248
  with gr.Column():
249
  input_box = gr.Number(label="Enter child's age (1-12)", minimum=1, maximum=12, step=1)
250
- submit_btn = gr.Button("Generate Coloring Pages PDF")
251
 
252
  with gr.Row():
253
  output_text = gr.Markdown()
@@ -262,7 +282,7 @@ try:
262
  result = generate_passover_coloring_pages(int(age))
263
 
264
  # Add a clearer message
265
- 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."
266
 
267
  return result
268
  except Exception as e:
 
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:
 
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
69
+ cover_img = Image.new('RGB', (2480, 3508), color='white') # A4 size at 300 DPI
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())
81
+ cover_filename = f"passover_{age}_cover_{timestamp}.png"
82
+ cover_path = os.path.join(IMAGES_DIR, cover_filename)
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"
169
+ response += f"1. Open the HTML file in a web browser\n"
170
+ response += f"2. Click the 'Print All Pages' button\n"
171
+ response += f"3. In the print dialog, make sure 'Background Graphics' is enabled\n"
172
+ response += f"4. Select your printer and print\n\n"
173
+ response += f"You can also print individual pages by opening the PNG files directly."
174
 
175
  return response
176
 
 
262
 
263
  with gr.Blocks() as demo:
264
  gr.Markdown("# Jewish Passover (Pesach) Coloring Pages Generator")
265
+ gr.Markdown("### Generates print-ready coloring pages that can be printed from your browser")
266
 
267
  with gr.Row():
268
  with gr.Column():
269
  input_box = gr.Number(label="Enter child's age (1-12)", minimum=1, maximum=12, step=1)
270
+ submit_btn = gr.Button("Generate Coloring Pages")
271
 
272
  with gr.Row():
273
  output_text = gr.Markdown()
 
282
  result = generate_passover_coloring_pages(int(age))
283
 
284
  # Add a clearer message
285
+ result += f"\n\n**Note:** Gradio cannot display the coloring pages directly. Please use the HTML file mentioned above to view and print them."
286
 
287
  return result
288
  except Exception as e: