Spaces:
Sleeping
Sleeping
Upload 10 files
Browse files- core/__init__.py +15 -0
- core/__pycache__/__init__.cpython-311.pyc +0 -0
- core/__pycache__/background_removal.cpython-311.pyc +0 -0
- core/__pycache__/bio_generator.cpython-311.pyc +0 -0
- core/__pycache__/compositing.cpython-311.pyc +0 -0
- core/__pycache__/flyer_builder.cpython-311.pyc +0 -0
- core/background_removal.py +232 -0
- core/bio_generator.py +280 -0
- core/compositing.py +293 -0
- core/flyer_builder.py +485 -0
core/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Core modules for Shelter Flyer Generator
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from .background_removal import remove_background
|
| 6 |
+
from .compositing import composite_animal_on_scene
|
| 7 |
+
from .bio_generator import generate_bio
|
| 8 |
+
from .flyer_builder import build_flyer
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
'remove_background',
|
| 12 |
+
'composite_animal_on_scene',
|
| 13 |
+
'generate_bio',
|
| 14 |
+
'build_flyer'
|
| 15 |
+
]
|
core/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (530 Bytes). View file
|
|
|
core/__pycache__/background_removal.cpython-311.pyc
ADDED
|
Binary file (8.76 kB). View file
|
|
|
core/__pycache__/bio_generator.cpython-311.pyc
ADDED
|
Binary file (12 kB). View file
|
|
|
core/__pycache__/compositing.cpython-311.pyc
ADDED
|
Binary file (10.3 kB). View file
|
|
|
core/__pycache__/flyer_builder.cpython-311.pyc
ADDED
|
Binary file (15.9 kB). View file
|
|
|
core/background_removal.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Background Removal Module
|
| 3 |
+
Uses briaai/RMBG-2.0 model from Hugging Face for high-quality background removal.
|
| 4 |
+
Falls back to rembg if the primary model fails.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import numpy as np
|
| 9 |
+
from typing import Optional
|
| 10 |
+
import warnings
|
| 11 |
+
|
| 12 |
+
# Module-level model cache
|
| 13 |
+
_bg_removal_model = None
|
| 14 |
+
_model_type = None
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def remove_background(image: Image.Image) -> Image.Image:
|
| 18 |
+
"""
|
| 19 |
+
Takes an RGB image of an animal, returns an RGBA image
|
| 20 |
+
with the background removed (transparent).
|
| 21 |
+
|
| 22 |
+
Uses: briaai/RMBG-2.0 via transformers pipeline
|
| 23 |
+
Fallback: rembg library (U2-Net based)
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
image: PIL Image in RGB or RGBA format
|
| 27 |
+
|
| 28 |
+
Returns:
|
| 29 |
+
PIL Image in RGBA format with transparent background
|
| 30 |
+
|
| 31 |
+
Raises:
|
| 32 |
+
RuntimeError: If both methods fail
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
# Convert to RGB if needed
|
| 36 |
+
if image.mode == 'RGBA':
|
| 37 |
+
# If already has alpha, just keep RGB channels
|
| 38 |
+
image = image.convert('RGB')
|
| 39 |
+
elif image.mode != 'RGB':
|
| 40 |
+
image = image.convert('RGB')
|
| 41 |
+
|
| 42 |
+
# Try primary method: RMBG-2.0
|
| 43 |
+
try:
|
| 44 |
+
result = _remove_background_rmbg(image)
|
| 45 |
+
if result is not None:
|
| 46 |
+
return result
|
| 47 |
+
except Exception as e:
|
| 48 |
+
print(f"⚠️ RMBG-2.0 failed: {e}")
|
| 49 |
+
print("Falling back to rembg...")
|
| 50 |
+
|
| 51 |
+
# Fallback: rembg
|
| 52 |
+
try:
|
| 53 |
+
result = _remove_background_rembg(image)
|
| 54 |
+
if result is not None:
|
| 55 |
+
return result
|
| 56 |
+
except Exception as e:
|
| 57 |
+
print(f"❌ rembg failed: {e}")
|
| 58 |
+
raise RuntimeError("Both background removal methods failed") from e
|
| 59 |
+
|
| 60 |
+
raise RuntimeError("Background removal returned None")
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _remove_background_rmbg(image: Image.Image) -> Optional[Image.Image]:
|
| 64 |
+
"""
|
| 65 |
+
Remove background using briaai/RMBG-2.0 model.
|
| 66 |
+
|
| 67 |
+
This is a state-of-the-art background removal model from Hugging Face.
|
| 68 |
+
The model is loaded once and cached for subsequent calls.
|
| 69 |
+
"""
|
| 70 |
+
global _bg_removal_model, _model_type
|
| 71 |
+
|
| 72 |
+
# Load model on first call
|
| 73 |
+
if _bg_removal_model is None or _model_type != 'rmbg':
|
| 74 |
+
print("Loading RMBG-2.0 model (first run may take a few minutes)...")
|
| 75 |
+
try:
|
| 76 |
+
from transformers import pipeline
|
| 77 |
+
import torch
|
| 78 |
+
|
| 79 |
+
# Check if CUDA is available
|
| 80 |
+
device = 0 if torch.cuda.is_available() else -1
|
| 81 |
+
device_name = "GPU" if device == 0 else "CPU"
|
| 82 |
+
print(f"Using device: {device_name}")
|
| 83 |
+
|
| 84 |
+
# Load the image segmentation pipeline
|
| 85 |
+
_bg_removal_model = pipeline(
|
| 86 |
+
"image-segmentation",
|
| 87 |
+
model="briaai/RMBG-2.0",
|
| 88 |
+
device=device,
|
| 89 |
+
trust_remote_code=True
|
| 90 |
+
)
|
| 91 |
+
_model_type = 'rmbg'
|
| 92 |
+
print("✅ RMBG-2.0 model loaded successfully.")
|
| 93 |
+
|
| 94 |
+
except Exception as e:
|
| 95 |
+
print(f"Failed to load RMBG-2.0: {e}")
|
| 96 |
+
return None
|
| 97 |
+
|
| 98 |
+
try:
|
| 99 |
+
# Run inference
|
| 100 |
+
# RMBG-2.0 returns a mask that we can use to create transparency
|
| 101 |
+
result = _bg_removal_model(image)
|
| 102 |
+
|
| 103 |
+
# The result is a list of dicts with 'mask' and 'label'
|
| 104 |
+
# We want the mask for the main subject
|
| 105 |
+
if isinstance(result, list) and len(result) > 0:
|
| 106 |
+
mask = result[0]['mask']
|
| 107 |
+
|
| 108 |
+
# Convert mask to numpy array
|
| 109 |
+
mask_array = np.array(mask)
|
| 110 |
+
|
| 111 |
+
# Convert image to numpy array
|
| 112 |
+
image_array = np.array(image)
|
| 113 |
+
|
| 114 |
+
# Create RGBA image
|
| 115 |
+
rgba_image = np.zeros((image_array.shape[0], image_array.shape[1], 4), dtype=np.uint8)
|
| 116 |
+
rgba_image[:, :, :3] = image_array
|
| 117 |
+
rgba_image[:, :, 3] = mask_array
|
| 118 |
+
|
| 119 |
+
# Convert back to PIL
|
| 120 |
+
result_image = Image.fromarray(rgba_image, mode='RGBA')
|
| 121 |
+
|
| 122 |
+
return result_image
|
| 123 |
+
else:
|
| 124 |
+
print("Unexpected result format from RMBG-2.0")
|
| 125 |
+
return None
|
| 126 |
+
|
| 127 |
+
except Exception as e:
|
| 128 |
+
print(f"Error during RMBG-2.0 inference: {e}")
|
| 129 |
+
return None
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _remove_background_rembg(image: Image.Image) -> Optional[Image.Image]:
|
| 133 |
+
"""
|
| 134 |
+
Remove background using rembg library (U2-Net based).
|
| 135 |
+
This is a reliable fallback method.
|
| 136 |
+
"""
|
| 137 |
+
global _bg_removal_model, _model_type
|
| 138 |
+
|
| 139 |
+
# Load rembg on first call
|
| 140 |
+
if _bg_removal_model is None or _model_type != 'rembg':
|
| 141 |
+
print("Loading rembg (U2-Net) model...")
|
| 142 |
+
try:
|
| 143 |
+
from rembg import remove
|
| 144 |
+
_bg_removal_model = remove
|
| 145 |
+
_model_type = 'rembg'
|
| 146 |
+
print("✅ rembg model loaded successfully.")
|
| 147 |
+
except Exception as e:
|
| 148 |
+
print(f"Failed to load rembg: {e}")
|
| 149 |
+
return None
|
| 150 |
+
|
| 151 |
+
try:
|
| 152 |
+
# rembg.remove returns a PIL Image with alpha channel
|
| 153 |
+
result_image = _bg_removal_model(image)
|
| 154 |
+
|
| 155 |
+
# Ensure it's RGBA
|
| 156 |
+
if result_image.mode != 'RGBA':
|
| 157 |
+
result_image = result_image.convert('RGBA')
|
| 158 |
+
|
| 159 |
+
return result_image
|
| 160 |
+
|
| 161 |
+
except Exception as e:
|
| 162 |
+
print(f"Error during rembg inference: {e}")
|
| 163 |
+
return None
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def test_background_removal():
|
| 167 |
+
"""Test function to verify background removal works."""
|
| 168 |
+
import os
|
| 169 |
+
from pathlib import Path
|
| 170 |
+
|
| 171 |
+
# Try to load a test image
|
| 172 |
+
test_images = [
|
| 173 |
+
Path("cat.png"),
|
| 174 |
+
Path("turtle.png"),
|
| 175 |
+
Path("examples/cat.png"),
|
| 176 |
+
Path("examples/turtle.png")
|
| 177 |
+
]
|
| 178 |
+
|
| 179 |
+
test_image_path = None
|
| 180 |
+
for img_path in test_images:
|
| 181 |
+
if img_path.exists():
|
| 182 |
+
test_image_path = img_path
|
| 183 |
+
break
|
| 184 |
+
|
| 185 |
+
if test_image_path is None:
|
| 186 |
+
print("No test images found. Please provide a test image.")
|
| 187 |
+
return False
|
| 188 |
+
|
| 189 |
+
print(f"Testing background removal on: {test_image_path}")
|
| 190 |
+
|
| 191 |
+
try:
|
| 192 |
+
# Load test image
|
| 193 |
+
test_image = Image.open(test_image_path)
|
| 194 |
+
print(f"Loaded image: {test_image.size}, mode: {test_image.mode}")
|
| 195 |
+
|
| 196 |
+
# Remove background
|
| 197 |
+
result = remove_background(test_image)
|
| 198 |
+
print(f"Result: {result.size}, mode: {result.mode}")
|
| 199 |
+
|
| 200 |
+
# Check that result has alpha channel
|
| 201 |
+
if result.mode != 'RGBA':
|
| 202 |
+
print("❌ Result is not RGBA!")
|
| 203 |
+
return False
|
| 204 |
+
|
| 205 |
+
# Check that some pixels are transparent
|
| 206 |
+
alpha_channel = np.array(result)[:, :, 3]
|
| 207 |
+
min_alpha = alpha_channel.min()
|
| 208 |
+
max_alpha = alpha_channel.max()
|
| 209 |
+
|
| 210 |
+
print(f"Alpha channel range: {min_alpha} to {max_alpha}")
|
| 211 |
+
|
| 212 |
+
if min_alpha == 255 and max_alpha == 255:
|
| 213 |
+
print("⚠️ Warning: No transparency detected (all pixels opaque)")
|
| 214 |
+
|
| 215 |
+
# Save result
|
| 216 |
+
output_path = Path("outputs") / f"test_bg_removed_{test_image_path.stem}.png"
|
| 217 |
+
output_path.parent.mkdir(exist_ok=True)
|
| 218 |
+
result.save(output_path)
|
| 219 |
+
print(f"✅ Test passed! Result saved to: {output_path}")
|
| 220 |
+
|
| 221 |
+
return True
|
| 222 |
+
|
| 223 |
+
except Exception as e:
|
| 224 |
+
print(f"❌ Test failed: {e}")
|
| 225 |
+
import traceback
|
| 226 |
+
traceback.print_exc()
|
| 227 |
+
return False
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
if __name__ == "__main__":
|
| 231 |
+
print("Running background removal test...")
|
| 232 |
+
test_background_removal()
|
core/bio_generator.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Bio Generation Module
|
| 3 |
+
Generates adoption bios using Hugging Face Inference API.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
from typing import List
|
| 8 |
+
import time
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def generate_bio(
|
| 12 |
+
name: str,
|
| 13 |
+
animal_type: str,
|
| 14 |
+
breed: str,
|
| 15 |
+
age: str,
|
| 16 |
+
traits: List[str],
|
| 17 |
+
additional_notes: str = ""
|
| 18 |
+
) -> str:
|
| 19 |
+
"""
|
| 20 |
+
Generates a 1–2 paragraph adoption bio using a Hugging Face LLM.
|
| 21 |
+
|
| 22 |
+
Uses: HuggingFaceH4/zephyr-7b-beta via Inference API
|
| 23 |
+
Returns: A warm, engaging adoption bio string.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
name: Animal's name
|
| 27 |
+
animal_type: "Dog", "Cat", or "Other"
|
| 28 |
+
breed: Breed description
|
| 29 |
+
age: Age description
|
| 30 |
+
traits: List of personality traits
|
| 31 |
+
additional_notes: Any additional information
|
| 32 |
+
|
| 33 |
+
Returns:
|
| 34 |
+
Generated bio text (1-2 paragraphs)
|
| 35 |
+
|
| 36 |
+
Raises:
|
| 37 |
+
RuntimeError: If API call fails
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
# Check for HF_TOKEN
|
| 41 |
+
hf_token = os.getenv("HF_TOKEN")
|
| 42 |
+
if not hf_token:
|
| 43 |
+
raise RuntimeError(
|
| 44 |
+
"HF_TOKEN environment variable not set. "
|
| 45 |
+
"Get your token at: https://huggingface.co/settings/tokens"
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
# Build the prompt
|
| 49 |
+
prompt = _build_bio_prompt(name, animal_type, breed, age, traits, additional_notes)
|
| 50 |
+
|
| 51 |
+
# Try Inference API
|
| 52 |
+
try:
|
| 53 |
+
return _generate_via_inference_api(prompt, hf_token)
|
| 54 |
+
except Exception as e:
|
| 55 |
+
print(f"⚠️ Inference API failed: {e}")
|
| 56 |
+
print("Trying fallback method...")
|
| 57 |
+
|
| 58 |
+
# Fallback: Try a different model or use a template
|
| 59 |
+
return _generate_fallback_bio(name, animal_type, breed, age, traits, additional_notes)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _build_bio_prompt(
|
| 63 |
+
name: str,
|
| 64 |
+
animal_type: str,
|
| 65 |
+
breed: str,
|
| 66 |
+
age: str,
|
| 67 |
+
traits: List[str],
|
| 68 |
+
additional_notes: str
|
| 69 |
+
) -> str:
|
| 70 |
+
"""
|
| 71 |
+
Build the prompt for the LLM.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
traits_str = ", ".join(traits) if traits else "friendly"
|
| 75 |
+
|
| 76 |
+
prompt = f"""You are a creative writer for an animal shelter. Write a warm, engaging adoption bio (1-2 paragraphs) for a pet based on the following details. The bio should make potential adopters fall in love with this animal.
|
| 77 |
+
|
| 78 |
+
Name: {name}
|
| 79 |
+
Type: {animal_type}
|
| 80 |
+
Breed: {breed}
|
| 81 |
+
Age: {age}
|
| 82 |
+
Personality traits: {traits_str}
|
| 83 |
+
Additional notes: {additional_notes if additional_notes else "None"}
|
| 84 |
+
|
| 85 |
+
Write the bio in a friendly, heartfelt tone. Start with "Meet {name}!" and end with an encouraging call to action to visit the shelter. Do not use hashtags or emojis. Keep it under 150 words.
|
| 86 |
+
|
| 87 |
+
Bio:"""
|
| 88 |
+
|
| 89 |
+
return prompt
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _generate_via_inference_api(prompt: str, hf_token: str, max_retries: int = 3) -> str:
|
| 93 |
+
"""
|
| 94 |
+
Generate bio using Hugging Face Inference API.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
try:
|
| 98 |
+
from huggingface_hub import InferenceClient
|
| 99 |
+
except ImportError:
|
| 100 |
+
raise RuntimeError(
|
| 101 |
+
"huggingface_hub not installed. "
|
| 102 |
+
"Install it with: pip install huggingface-hub"
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
# Initialize client
|
| 106 |
+
client = InferenceClient(token=hf_token)
|
| 107 |
+
|
| 108 |
+
# Models to try (in order of preference)
|
| 109 |
+
models = [
|
| 110 |
+
"HuggingFaceH4/zephyr-7b-beta",
|
| 111 |
+
"mistralai/Mistral-7B-Instruct-v0.2",
|
| 112 |
+
"meta-llama/Llama-2-7b-chat-hf",
|
| 113 |
+
"google/flan-t5-xl"
|
| 114 |
+
]
|
| 115 |
+
|
| 116 |
+
last_error = None
|
| 117 |
+
|
| 118 |
+
for model_name in models:
|
| 119 |
+
for attempt in range(max_retries):
|
| 120 |
+
try:
|
| 121 |
+
print(f"Attempting {model_name} (attempt {attempt + 1}/{max_retries})...")
|
| 122 |
+
|
| 123 |
+
# Call the API
|
| 124 |
+
response = client.text_generation(
|
| 125 |
+
prompt,
|
| 126 |
+
model=model_name,
|
| 127 |
+
max_new_tokens=250,
|
| 128 |
+
temperature=0.7,
|
| 129 |
+
top_p=0.9,
|
| 130 |
+
repetition_penalty=1.1,
|
| 131 |
+
do_sample=True
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
# Extract the bio text
|
| 135 |
+
bio = _extract_bio_from_response(response)
|
| 136 |
+
|
| 137 |
+
if bio and len(bio) > 20:
|
| 138 |
+
print(f"✅ Bio generated successfully using {model_name}")
|
| 139 |
+
return bio
|
| 140 |
+
else:
|
| 141 |
+
print(f"⚠️ Generated bio too short, retrying...")
|
| 142 |
+
|
| 143 |
+
except Exception as e:
|
| 144 |
+
last_error = e
|
| 145 |
+
print(f"⚠️ Attempt failed: {e}")
|
| 146 |
+
|
| 147 |
+
if attempt < max_retries - 1:
|
| 148 |
+
wait_time = 2 ** attempt # Exponential backoff
|
| 149 |
+
print(f"Waiting {wait_time}s before retry...")
|
| 150 |
+
time.sleep(wait_time)
|
| 151 |
+
|
| 152 |
+
print(f"Model {model_name} failed after {max_retries} attempts, trying next model...")
|
| 153 |
+
|
| 154 |
+
# If all models failed, raise the last error
|
| 155 |
+
raise RuntimeError(f"All models failed. Last error: {last_error}")
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _extract_bio_from_response(response: str) -> str:
|
| 159 |
+
"""
|
| 160 |
+
Extract the bio text from the model response.
|
| 161 |
+
"""
|
| 162 |
+
|
| 163 |
+
# The response might include the prompt + generated text
|
| 164 |
+
# Try to extract just the bio part
|
| 165 |
+
|
| 166 |
+
# Look for "Bio:" and take everything after it
|
| 167 |
+
if "Bio:" in response:
|
| 168 |
+
bio = response.split("Bio:")[-1].strip()
|
| 169 |
+
else:
|
| 170 |
+
bio = response.strip()
|
| 171 |
+
|
| 172 |
+
# Remove any trailing prompt artifacts
|
| 173 |
+
bio = bio.strip()
|
| 174 |
+
|
| 175 |
+
# Remove any "---" or similar separators
|
| 176 |
+
if "---" in bio:
|
| 177 |
+
bio = bio.split("---")[0].strip()
|
| 178 |
+
|
| 179 |
+
return bio
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def _generate_fallback_bio(
|
| 183 |
+
name: str,
|
| 184 |
+
animal_type: str,
|
| 185 |
+
breed: str,
|
| 186 |
+
age: str,
|
| 187 |
+
traits: List[str],
|
| 188 |
+
additional_notes: str
|
| 189 |
+
) -> str:
|
| 190 |
+
"""
|
| 191 |
+
Generate a bio using a template when API is unavailable.
|
| 192 |
+
"""
|
| 193 |
+
|
| 194 |
+
print("⚠️ Using fallback template-based bio generation")
|
| 195 |
+
|
| 196 |
+
# Determine pronouns based on animal type
|
| 197 |
+
pronoun = "they" if animal_type == "Other" else "he/she"
|
| 198 |
+
possessive = "their" if animal_type == "Other" else "his/her"
|
| 199 |
+
|
| 200 |
+
# Build traits description
|
| 201 |
+
if traits:
|
| 202 |
+
if len(traits) == 1:
|
| 203 |
+
traits_desc = traits[0].lower()
|
| 204 |
+
elif len(traits) == 2:
|
| 205 |
+
traits_desc = f"{traits[0].lower()} and {traits[1].lower()}"
|
| 206 |
+
else:
|
| 207 |
+
traits_desc = f"{', '.join(t.lower() for t in traits[:-1])}, and {traits[-1].lower()}"
|
| 208 |
+
else:
|
| 209 |
+
traits_desc = "friendly and loving"
|
| 210 |
+
|
| 211 |
+
# Build the bio
|
| 212 |
+
animal_word = animal_type.lower() if animal_type != "Other" else "animal"
|
| 213 |
+
|
| 214 |
+
intro = f"Meet {name}! This {age} {breed} {animal_word} is looking for a forever home."
|
| 215 |
+
|
| 216 |
+
personality = f"{name} is {traits_desc}."
|
| 217 |
+
|
| 218 |
+
if "good with kids" in [t.lower() for t in traits]:
|
| 219 |
+
personality += f" {name.split()[0]} would be perfect for a family with children."
|
| 220 |
+
elif "calm" in [t.lower() for t in traits] or "relaxed" in [t.lower() for t in traits]:
|
| 221 |
+
personality += f" {name.split()[0]} would thrive in a peaceful, quiet home."
|
| 222 |
+
elif "high energy" in [t.lower() for t in traits] or "playful" in [t.lower() for t in traits]:
|
| 223 |
+
personality += f" {name.split()[0]} would love an active family who enjoys outdoor adventures."
|
| 224 |
+
|
| 225 |
+
if additional_notes:
|
| 226 |
+
personality += f" {additional_notes}"
|
| 227 |
+
|
| 228 |
+
call_to_action = f"Come meet {name} at our shelter today and see if {pronoun}'s the perfect match for your family!"
|
| 229 |
+
|
| 230 |
+
bio = f"{intro} {personality} {call_to_action}"
|
| 231 |
+
|
| 232 |
+
return bio
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def test_bio_generation():
|
| 236 |
+
"""Test function to verify bio generation works."""
|
| 237 |
+
|
| 238 |
+
print("Testing bio generation...")
|
| 239 |
+
|
| 240 |
+
test_cases = [
|
| 241 |
+
{
|
| 242 |
+
"name": "Bella",
|
| 243 |
+
"animal_type": "Dog",
|
| 244 |
+
"breed": "Golden Retriever",
|
| 245 |
+
"age": "2 years",
|
| 246 |
+
"traits": ["Good with kids", "Playful", "Loves cuddles", "House-trained"],
|
| 247 |
+
"additional_notes": "Bella knows basic commands and walks well on a leash."
|
| 248 |
+
},
|
| 249 |
+
{
|
| 250 |
+
"name": "Whiskers",
|
| 251 |
+
"animal_type": "Cat",
|
| 252 |
+
"breed": "Domestic Shorthair",
|
| 253 |
+
"age": "3 years",
|
| 254 |
+
"traits": ["Independent", "Calm / Relaxed", "Good with other cats"],
|
| 255 |
+
"additional_notes": "Whiskers enjoys sunny window spots and gentle petting."
|
| 256 |
+
}
|
| 257 |
+
]
|
| 258 |
+
|
| 259 |
+
for i, test_case in enumerate(test_cases, 1):
|
| 260 |
+
print(f"\n{'='*60}")
|
| 261 |
+
print(f"Test Case {i}: {test_case['name']}")
|
| 262 |
+
print(f"{'='*60}")
|
| 263 |
+
|
| 264 |
+
try:
|
| 265 |
+
bio = generate_bio(**test_case)
|
| 266 |
+
print(f"\nGenerated Bio:")
|
| 267 |
+
print(f"{bio}")
|
| 268 |
+
print(f"\n✅ Test case {i} passed!")
|
| 269 |
+
|
| 270 |
+
except Exception as e:
|
| 271 |
+
print(f"\n❌ Test case {i} failed: {e}")
|
| 272 |
+
import traceback
|
| 273 |
+
traceback.print_exc()
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Image Compositing Module
|
| 3 |
+
Composites the animal cutout onto a background scene with smart scaling and positioning.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from PIL import Image, ImageFilter, ImageEnhance
|
| 7 |
+
import numpy as np
|
| 8 |
+
from typing import Literal, Tuple
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def composite_animal_on_scene(
|
| 12 |
+
animal_rgba: Image.Image,
|
| 13 |
+
scene: Image.Image,
|
| 14 |
+
position: Literal["center", "left", "right"] = "center",
|
| 15 |
+
scale_factor: float = 0.6
|
| 16 |
+
) -> Image.Image:
|
| 17 |
+
"""
|
| 18 |
+
Places the transparent-background animal onto the scene image.
|
| 19 |
+
Returns the final composited RGB image.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
animal_rgba: PIL Image in RGBA format (animal with transparent background)
|
| 23 |
+
scene: PIL Image (background scene)
|
| 24 |
+
position: Where to place the animal ("center", "left", "right")
|
| 25 |
+
scale_factor: Animal size relative to scene height (0.0 to 1.0)
|
| 26 |
+
|
| 27 |
+
Returns:
|
| 28 |
+
PIL Image in RGB format with animal composited on scene
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
# Ensure scene is RGB
|
| 32 |
+
if scene.mode == 'RGBA':
|
| 33 |
+
scene = scene.convert('RGB')
|
| 34 |
+
elif scene.mode != 'RGB':
|
| 35 |
+
scene = scene.convert('RGB')
|
| 36 |
+
|
| 37 |
+
# Ensure animal is RGBA
|
| 38 |
+
if animal_rgba.mode != 'RGBA':
|
| 39 |
+
animal_rgba = animal_rgba.convert('RGBA')
|
| 40 |
+
|
| 41 |
+
# Make a copy of the scene to avoid modifying the original
|
| 42 |
+
composite = scene.copy()
|
| 43 |
+
|
| 44 |
+
# Resize animal to fit the scene
|
| 45 |
+
animal_resized = _resize_animal_to_scene(animal_rgba, scene, scale_factor)
|
| 46 |
+
|
| 47 |
+
# Smooth the edges of the alpha mask
|
| 48 |
+
animal_smooth = _smooth_alpha_edges(animal_resized)
|
| 49 |
+
|
| 50 |
+
# Calculate position
|
| 51 |
+
x_pos, y_pos = _calculate_position(
|
| 52 |
+
animal_size=animal_smooth.size,
|
| 53 |
+
scene_size=composite.size,
|
| 54 |
+
position=position
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
# Composite the animal onto the scene
|
| 58 |
+
# PIL's paste with mask uses the alpha channel for transparency
|
| 59 |
+
composite.paste(animal_smooth, (x_pos, y_pos), animal_smooth)
|
| 60 |
+
|
| 61 |
+
return composite
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _resize_animal_to_scene(
|
| 65 |
+
animal: Image.Image,
|
| 66 |
+
scene: Image.Image,
|
| 67 |
+
scale_factor: float
|
| 68 |
+
) -> Image.Image:
|
| 69 |
+
"""
|
| 70 |
+
Resize animal proportionally to fill scale_factor of scene height.
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
animal: RGBA image of animal
|
| 74 |
+
scene: Background scene image
|
| 75 |
+
scale_factor: Target height as fraction of scene height
|
| 76 |
+
|
| 77 |
+
Returns:
|
| 78 |
+
Resized animal image
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
# Target height is scale_factor * scene height
|
| 82 |
+
target_height = int(scene.size[1] * scale_factor)
|
| 83 |
+
|
| 84 |
+
# Calculate new width maintaining aspect ratio
|
| 85 |
+
aspect_ratio = animal.size[0] / animal.size[1]
|
| 86 |
+
target_width = int(target_height * aspect_ratio)
|
| 87 |
+
|
| 88 |
+
# Ensure animal doesn't exceed scene width
|
| 89 |
+
max_width = int(scene.size[0] * 0.9) # Leave 10% margin
|
| 90 |
+
if target_width > max_width:
|
| 91 |
+
target_width = max_width
|
| 92 |
+
target_height = int(target_width / aspect_ratio)
|
| 93 |
+
|
| 94 |
+
# Resize with high-quality resampling
|
| 95 |
+
animal_resized = animal.resize(
|
| 96 |
+
(target_width, target_height),
|
| 97 |
+
Image.Resampling.LANCZOS
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
return animal_resized
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _smooth_alpha_edges(animal_rgba: Image.Image, blur_radius: int = 2) -> Image.Image:
|
| 104 |
+
"""
|
| 105 |
+
Apply slight Gaussian blur to edges of the alpha mask for smoother blending.
|
| 106 |
+
|
| 107 |
+
Args:
|
| 108 |
+
animal_rgba: RGBA image
|
| 109 |
+
blur_radius: Radius of Gaussian blur (pixels)
|
| 110 |
+
|
| 111 |
+
Returns:
|
| 112 |
+
RGBA image with smoothed alpha channel
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
# Split into RGB and alpha
|
| 116 |
+
rgb = animal_rgba.convert('RGB')
|
| 117 |
+
alpha = animal_rgba.split()[3] # Get alpha channel
|
| 118 |
+
|
| 119 |
+
# Apply slight blur to alpha channel
|
| 120 |
+
alpha_blurred = alpha.filter(ImageFilter.GaussianBlur(radius=blur_radius))
|
| 121 |
+
|
| 122 |
+
# Merge back
|
| 123 |
+
result = rgb.copy()
|
| 124 |
+
result.putalpha(alpha_blurred)
|
| 125 |
+
|
| 126 |
+
return result
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _calculate_position(
|
| 130 |
+
animal_size: Tuple[int, int],
|
| 131 |
+
scene_size: Tuple[int, int],
|
| 132 |
+
position: str
|
| 133 |
+
) -> Tuple[int, int]:
|
| 134 |
+
"""
|
| 135 |
+
Calculate x, y position for animal placement.
|
| 136 |
+
|
| 137 |
+
Args:
|
| 138 |
+
animal_size: (width, height) of animal
|
| 139 |
+
scene_size: (width, height) of scene
|
| 140 |
+
position: "center", "left", or "right"
|
| 141 |
+
|
| 142 |
+
Returns:
|
| 143 |
+
(x, y) position for top-left corner of animal
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
animal_width, animal_height = animal_size
|
| 147 |
+
scene_width, scene_height = scene_size
|
| 148 |
+
|
| 149 |
+
# Vertical position: bottom-aligned with slight offset
|
| 150 |
+
# This makes the animal look like it's "standing" on the scene
|
| 151 |
+
y_offset = int(scene_height * 0.15) # 15% from bottom
|
| 152 |
+
y_pos = scene_height - animal_height - y_offset
|
| 153 |
+
|
| 154 |
+
# Ensure animal doesn't go above the scene
|
| 155 |
+
y_pos = max(y_pos, 0)
|
| 156 |
+
|
| 157 |
+
# Horizontal position
|
| 158 |
+
if position == "center":
|
| 159 |
+
x_pos = (scene_width - animal_width) // 2
|
| 160 |
+
elif position == "left":
|
| 161 |
+
x_offset = int(scene_width * 0.1) # 10% from left
|
| 162 |
+
x_pos = x_offset
|
| 163 |
+
elif position == "right":
|
| 164 |
+
x_offset = int(scene_width * 0.1) # 10% from right
|
| 165 |
+
x_pos = scene_width - animal_width - x_offset
|
| 166 |
+
else:
|
| 167 |
+
# Default to center
|
| 168 |
+
x_pos = (scene_width - animal_width) // 2
|
| 169 |
+
|
| 170 |
+
# Ensure animal stays within scene bounds
|
| 171 |
+
x_pos = max(0, min(x_pos, scene_width - animal_width))
|
| 172 |
+
|
| 173 |
+
return x_pos, y_pos
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def auto_adjust_brightness(
|
| 177 |
+
animal_rgba: Image.Image,
|
| 178 |
+
scene: Image.Image,
|
| 179 |
+
strength: float = 0.5
|
| 180 |
+
) -> Image.Image:
|
| 181 |
+
"""
|
| 182 |
+
Optional: Adjust animal brightness to match scene lighting.
|
| 183 |
+
|
| 184 |
+
Args:
|
| 185 |
+
animal_rgba: RGBA image of animal
|
| 186 |
+
scene: Background scene image
|
| 187 |
+
strength: How much to adjust (0.0 = no adjustment, 1.0 = full adjustment)
|
| 188 |
+
|
| 189 |
+
Returns:
|
| 190 |
+
RGBA image with adjusted brightness
|
| 191 |
+
"""
|
| 192 |
+
|
| 193 |
+
# Calculate average brightness of scene
|
| 194 |
+
scene_gray = scene.convert('L')
|
| 195 |
+
scene_array = np.array(scene_gray)
|
| 196 |
+
scene_brightness = scene_array.mean() / 255.0
|
| 197 |
+
|
| 198 |
+
# Calculate average brightness of animal (excluding transparent pixels)
|
| 199 |
+
animal_array = np.array(animal_rgba)
|
| 200 |
+
rgb = animal_array[:, :, :3]
|
| 201 |
+
alpha = animal_array[:, :, 3]
|
| 202 |
+
|
| 203 |
+
# Only consider non-transparent pixels
|
| 204 |
+
mask = alpha > 0
|
| 205 |
+
if mask.sum() == 0:
|
| 206 |
+
return animal_rgba # No visible pixels
|
| 207 |
+
|
| 208 |
+
animal_brightness = rgb[mask].mean() / 255.0
|
| 209 |
+
|
| 210 |
+
# Calculate brightness adjustment factor
|
| 211 |
+
brightness_diff = scene_brightness - animal_brightness
|
| 212 |
+
adjustment = 1.0 + (brightness_diff * strength)
|
| 213 |
+
adjustment = max(0.5, min(adjustment, 1.5)) # Clamp to reasonable range
|
| 214 |
+
|
| 215 |
+
# Apply brightness adjustment
|
| 216 |
+
rgb_image = animal_rgba.convert('RGB')
|
| 217 |
+
enhancer = ImageEnhance.Brightness(rgb_image)
|
| 218 |
+
adjusted_rgb = enhancer.enhance(adjustment)
|
| 219 |
+
|
| 220 |
+
# Merge back with alpha
|
| 221 |
+
result = adjusted_rgb.copy()
|
| 222 |
+
result.putalpha(animal_rgba.split()[3])
|
| 223 |
+
|
| 224 |
+
return result
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def test_compositing():
|
| 228 |
+
"""Test function to verify compositing works."""
|
| 229 |
+
from pathlib import Path
|
| 230 |
+
import sys
|
| 231 |
+
|
| 232 |
+
# Try to import background removal to get a cutout
|
| 233 |
+
try:
|
| 234 |
+
from .background_removal import remove_background
|
| 235 |
+
except ImportError:
|
| 236 |
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 237 |
+
from core.background_removal import remove_background
|
| 238 |
+
|
| 239 |
+
# Find test images
|
| 240 |
+
test_animal = None
|
| 241 |
+
for path in [Path("cat.png"), Path("examples/cat.png")]:
|
| 242 |
+
if path.exists():
|
| 243 |
+
test_animal = path
|
| 244 |
+
break
|
| 245 |
+
|
| 246 |
+
test_scene = None
|
| 247 |
+
for path in [Path("backgrounds/living_room.jpg"), Path("backgrounds/park.jpg")]:
|
| 248 |
+
if path.exists():
|
| 249 |
+
test_scene = path
|
| 250 |
+
break
|
| 251 |
+
|
| 252 |
+
if test_animal is None or test_scene is None:
|
| 253 |
+
print("❌ Test images not found")
|
| 254 |
+
return False
|
| 255 |
+
|
| 256 |
+
print(f"Testing compositing with animal: {test_animal}, scene: {test_scene}")
|
| 257 |
+
|
| 258 |
+
try:
|
| 259 |
+
# Load images
|
| 260 |
+
animal_img = Image.open(test_animal)
|
| 261 |
+
scene_img = Image.open(test_scene)
|
| 262 |
+
|
| 263 |
+
# Remove background
|
| 264 |
+
print("Removing background...")
|
| 265 |
+
animal_cutout = remove_background(animal_img)
|
| 266 |
+
|
| 267 |
+
# Composite
|
| 268 |
+
print("Compositing...")
|
| 269 |
+
result = composite_animal_on_scene(
|
| 270 |
+
animal_rgba=animal_cutout,
|
| 271 |
+
scene=scene_img,
|
| 272 |
+
position="center",
|
| 273 |
+
scale_factor=0.6
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
# Save result
|
| 277 |
+
output_path = Path("outputs") / f"test_composite_{test_animal.stem}_on_{test_scene.stem}.jpg"
|
| 278 |
+
output_path.parent.mkdir(exist_ok=True)
|
| 279 |
+
result.save(output_path, quality=95)
|
| 280 |
+
print(f"✅ Test passed! Result saved to: {output_path}")
|
| 281 |
+
|
| 282 |
+
return True
|
| 283 |
+
|
| 284 |
+
except Exception as e:
|
| 285 |
+
print(f"❌ Test failed: {e}")
|
| 286 |
+
import traceback
|
| 287 |
+
traceback.print_exc()
|
| 288 |
+
return False
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
if __name__ == "__main__":
|
| 292 |
+
print("Running compositing test...")
|
| 293 |
+
test_compositing()
|
core/flyer_builder.py
ADDED
|
@@ -0,0 +1,485 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Flyer Builder Module
|
| 3 |
+
Assembles the final adoption flyer with photo, bio, and shelter information.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Optional, Tuple
|
| 9 |
+
import textwrap
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def build_flyer(
|
| 13 |
+
photo: Image.Image,
|
| 14 |
+
name: str,
|
| 15 |
+
animal_type: str,
|
| 16 |
+
breed: str,
|
| 17 |
+
age: str,
|
| 18 |
+
bio: str,
|
| 19 |
+
shelter_name: str = "Your Local Animal Shelter",
|
| 20 |
+
shelter_contact: str = "",
|
| 21 |
+
template: str = "template_1"
|
| 22 |
+
) -> Image.Image:
|
| 23 |
+
"""
|
| 24 |
+
Assembles a print-ready flyer image (PNG).
|
| 25 |
+
Returns a PIL Image of the final flyer.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
photo: Enhanced animal photo (composited on scene)
|
| 29 |
+
name: Animal's name
|
| 30 |
+
animal_type: "Dog", "Cat", or "Other"
|
| 31 |
+
breed: Breed description
|
| 32 |
+
age: Age description
|
| 33 |
+
bio: Generated bio text
|
| 34 |
+
shelter_name: Name of the shelter
|
| 35 |
+
shelter_contact: Contact information
|
| 36 |
+
template: Template style to use
|
| 37 |
+
|
| 38 |
+
Returns:
|
| 39 |
+
PIL Image of the final flyer (1080 x 1920 px, portrait)
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
# Canvas size (portrait, social-media friendly)
|
| 43 |
+
canvas_width = 1080
|
| 44 |
+
canvas_height = 1920
|
| 45 |
+
|
| 46 |
+
# Color scheme (warm, inviting colors)
|
| 47 |
+
colors = {
|
| 48 |
+
'background': (255, 250, 245), # Warm white
|
| 49 |
+
'header_bg': (255, 140, 105), # Coral
|
| 50 |
+
'text_dark': (51, 51, 51), # Dark gray
|
| 51 |
+
'text_light': (255, 255, 255), # White
|
| 52 |
+
'accent': (100, 180, 220), # Soft blue
|
| 53 |
+
'info_bg': (245, 245, 245) # Light gray
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
# Create canvas
|
| 57 |
+
flyer = Image.new('RGB', (canvas_width, canvas_height), colors['background'])
|
| 58 |
+
draw = ImageDraw.Draw(flyer)
|
| 59 |
+
|
| 60 |
+
# Load fonts
|
| 61 |
+
fonts = _load_fonts()
|
| 62 |
+
|
| 63 |
+
# Layout positions
|
| 64 |
+
margin = 40
|
| 65 |
+
current_y = margin
|
| 66 |
+
|
| 67 |
+
# 1. Header: "ADOPT ME!" banner
|
| 68 |
+
current_y = _draw_header(draw, canvas_width, current_y, colors, fonts)
|
| 69 |
+
|
| 70 |
+
# 2. Animal photo (centered, with rounded corners)
|
| 71 |
+
current_y = _draw_photo(flyer, photo, canvas_width, current_y, margin)
|
| 72 |
+
|
| 73 |
+
# 3. Info bar: Name, breed, age, type
|
| 74 |
+
current_y = _draw_info_bar(
|
| 75 |
+
draw, name, breed, age, animal_type,
|
| 76 |
+
canvas_width, current_y, margin, colors, fonts
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
# 4. Bio section
|
| 80 |
+
current_y = _draw_bio(
|
| 81 |
+
draw, bio, canvas_width, current_y, margin, colors, fonts
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
# 5. Footer: Shelter info
|
| 85 |
+
_draw_footer(
|
| 86 |
+
draw, shelter_name, shelter_contact,
|
| 87 |
+
canvas_width, canvas_height, margin, colors, fonts
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
return flyer
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _load_fonts() -> dict:
|
| 94 |
+
"""
|
| 95 |
+
Load fonts with fallback to default if custom fonts not available.
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
fonts = {}
|
| 99 |
+
|
| 100 |
+
# Try to load custom fonts
|
| 101 |
+
font_paths = {
|
| 102 |
+
'bold': [
|
| 103 |
+
Path("templates/fonts/Poppins-Bold.ttf"),
|
| 104 |
+
Path("fonts/Poppins-Bold.ttf"),
|
| 105 |
+
],
|
| 106 |
+
'regular': [
|
| 107 |
+
Path("templates/fonts/Poppins-Regular.ttf"),
|
| 108 |
+
Path("fonts/Poppins-Regular.ttf"),
|
| 109 |
+
]
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
# Try loading custom fonts
|
| 113 |
+
for font_type, paths in font_paths.items():
|
| 114 |
+
loaded = False
|
| 115 |
+
for path in paths:
|
| 116 |
+
if path.exists():
|
| 117 |
+
try:
|
| 118 |
+
fonts[f'{font_type}_large'] = ImageFont.truetype(str(path), 72)
|
| 119 |
+
fonts[f'{font_type}_title'] = ImageFont.truetype(str(path), 48)
|
| 120 |
+
fonts[f'{font_type}_heading'] = ImageFont.truetype(str(path), 36)
|
| 121 |
+
fonts[f'{font_type}_body'] = ImageFont.truetype(str(path), 28)
|
| 122 |
+
fonts[f'{font_type}_small'] = ImageFont.truetype(str(path), 24)
|
| 123 |
+
loaded = True
|
| 124 |
+
break
|
| 125 |
+
except Exception as e:
|
| 126 |
+
print(f"⚠️ Failed to load font {path}: {e}")
|
| 127 |
+
|
| 128 |
+
if not loaded:
|
| 129 |
+
print(f"⚠️ Using default font for {font_type}")
|
| 130 |
+
|
| 131 |
+
# Fallback to default font if needed
|
| 132 |
+
if not fonts:
|
| 133 |
+
try:
|
| 134 |
+
fonts['bold_large'] = ImageFont.truetype("arial.ttf", 72)
|
| 135 |
+
fonts['bold_title'] = ImageFont.truetype("arial.ttf", 48)
|
| 136 |
+
fonts['bold_heading'] = ImageFont.truetype("arial.ttf", 36)
|
| 137 |
+
fonts['regular_body'] = ImageFont.truetype("arial.ttf", 28)
|
| 138 |
+
fonts['regular_small'] = ImageFont.truetype("arial.ttf", 24)
|
| 139 |
+
except:
|
| 140 |
+
# Ultimate fallback
|
| 141 |
+
fonts['bold_large'] = ImageFont.load_default()
|
| 142 |
+
fonts['bold_title'] = ImageFont.load_default()
|
| 143 |
+
fonts['bold_heading'] = ImageFont.load_default()
|
| 144 |
+
fonts['regular_body'] = ImageFont.load_default()
|
| 145 |
+
fonts['regular_small'] = ImageFont.load_default()
|
| 146 |
+
|
| 147 |
+
return fonts
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _draw_header(
|
| 151 |
+
draw: ImageDraw.ImageDraw,
|
| 152 |
+
canvas_width: int,
|
| 153 |
+
y_pos: int,
|
| 154 |
+
colors: dict,
|
| 155 |
+
fonts: dict
|
| 156 |
+
) -> int:
|
| 157 |
+
"""
|
| 158 |
+
Draw the "ADOPT ME!" header banner.
|
| 159 |
+
Returns the new y position.
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
header_height = 150
|
| 163 |
+
|
| 164 |
+
# Draw header background
|
| 165 |
+
draw.rectangle(
|
| 166 |
+
[(0, y_pos), (canvas_width, y_pos + header_height)],
|
| 167 |
+
fill=colors['header_bg']
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
# Draw header text
|
| 171 |
+
header_text = "🐾 ADOPT ME! 🐾"
|
| 172 |
+
font = fonts.get('bold_large', fonts.get('bold_title', ImageFont.load_default()))
|
| 173 |
+
|
| 174 |
+
# Get text bbox for centering
|
| 175 |
+
bbox = draw.textbbox((0, 0), header_text, font=font)
|
| 176 |
+
text_width = bbox[2] - bbox[0]
|
| 177 |
+
text_height = bbox[3] - bbox[1]
|
| 178 |
+
|
| 179 |
+
text_x = (canvas_width - text_width) // 2
|
| 180 |
+
text_y = y_pos + (header_height - text_height) // 2
|
| 181 |
+
|
| 182 |
+
draw.text(
|
| 183 |
+
(text_x, text_y),
|
| 184 |
+
header_text,
|
| 185 |
+
fill=colors['text_light'],
|
| 186 |
+
font=font
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
return y_pos + header_height + 40
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _draw_photo(
|
| 193 |
+
flyer: Image.Image,
|
| 194 |
+
photo: Image.Image,
|
| 195 |
+
canvas_width: int,
|
| 196 |
+
y_pos: int,
|
| 197 |
+
margin: int
|
| 198 |
+
) -> int:
|
| 199 |
+
"""
|
| 200 |
+
Draw the animal photo with rounded corners.
|
| 201 |
+
Returns the new y position.
|
| 202 |
+
"""
|
| 203 |
+
|
| 204 |
+
# Photo dimensions
|
| 205 |
+
photo_width = canvas_width - (2 * margin)
|
| 206 |
+
photo_height = int(photo_width * 0.75) # 4:3 aspect ratio
|
| 207 |
+
|
| 208 |
+
# Resize photo to fit
|
| 209 |
+
photo_resized = photo.copy()
|
| 210 |
+
photo_resized.thumbnail((photo_width, photo_height), Image.Resampling.LANCZOS)
|
| 211 |
+
|
| 212 |
+
# Center the resized photo
|
| 213 |
+
photo_x = margin + (photo_width - photo_resized.width) // 2
|
| 214 |
+
photo_y = y_pos
|
| 215 |
+
|
| 216 |
+
# Create rounded corners mask
|
| 217 |
+
mask = _create_rounded_rectangle_mask(
|
| 218 |
+
photo_resized.size,
|
| 219 |
+
radius=30
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
# Apply mask to photo
|
| 223 |
+
photo_rounded = photo_resized.copy()
|
| 224 |
+
photo_rounded.putalpha(mask)
|
| 225 |
+
|
| 226 |
+
# Paste onto flyer
|
| 227 |
+
flyer.paste(photo_rounded, (photo_x, photo_y), photo_rounded)
|
| 228 |
+
|
| 229 |
+
return photo_y + photo_resized.height + 40
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def _create_rounded_rectangle_mask(size: Tuple[int, int], radius: int) -> Image.Image:
|
| 233 |
+
"""
|
| 234 |
+
Create a mask for rounded corners.
|
| 235 |
+
"""
|
| 236 |
+
|
| 237 |
+
mask = Image.new('L', size, 0)
|
| 238 |
+
draw = ImageDraw.Draw(mask)
|
| 239 |
+
|
| 240 |
+
# Draw rounded rectangle
|
| 241 |
+
draw.rounded_rectangle(
|
| 242 |
+
[(0, 0), size],
|
| 243 |
+
radius=radius,
|
| 244 |
+
fill=255
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
return mask
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def _draw_info_bar(
|
| 251 |
+
draw: ImageDraw.ImageDraw,
|
| 252 |
+
name: str,
|
| 253 |
+
breed: str,
|
| 254 |
+
age: str,
|
| 255 |
+
animal_type: str,
|
| 256 |
+
canvas_width: int,
|
| 257 |
+
y_pos: int,
|
| 258 |
+
margin: int,
|
| 259 |
+
colors: dict,
|
| 260 |
+
fonts: dict
|
| 261 |
+
) -> int:
|
| 262 |
+
"""
|
| 263 |
+
Draw the info bar with name, breed, age, type.
|
| 264 |
+
Returns the new y position.
|
| 265 |
+
"""
|
| 266 |
+
|
| 267 |
+
bar_height = 180
|
| 268 |
+
bar_y = y_pos
|
| 269 |
+
|
| 270 |
+
# Draw background
|
| 271 |
+
draw.rectangle(
|
| 272 |
+
[(margin, bar_y), (canvas_width - margin, bar_y + bar_height)],
|
| 273 |
+
fill=colors['info_bg'],
|
| 274 |
+
outline=colors['accent'],
|
| 275 |
+
width=3
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
# Draw animal name (large, centered at top)
|
| 279 |
+
name_font = fonts.get('bold_title', ImageFont.load_default())
|
| 280 |
+
bbox = draw.textbbox((0, 0), name, font=name_font)
|
| 281 |
+
name_width = bbox[2] - bbox[0]
|
| 282 |
+
name_x = (canvas_width - name_width) // 2
|
| 283 |
+
name_y = bar_y + 20
|
| 284 |
+
|
| 285 |
+
draw.text(
|
| 286 |
+
(name_x, name_y),
|
| 287 |
+
name,
|
| 288 |
+
fill=colors['text_dark'],
|
| 289 |
+
font=name_font
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
# Draw breed, age, type (smaller, below name)
|
| 293 |
+
info_font = fonts.get('regular_body', ImageFont.load_default())
|
| 294 |
+
|
| 295 |
+
info_text = f"{breed} • {age} • {animal_type}"
|
| 296 |
+
bbox = draw.textbbox((0, 0), info_text, font=info_font)
|
| 297 |
+
info_width = bbox[2] - bbox[0]
|
| 298 |
+
info_x = (canvas_width - info_width) // 2
|
| 299 |
+
info_y = name_y + 65
|
| 300 |
+
|
| 301 |
+
draw.text(
|
| 302 |
+
(info_x, info_y),
|
| 303 |
+
info_text,
|
| 304 |
+
fill=colors['text_dark'],
|
| 305 |
+
font=info_font
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
return bar_y + bar_height + 40
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def _draw_bio(
|
| 312 |
+
draw: ImageDraw.ImageDraw,
|
| 313 |
+
bio: str,
|
| 314 |
+
canvas_width: int,
|
| 315 |
+
y_pos: int,
|
| 316 |
+
margin: int,
|
| 317 |
+
colors: dict,
|
| 318 |
+
fonts: dict
|
| 319 |
+
) -> int:
|
| 320 |
+
"""
|
| 321 |
+
Draw the bio text with word wrapping.
|
| 322 |
+
Returns the new y position.
|
| 323 |
+
"""
|
| 324 |
+
|
| 325 |
+
bio_font = fonts.get('regular_body', ImageFont.load_default())
|
| 326 |
+
|
| 327 |
+
# Word wrap the bio
|
| 328 |
+
max_width = canvas_width - (2 * margin) - 40
|
| 329 |
+
|
| 330 |
+
# Estimate characters per line
|
| 331 |
+
# Use a sample to estimate average char width
|
| 332 |
+
sample = "A" * 50
|
| 333 |
+
bbox = draw.textbbox((0, 0), sample, font=bio_font)
|
| 334 |
+
avg_char_width = (bbox[2] - bbox[0]) / 50
|
| 335 |
+
chars_per_line = int(max_width / avg_char_width)
|
| 336 |
+
|
| 337 |
+
wrapped_lines = textwrap.wrap(bio, width=chars_per_line)
|
| 338 |
+
|
| 339 |
+
# Draw each line
|
| 340 |
+
line_spacing = 15
|
| 341 |
+
current_y = y_pos
|
| 342 |
+
|
| 343 |
+
for line in wrapped_lines:
|
| 344 |
+
draw.text(
|
| 345 |
+
(margin + 20, current_y),
|
| 346 |
+
line,
|
| 347 |
+
fill=colors['text_dark'],
|
| 348 |
+
font=bio_font
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
bbox = draw.textbbox((0, 0), line, font=bio_font)
|
| 352 |
+
line_height = bbox[3] - bbox[1]
|
| 353 |
+
current_y += line_height + line_spacing
|
| 354 |
+
|
| 355 |
+
return current_y + 40
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def _draw_footer(
|
| 359 |
+
draw: ImageDraw.ImageDraw,
|
| 360 |
+
shelter_name: str,
|
| 361 |
+
shelter_contact: str,
|
| 362 |
+
canvas_width: int,
|
| 363 |
+
canvas_height: int,
|
| 364 |
+
margin: int,
|
| 365 |
+
colors: dict,
|
| 366 |
+
fonts: dict
|
| 367 |
+
):
|
| 368 |
+
"""
|
| 369 |
+
Draw the footer with shelter information.
|
| 370 |
+
"""
|
| 371 |
+
|
| 372 |
+
footer_height = 150
|
| 373 |
+
footer_y = canvas_height - footer_height
|
| 374 |
+
|
| 375 |
+
# Draw footer background
|
| 376 |
+
draw.rectangle(
|
| 377 |
+
[(0, footer_y), (canvas_width, canvas_height)],
|
| 378 |
+
fill=colors['accent']
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
# Draw shelter name
|
| 382 |
+
name_font = fonts.get('bold_heading', ImageFont.load_default())
|
| 383 |
+
bbox = draw.textbbox((0, 0), shelter_name, font=name_font)
|
| 384 |
+
name_width = bbox[2] - bbox[0]
|
| 385 |
+
name_x = (canvas_width - name_width) // 2
|
| 386 |
+
name_y = footer_y + 30
|
| 387 |
+
|
| 388 |
+
draw.text(
|
| 389 |
+
(name_x, name_y),
|
| 390 |
+
shelter_name,
|
| 391 |
+
fill=colors['text_light'],
|
| 392 |
+
font=name_font
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
# Draw contact info if provided
|
| 396 |
+
if shelter_contact:
|
| 397 |
+
contact_font = fonts.get('regular_small', ImageFont.load_default())
|
| 398 |
+
bbox = draw.textbbox((0, 0), shelter_contact, font=contact_font)
|
| 399 |
+
contact_width = bbox[2] - bbox[0]
|
| 400 |
+
contact_x = (canvas_width - contact_width) // 2
|
| 401 |
+
contact_y = name_y + 55
|
| 402 |
+
|
| 403 |
+
draw.text(
|
| 404 |
+
(contact_x, contact_y),
|
| 405 |
+
shelter_contact,
|
| 406 |
+
fill=colors['text_light'],
|
| 407 |
+
font=contact_font
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def build_flyer_pdf(
|
| 412 |
+
photo: Image.Image,
|
| 413 |
+
name: str,
|
| 414 |
+
animal_type: str,
|
| 415 |
+
breed: str,
|
| 416 |
+
age: str,
|
| 417 |
+
bio: str,
|
| 418 |
+
shelter_name: str = "Your Local Animal Shelter",
|
| 419 |
+
shelter_contact: str = "",
|
| 420 |
+
template: str = "template_1"
|
| 421 |
+
) -> bytes:
|
| 422 |
+
"""
|
| 423 |
+
Same as build_flyer but returns PDF bytes.
|
| 424 |
+
Coming soon - for now returns None.
|
| 425 |
+
"""
|
| 426 |
+
|
| 427 |
+
# TODO: Implement PDF generation using fpdf2
|
| 428 |
+
print("⚠️ PDF generation not yet implemented")
|
| 429 |
+
return None
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def test_flyer_builder():
|
| 433 |
+
"""Test function to verify flyer building works."""
|
| 434 |
+
from pathlib import Path
|
| 435 |
+
|
| 436 |
+
# Try to find a composited image or create a simple test
|
| 437 |
+
test_composite = None
|
| 438 |
+
for path in Path("outputs").glob("test_composite_*.jpg"):
|
| 439 |
+
test_composite = path
|
| 440 |
+
break
|
| 441 |
+
|
| 442 |
+
if test_composite is None:
|
| 443 |
+
print("⚠️ No composite test image found. Creating a simple test...")
|
| 444 |
+
# Create a simple test image
|
| 445 |
+
test_img = Image.new('RGB', (800, 600), (100, 150, 200))
|
| 446 |
+
test_composite = test_img
|
| 447 |
+
else:
|
| 448 |
+
test_composite = Image.open(test_composite)
|
| 449 |
+
|
| 450 |
+
print(f"Testing flyer builder with image: {test_composite}")
|
| 451 |
+
|
| 452 |
+
# Test data
|
| 453 |
+
test_data = {
|
| 454 |
+
"photo": test_composite,
|
| 455 |
+
"name": "Bella",
|
| 456 |
+
"animal_type": "Dog",
|
| 457 |
+
"breed": "Golden Retriever",
|
| 458 |
+
"age": "2 years",
|
| 459 |
+
"bio": "Meet Bella! This sweet golden girl is the perfect family companion. She's great with kids, loves to play fetch, and will greet you every day with a wagging tail. Bella is house-trained and knows basic commands. Come meet Bella at our shelter today and see if she's the perfect match for your family!",
|
| 460 |
+
"shelter_name": "Happy Paws Animal Shelter",
|
| 461 |
+
"shelter_contact": "(555) 123-4567 | www.happypaws.org"
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
try:
|
| 465 |
+
print("Building flyer...")
|
| 466 |
+
flyer = build_flyer(**test_data)
|
| 467 |
+
|
| 468 |
+
# Save result
|
| 469 |
+
output_path = Path("outputs") / "test_flyer.png"
|
| 470 |
+
output_path.parent.mkdir(exist_ok=True)
|
| 471 |
+
flyer.save(output_path, quality=95)
|
| 472 |
+
print(f"✅ Test passed! Flyer saved to: {output_path}")
|
| 473 |
+
|
| 474 |
+
return True
|
| 475 |
+
|
| 476 |
+
except Exception as e:
|
| 477 |
+
print(f"❌ Test failed: {e}")
|
| 478 |
+
import traceback
|
| 479 |
+
traceback.print_exc()
|
| 480 |
+
return False
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
if __name__ == "__main__":
|
| 484 |
+
print("Running flyer builder test...")
|
| 485 |
+
test_flyer_builder()
|