Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,11 +8,11 @@ import tempfile
|
|
| 8 |
import os
|
| 9 |
import time
|
| 10 |
import shutil
|
| 11 |
-
from PIL import Image
|
| 12 |
from tools.final_answer import FinalAnswerTool
|
| 13 |
from Gradio_UI import GradioUI
|
| 14 |
|
| 15 |
-
# Создаем постоянную директорию для хранения изображений
|
| 16 |
IMAGES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "coloring_images")
|
| 17 |
os.makedirs(IMAGES_DIR, exist_ok=True)
|
| 18 |
|
|
@@ -68,73 +68,133 @@ def generate_passover_coloring_pages(age: int) -> str:
|
|
| 68 |
selected_pages = passover_pages[complexity]
|
| 69 |
descriptions = [page.split(',')[0] if ',' in page else page for page in selected_pages]
|
| 70 |
|
| 71 |
-
#
|
| 72 |
-
for file in os.listdir(IMAGES_DIR):
|
| 73 |
-
if file.endswith(".png"):
|
| 74 |
-
file_path = os.path.join(IMAGES_DIR, file)
|
| 75 |
-
try:
|
| 76 |
-
os.remove(file_path)
|
| 77 |
-
except:
|
| 78 |
-
pass
|
| 79 |
-
|
| 80 |
-
# Создаем заглушки для изображений на случай сбоя в генерации
|
| 81 |
def create_placeholder_image(description, index):
|
| 82 |
img = Image.new('RGB', (800, 600), color='white')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
return img
|
| 84 |
|
| 85 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
try:
|
| 87 |
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
| 88 |
|
| 89 |
-
#
|
| 90 |
-
|
| 91 |
-
for page in selected_pages:
|
| 92 |
-
enhanced_prompts.append(f"{page}, Jewish traditional Passover symbols only, no Christian imagery, suitable for printing as a coloring page")
|
| 93 |
-
|
| 94 |
-
# Сохраняем пути к изображениям
|
| 95 |
-
image_paths = []
|
| 96 |
-
|
| 97 |
-
# Генерируем и сохраняем изображения
|
| 98 |
-
for i, prompt in enumerate(enhanced_prompts):
|
| 99 |
try:
|
| 100 |
-
img = image_generation_tool(prompt)
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
img_path = os.path.join(IMAGES_DIR, f"passover_{age}_{i}_{timestamp}.png")
|
| 104 |
img.save(img_path)
|
| 105 |
image_paths.append(img_path)
|
|
|
|
|
|
|
| 106 |
except Exception as e:
|
| 107 |
-
#
|
| 108 |
-
placeholder = create_placeholder_image(
|
| 109 |
-
|
|
|
|
| 110 |
placeholder.save(img_path)
|
| 111 |
image_paths.append(img_path)
|
|
|
|
| 112 |
print(f"Error generating image {i}: {str(e)}")
|
| 113 |
-
|
| 114 |
-
# Создаем форматированный ответ с описаниями
|
| 115 |
-
response = f"## Jewish Passover (Pesach) Coloring Pages for a {age}-year-old:\n\n"
|
| 116 |
-
response += "\n".join([f"- {desc}" for desc in descriptions])
|
| 117 |
-
|
| 118 |
-
# Сохраняем пути к изображениям в ответе в специальном формате
|
| 119 |
-
image_paths_str = "||".join(image_paths)
|
| 120 |
-
return f"{response}\n\nIMAGE_PATHS:{image_paths_str}"
|
| 121 |
|
| 122 |
except Exception as e:
|
| 123 |
-
#
|
| 124 |
-
response = f"## Jewish Passover (Pesach) Coloring Pages for a {age}-year-old:\n\n"
|
| 125 |
-
response += "\n".join([f"- {desc}" for desc in descriptions])
|
| 126 |
-
|
| 127 |
-
# Создаем заглушки для каждого описания
|
| 128 |
-
image_paths = []
|
| 129 |
for i, desc in enumerate(descriptions):
|
| 130 |
placeholder = create_placeholder_image(desc, i)
|
| 131 |
-
|
|
|
|
| 132 |
placeholder.save(img_path)
|
| 133 |
image_paths.append(img_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
-
#
|
| 136 |
-
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
# Custom UI wrapper to handle image display
|
| 140 |
class CustomGradioUI(GradioUI):
|
|
@@ -178,16 +238,16 @@ class CustomGradioUI(GradioUI):
|
|
| 178 |
if "IMAGE_PATHS:" in result:
|
| 179 |
paths_part = result.split("IMAGE_PATHS:")[1]
|
| 180 |
image_paths = paths_part.split("||")
|
| 181 |
-
#
|
| 182 |
result = result.split("\n\nIMAGE_PATHS:")[0]
|
| 183 |
|
| 184 |
-
#
|
| 185 |
if not image_paths:
|
| 186 |
for file in os.listdir(IMAGES_DIR):
|
| 187 |
if file.endswith('.png') and f"passover_{age}_" in file:
|
| 188 |
image_paths.append(os.path.join(IMAGES_DIR, file))
|
| 189 |
|
| 190 |
-
#
|
| 191 |
valid_image_paths = [path for path in image_paths if os.path.exists(path)]
|
| 192 |
|
| 193 |
# Return the result and image paths
|
|
|
|
| 8 |
import os
|
| 9 |
import time
|
| 10 |
import shutil
|
| 11 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 12 |
from tools.final_answer import FinalAnswerTool
|
| 13 |
from Gradio_UI import GradioUI
|
| 14 |
|
| 15 |
+
# Создаем постоянную директорию для хранения изображений и HTML
|
| 16 |
IMAGES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "coloring_images")
|
| 17 |
os.makedirs(IMAGES_DIR, exist_ok=True)
|
| 18 |
|
|
|
|
| 68 |
selected_pages = passover_pages[complexity]
|
| 69 |
descriptions = [page.split(',')[0] if ',' in page else page for page in selected_pages]
|
| 70 |
|
| 71 |
+
# Create placeholder images function
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
def create_placeholder_image(description, index):
|
| 73 |
img = Image.new('RGB', (800, 600), color='white')
|
| 74 |
+
draw = ImageDraw.Draw(img)
|
| 75 |
+
draw.rectangle([(10, 10), (790, 590)], outline='black', width=2)
|
| 76 |
+
|
| 77 |
+
# Add text
|
| 78 |
+
draw.text((400, 300), description.split(',')[0] if ',' in description else description,
|
| 79 |
+
fill='black', anchor='mm')
|
| 80 |
+
draw.text((400, 350), "Jewish Passover Coloring Page", fill='black', anchor='mm')
|
| 81 |
+
draw.text((400, 400), f"For age: {age}", fill='black', anchor='mm')
|
| 82 |
+
|
| 83 |
return img
|
| 84 |
|
| 85 |
+
# Generate and save images
|
| 86 |
+
image_paths = []
|
| 87 |
+
actual_files = []
|
| 88 |
+
timestamp = int(time.time())
|
| 89 |
+
|
| 90 |
try:
|
| 91 |
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
| 92 |
|
| 93 |
+
# Generate images
|
| 94 |
+
for i, (prompt, desc) in enumerate(zip(selected_pages, descriptions)):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
try:
|
| 96 |
+
img = image_generation_tool(f"{prompt}, Jewish traditional Passover symbols only, no Christian imagery, suitable for printing as a coloring page")
|
| 97 |
+
img_filename = f"passover_{age}_{i}_{timestamp}.png"
|
| 98 |
+
img_path = os.path.join(IMAGES_DIR, img_filename)
|
|
|
|
| 99 |
img.save(img_path)
|
| 100 |
image_paths.append(img_path)
|
| 101 |
+
actual_files.append((img_filename, desc))
|
| 102 |
+
|
| 103 |
except Exception as e:
|
| 104 |
+
# Create placeholder if image generation fails
|
| 105 |
+
placeholder = create_placeholder_image(desc, i)
|
| 106 |
+
img_filename = f"passover_{age}_{i}_placeholder_{timestamp}.png"
|
| 107 |
+
img_path = os.path.join(IMAGES_DIR, img_filename)
|
| 108 |
placeholder.save(img_path)
|
| 109 |
image_paths.append(img_path)
|
| 110 |
+
actual_files.append((img_filename, desc))
|
| 111 |
print(f"Error generating image {i}: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
except Exception as e:
|
| 114 |
+
# If all image generation fails, create placeholders
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
for i, desc in enumerate(descriptions):
|
| 116 |
placeholder = create_placeholder_image(desc, i)
|
| 117 |
+
img_filename = f"passover_{age}_{i}_placeholder_{timestamp}.png"
|
| 118 |
+
img_path = os.path.join(IMAGES_DIR, img_filename)
|
| 119 |
placeholder.save(img_path)
|
| 120 |
image_paths.append(img_path)
|
| 121 |
+
actual_files.append((img_filename, desc))
|
| 122 |
+
|
| 123 |
+
# Create a printable HTML file
|
| 124 |
+
html_filename = f"passover_coloring_pages_{age}_{timestamp}.html"
|
| 125 |
+
html_path = os.path.join(IMAGES_DIR, html_filename)
|
| 126 |
+
|
| 127 |
+
with open(html_path, 'w') as f:
|
| 128 |
+
f.write(f"""<!DOCTYPE html>
|
| 129 |
+
<html>
|
| 130 |
+
<head>
|
| 131 |
+
<title>Jewish Passover Coloring Pages - Age {age}</title>
|
| 132 |
+
<style>
|
| 133 |
+
body {{ font-family: Arial, sans-serif; max-width: 900px; margin: 0 auto; padding: 20px; }}
|
| 134 |
+
h1, h2 {{ color: #2c3e50; text-align: center; }}
|
| 135 |
+
.controls {{ background-color: #f8f9fa; padding: 15px; margin-bottom: 20px; text-align: center; border-radius: 5px; }}
|
| 136 |
+
.page {{ page-break-after: always; margin-bottom: 30px; }}
|
| 137 |
+
img {{ max-width: 100%; display: block; margin: 0 auto; border: 1px solid #ddd; }}
|
| 138 |
+
.page-title {{ text-align: center; margin-top: 10px; font-weight: bold; }}
|
| 139 |
+
.print-button {{ background-color: #3498db; color: white; border: none; padding: 10px 20px;
|
| 140 |
+
border-radius: 4px; cursor: pointer; font-size: 16px; }}
|
| 141 |
+
.print-button:hover {{ background-color: #2980b9; }}
|
| 142 |
+
@media print {{
|
| 143 |
+
.controls {{ display: none; }}
|
| 144 |
+
.page {{ margin-bottom: 0; }}
|
| 145 |
+
body {{ padding: 0; margin: 0; }}
|
| 146 |
+
}}
|
| 147 |
+
</style>
|
| 148 |
+
</head>
|
| 149 |
+
<body>
|
| 150 |
+
<div class="controls">
|
| 151 |
+
<h1>Jewish Passover (Pesach) Coloring Pages</h1>
|
| 152 |
+
<h2>For Ages {age} Years</h2>
|
| 153 |
+
<p>Click the button below to print all coloring pages.</p>
|
| 154 |
+
<button class="print-button" onclick="window.print()">Print All Pages</button>
|
| 155 |
+
</div>
|
| 156 |
+
""")
|
| 157 |
+
|
| 158 |
+
# Add cover page
|
| 159 |
+
f.write(f"""
|
| 160 |
+
<div class="page">
|
| 161 |
+
<h1 style="margin-top: 100px;">Jewish Passover (Pesach)</h1>
|
| 162 |
+
<h1>Coloring Pages</h1>
|
| 163 |
+
<h2>For Ages {age} Years</h2>
|
| 164 |
+
<div style="text-align: center; margin-top: 50px;">
|
| 165 |
+
<p>Created for Jewish children and families</p>
|
| 166 |
+
<p>to celebrate the story of Passover</p>
|
| 167 |
+
</div>
|
| 168 |
+
</div>
|
| 169 |
+
""")
|
| 170 |
|
| 171 |
+
# Add each coloring page
|
| 172 |
+
for filename, desc in actual_files:
|
| 173 |
+
f.write(f"""
|
| 174 |
+
<div class="page">
|
| 175 |
+
<img src="{filename}" alt="{desc}">
|
| 176 |
+
<div class="page-title">{desc}</div>
|
| 177 |
+
</div>
|
| 178 |
+
""")
|
| 179 |
+
|
| 180 |
+
f.write("""
|
| 181 |
+
</body>
|
| 182 |
+
</html>
|
| 183 |
+
""")
|
| 184 |
+
|
| 185 |
+
# Create formatted response
|
| 186 |
+
response = f"## Jewish Passover (Pesach) Coloring Pages for a {age}-year-old:\n\n"
|
| 187 |
+
response += "\n".join([f"- {desc}" for desc in descriptions])
|
| 188 |
+
|
| 189 |
+
# Add information about the printable HTML file
|
| 190 |
+
response += f"\n\n**Coloring pages have been generated!**\n\n"
|
| 191 |
+
response += f"To print the coloring pages, please open this file in your web browser:\n\n"
|
| 192 |
+
response += f"{html_path}\n\n"
|
| 193 |
+
response += f"The individual image files are also available in the 'coloring_images' folder."
|
| 194 |
+
|
| 195 |
+
# Add image paths for the gallery display attempt
|
| 196 |
+
image_paths_str = "||".join(image_paths)
|
| 197 |
+
return f"{response}\n\nIMAGE_PATHS:{image_paths_str}"
|
| 198 |
|
| 199 |
# Custom UI wrapper to handle image display
|
| 200 |
class CustomGradioUI(GradioUI):
|
|
|
|
| 238 |
if "IMAGE_PATHS:" in result:
|
| 239 |
paths_part = result.split("IMAGE_PATHS:")[1]
|
| 240 |
image_paths = paths_part.split("||")
|
| 241 |
+
# Remove the paths marker from the result
|
| 242 |
result = result.split("\n\nIMAGE_PATHS:")[0]
|
| 243 |
|
| 244 |
+
# If no paths found, look in the directory
|
| 245 |
if not image_paths:
|
| 246 |
for file in os.listdir(IMAGES_DIR):
|
| 247 |
if file.endswith('.png') and f"passover_{age}_" in file:
|
| 248 |
image_paths.append(os.path.join(IMAGES_DIR, file))
|
| 249 |
|
| 250 |
+
# Check that paths lead to real files
|
| 251 |
valid_image_paths = [path for path in image_paths if os.path.exists(path)]
|
| 252 |
|
| 253 |
# Return the result and image paths
|