MaiquelQuerales1977 commited on
Commit
ba18f53
·
verified ·
1 Parent(s): 2c31c11

Upload 17 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ backgrounds/beach.jpg filter=lfs diff=lfs merge=lfs -text
37
+ backgrounds/cozy_home.jpg filter=lfs diff=lfs merge=lfs -text
38
+ backgrounds/garden.jpg filter=lfs diff=lfs merge=lfs -text
39
+ backgrounds/living_room.jpg filter=lfs diff=lfs merge=lfs -text
40
+ backgrounds/park.jpg filter=lfs diff=lfs merge=lfs -text
app.py ADDED
@@ -0,0 +1,533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Shelter Flyer Generator - Main Application
3
+ A Gradio-based web app for animal shelters to generate adoption flyers.
4
+
5
+ Compatible with both local deployment and Hugging Face Spaces.
6
+ """
7
+
8
+ import os
9
+ import sys
10
+ import gradio as gr
11
+ from PIL import Image
12
+ from pathlib import Path
13
+ from datetime import datetime
14
+
15
+ # Load environment variables (for local .env support)
16
+ # Priority: Environment variables > .env file
17
+ try:
18
+ from dotenv import load_dotenv
19
+ load_dotenv() # This loads .env if present, but doesn't override existing env vars
20
+ except ImportError:
21
+ print("[INFO] python-dotenv not installed. Using environment variables only.")
22
+
23
+ # Import core modules
24
+ try:
25
+ from core.background_removal import remove_background
26
+ from core.compositing import composite_animal_on_scene
27
+ from core.bio_generator import generate_bio
28
+ from core.flyer_builder import build_flyer
29
+ print("[OK] All core modules loaded successfully.")
30
+ except ImportError as e:
31
+ print(f"[ERROR] Failed to import core modules: {e}")
32
+ print("Please ensure all core modules are present in the 'core/' directory.")
33
+ sys.exit(1)
34
+
35
+ # ============================================================================
36
+ # ROBUST TOKEN MANAGEMENT
37
+ # ============================================================================
38
+ def check_hf_token():
39
+ """
40
+ Check for HF_TOKEN with proper priority:
41
+ 1. Environment variable (for HF Spaces)
42
+ 2. .env file (for local development)
43
+
44
+ Returns:
45
+ str or None: The token if found, None otherwise
46
+ """
47
+ token = os.getenv("HF_TOKEN")
48
+
49
+ if token and token != "hf_xxxxxxxxxxxxxxxxxxxxx":
50
+ print("✅ Token detected")
51
+ return token
52
+ else:
53
+ print("❌ Token not found")
54
+ print("[WARN] Bio generation will use fallback template mode.")
55
+ print("[INFO] To use AI bio generation, set HF_TOKEN environment variable.")
56
+ print("[INFO] Get your token at: https://huggingface.co/settings/tokens")
57
+ return None
58
+
59
+ # Check token at startup
60
+ HF_TOKEN = check_hf_token()
61
+
62
+ # ============================================================================
63
+ # PATH CONSISTENCY (pathlib for cross-platform compatibility)
64
+ # ============================================================================
65
+ BASE_DIR = Path(__file__).parent.resolve()
66
+ BACKGROUNDS_DIR = BASE_DIR / "backgrounds"
67
+ OUTPUTS_DIR = BASE_DIR / "outputs"
68
+
69
+ # Ensure outputs directory exists
70
+ OUTPUTS_DIR.mkdir(parents=True, exist_ok=True)
71
+
72
+ # Pre-defined personality traits
73
+ PERSONALITY_TRAITS = [
74
+ "Good with kids",
75
+ "Good with other dogs",
76
+ "Good with cats",
77
+ "High energy",
78
+ "Calm / Relaxed",
79
+ "Playful",
80
+ "Loyal",
81
+ "Trained / Knows commands",
82
+ "Loves cuddles",
83
+ "Independent",
84
+ "Gentle",
85
+ "Protective",
86
+ "Loves walks",
87
+ "House-trained",
88
+ "Special needs"
89
+ ]
90
+
91
+ # Available background scenes
92
+ BACKGROUND_SCENES = {
93
+ "Living Room": "living_room.jpg",
94
+ "Cozy Home": "cozy_home.jpg",
95
+ "Garden/Yard": "garden.jpg",
96
+ "Forest Park": "park.jpg",
97
+ "Beach Sunset": "beach.jpg"
98
+ }
99
+
100
+
101
+ # ============================================================================
102
+ # MAIN PIPELINE WITH FILE DOWNLOAD SUPPORT
103
+ # ============================================================================
104
+ def generate_flyer_pipeline(
105
+ animal_photo,
106
+ scene_choice,
107
+ custom_scene,
108
+ animal_name,
109
+ animal_type,
110
+ breed,
111
+ age,
112
+ traits,
113
+ additional_notes,
114
+ shelter_name,
115
+ shelter_contact
116
+ ):
117
+ """
118
+ Main pipeline that orchestrates the flyer generation process.
119
+
120
+ Returns:
121
+ enhanced_photo: PIL.Image - The composited animal on scene
122
+ generated_bio: str - The AI-generated bio
123
+ flyer_file_path: str - Path to downloadable flyer file
124
+ status: str - Status message
125
+ """
126
+
127
+ try:
128
+ # Validate inputs
129
+ if animal_photo is None:
130
+ return None, None, None, "❌ Please upload an animal photo."
131
+
132
+ if not animal_name or not animal_type or not breed or not age:
133
+ return None, None, None, "❌ Please fill in all animal information fields."
134
+
135
+ status_msg = "🚀 Starting flyer generation...\n\n"
136
+
137
+ # Step 1: Select scene
138
+ if custom_scene is not None:
139
+ scene_image = custom_scene
140
+ status_msg += "✅ Using custom background scene\n"
141
+ elif scene_choice and scene_choice in BACKGROUND_SCENES:
142
+ scene_path = BACKGROUNDS_DIR / BACKGROUND_SCENES[scene_choice]
143
+ if not scene_path.exists():
144
+ return None, None, None, f"❌ Background file not found: {scene_path}"
145
+ scene_image = Image.open(scene_path)
146
+ status_msg += f"✅ Using {scene_choice} background\n"
147
+ else:
148
+ return None, None, None, "❌ Please select a background scene or upload a custom one."
149
+
150
+ # Step 2: Remove background from animal photo
151
+ status_msg += "🔄 Removing background from animal photo...\n"
152
+ try:
153
+ animal_cutout = remove_background(animal_photo)
154
+ status_msg += "✅ Background removed successfully\n"
155
+ except Exception as e:
156
+ status_msg += f"❌ Background removal failed: {str(e)}\n"
157
+ return None, None, None, status_msg
158
+
159
+ # Step 3: Composite animal onto scene
160
+ status_msg += "🔄 Compositing animal onto scene...\n"
161
+ try:
162
+ enhanced_photo = composite_animal_on_scene(
163
+ animal_rgba=animal_cutout,
164
+ scene=scene_image,
165
+ position="center",
166
+ scale_factor=0.6
167
+ )
168
+ status_msg += "✅ Enhanced photo created\n"
169
+ except Exception as e:
170
+ status_msg += f"❌ Compositing failed: {str(e)}\n"
171
+ return None, None, None, status_msg
172
+
173
+ # Step 4: Generate bio with AI error handling & fallback
174
+ status_msg += "🔄 Generating bio...\n"
175
+ try:
176
+ bio_text = generate_bio(
177
+ name=animal_name,
178
+ animal_type=animal_type,
179
+ breed=breed,
180
+ age=age,
181
+ traits=traits if traits else [],
182
+ additional_notes=additional_notes
183
+ )
184
+
185
+ # Check if fallback was used
186
+ if "Meet" in bio_text and "looking for a forever home" in bio_text:
187
+ status_msg += "✅ Bio generated (using template fallback)\n"
188
+ else:
189
+ status_msg += "✅ Bio generated with AI\n"
190
+
191
+ except Exception as e:
192
+ status_msg += f"⚠️ Bio generation encountered an issue: {str(e)}\n"
193
+ status_msg += "📝 Using template-based bio as fallback...\n"
194
+
195
+ # Manual fallback if bio_generator fails completely
196
+ bio_text = f"Meet {animal_name}! This {age} {breed} {animal_type.lower()} is looking for a forever home. "
197
+ if traits:
198
+ bio_text += f"{animal_name} is {', '.join(traits[:3]).lower()}. "
199
+ bio_text += f"Come meet {animal_name} at our shelter today!"
200
+ status_msg += "✅ Template bio created\n"
201
+
202
+ # Step 5: Build final flyer
203
+ status_msg += "🔄 Building final flyer...\n"
204
+ try:
205
+ flyer_image = build_flyer(
206
+ photo=enhanced_photo,
207
+ name=animal_name,
208
+ animal_type=animal_type,
209
+ breed=breed,
210
+ age=age,
211
+ bio=bio_text,
212
+ shelter_name=shelter_name if shelter_name else "Your Local Animal Shelter",
213
+ shelter_contact=shelter_contact if shelter_contact else "",
214
+ template="template_1"
215
+ )
216
+ status_msg += "✅ Flyer created successfully\n"
217
+ except Exception as e:
218
+ status_msg += f"❌ Flyer building failed: {str(e)}\n"
219
+ return None, None, None, status_msg
220
+
221
+ # Step 6: Save flyer to file for download
222
+ status_msg += "💾 Saving flyer...\n"
223
+ try:
224
+ # Create unique filename with timestamp
225
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
226
+ safe_name = "".join(c for c in animal_name if c.isalnum() or c in (' ', '-', '_'))
227
+ safe_name = safe_name.replace(' ', '_')
228
+ flyer_filename = f"flyer_{safe_name}_{timestamp}.jpg"
229
+ flyer_path = OUTPUTS_DIR / flyer_filename
230
+
231
+ # Save with high quality
232
+ flyer_image.save(flyer_path, "JPEG", quality=95, optimize=True)
233
+
234
+ status_msg += f"✅ Flyer saved: {flyer_filename}\n"
235
+ status_msg += "\n🎉 Generation complete! You can now download your flyer.\n"
236
+
237
+ # Return the path as a string (Gradio will handle the file download)
238
+ return enhanced_photo, bio_text, str(flyer_path), status_msg
239
+
240
+ except Exception as e:
241
+ status_msg += f"❌ Failed to save flyer: {str(e)}\n"
242
+ return enhanced_photo, bio_text, None, status_msg
243
+
244
+ except Exception as e:
245
+ import traceback
246
+ error_msg = "❌ Unexpected error occurred:\n\n"
247
+ error_msg += f"Error: {str(e)}\n\n"
248
+ error_msg += "Stack trace:\n"
249
+ error_msg += traceback.format_exc()
250
+ return None, None, None, error_msg
251
+
252
+
253
+ def regenerate_bio_only(
254
+ animal_name,
255
+ animal_type,
256
+ breed,
257
+ age,
258
+ traits,
259
+ additional_notes
260
+ ):
261
+ """
262
+ Regenerates just the bio without reprocessing images.
263
+ Includes proper error handling and fallback.
264
+ """
265
+
266
+ try:
267
+ if not animal_name or not animal_type:
268
+ return "❌ Please provide at least name and animal type.", "Error"
269
+
270
+ bio_text = generate_bio(
271
+ name=animal_name,
272
+ animal_type=animal_type,
273
+ breed=breed,
274
+ age=age,
275
+ traits=traits if traits else [],
276
+ additional_notes=additional_notes
277
+ )
278
+
279
+ # Check if AI or fallback was used
280
+ if "Meet" in bio_text and "looking for a forever home" in bio_text:
281
+ status = "✅ Bio regenerated (template mode)"
282
+ else:
283
+ status = "✅ Bio regenerated with AI"
284
+
285
+ return bio_text, status
286
+
287
+ except Exception as e:
288
+ error_msg = f"❌ Error generating bio: {str(e)}\n"
289
+ error_msg += "Using fallback template..."
290
+
291
+ # Fallback bio
292
+ bio_text = f"Meet {animal_name}! This {breed} {animal_type.lower()} is looking for a loving home. "
293
+ if traits:
294
+ bio_text += f"{animal_name} is {', '.join(traits[:2]).lower()}. "
295
+ bio_text += f"Visit our shelter to meet {animal_name}!"
296
+
297
+ return bio_text, "⚠️ Used fallback template (API unavailable)"
298
+
299
+
300
+ # ============================================================================
301
+ # GRADIO 5.0+ COMPATIBLE UI
302
+ # ============================================================================
303
+ with gr.Blocks(
304
+ title="🐾 Shelter Flyer Generator",
305
+ theme=gr.themes.Soft()
306
+ ) as app:
307
+
308
+ gr.Markdown("""
309
+ # 🐾 Shelter Flyer Generator
310
+
311
+ Create beautiful adoption flyers for shelter animals with AI-enhanced photos and compelling bios.
312
+
313
+ **How it works:**
314
+ 1. Upload a photo of the animal
315
+ 2. Choose a background scene
316
+ 3. Fill in the animal's information
317
+ 4. Generate a professional flyer!
318
+ """)
319
+
320
+ with gr.Tabs():
321
+ # ====================================================================
322
+ # TAB 1: Upload & Describe
323
+ # ====================================================================
324
+ with gr.Tab("📸 Upload & Describe"):
325
+ with gr.Row():
326
+ with gr.Column():
327
+ gr.Markdown("### Animal Photo")
328
+ animal_photo = gr.Image(
329
+ type="pil",
330
+ label="Upload Animal Photo",
331
+ height=400
332
+ )
333
+
334
+ gr.Markdown("### Background Scene")
335
+ scene_choice = gr.Radio(
336
+ choices=list(BACKGROUND_SCENES.keys()),
337
+ label="Choose a Background Scene",
338
+ value="Living Room"
339
+ )
340
+
341
+ custom_scene = gr.Image(
342
+ type="pil",
343
+ label="Or Upload Your Own Scene (optional)",
344
+ height=200
345
+ )
346
+
347
+ with gr.Column():
348
+ gr.Markdown("### Animal Information")
349
+ animal_name = gr.Textbox(
350
+ label="Animal Name",
351
+ placeholder="e.g., Bella"
352
+ )
353
+
354
+ animal_type = gr.Radio(
355
+ choices=["Dog", "Cat", "Other"],
356
+ label="Animal Type",
357
+ value="Dog"
358
+ )
359
+
360
+ with gr.Row():
361
+ breed = gr.Textbox(
362
+ label="Breed",
363
+ placeholder="e.g., Golden Retriever"
364
+ )
365
+ age = gr.Textbox(
366
+ label="Age",
367
+ placeholder="e.g., 2 years"
368
+ )
369
+
370
+ gr.Markdown("### Personality Traits")
371
+ traits = gr.CheckboxGroup(
372
+ choices=PERSONALITY_TRAITS,
373
+ label="Select all that apply"
374
+ )
375
+
376
+ additional_notes = gr.Textbox(
377
+ lines=3,
378
+ label="Additional Notes",
379
+ placeholder="Any special information about this animal..."
380
+ )
381
+
382
+ gr.Markdown("### Shelter Information")
383
+ shelter_name = gr.Textbox(
384
+ label="Shelter Name",
385
+ placeholder="e.g., Happy Paws Animal Shelter",
386
+ value="Your Local Animal Shelter"
387
+ )
388
+
389
+ shelter_contact = gr.Textbox(
390
+ label="Contact Info",
391
+ placeholder="e.g., (555) 123-4567 | www.shelter.org"
392
+ )
393
+
394
+ with gr.Row():
395
+ generate_btn = gr.Button(
396
+ "🐾 Generate Flyer",
397
+ variant="primary",
398
+ size="lg"
399
+ )
400
+
401
+ status_output = gr.Textbox(
402
+ label="Status",
403
+ lines=10,
404
+ interactive=False
405
+ )
406
+
407
+ # ====================================================================
408
+ # TAB 2: Preview & Edit
409
+ # ====================================================================
410
+ with gr.Tab("👁️ Preview & Edit"):
411
+ gr.Markdown("### Enhanced Photo")
412
+ enhanced_photo_output = gr.Image(
413
+ label="Enhanced Photo Preview",
414
+ type="pil"
415
+ )
416
+
417
+ gr.Markdown("### Generated Bio")
418
+ with gr.Row():
419
+ bio_output = gr.Textbox(
420
+ lines=8,
421
+ label="Generated Bio (Editable)",
422
+ interactive=True
423
+ )
424
+
425
+ with gr.Row():
426
+ regenerate_bio_btn = gr.Button("🔄 Regenerate Bio")
427
+ bio_status = gr.Textbox(
428
+ label="Bio Status",
429
+ lines=1,
430
+ interactive=False
431
+ )
432
+
433
+ # ====================================================================
434
+ # TAB 3: Download (UPDATED FOR FILE DOWNLOADS)
435
+ # ====================================================================
436
+ with gr.Tab("⬇️ Download"):
437
+ gr.Markdown("""
438
+ ### Download Your Flyer
439
+
440
+ Once your flyer is generated, you can download it here.
441
+ """)
442
+
443
+ # Main flyer download with file output
444
+ download_flyer = gr.File(
445
+ label="📥 Download Final Flyer (JPG)",
446
+ interactive=False
447
+ )
448
+
449
+ gr.Markdown("""
450
+ ---
451
+ **Tip:** The downloaded JPG is high-quality and ready for:
452
+ - Social media posts
453
+ - Email campaigns
454
+ - Printing on flyers
455
+ - Posting on your shelter website
456
+ """)
457
+
458
+ # ========================================================================
459
+ # EVENT HANDLERS
460
+ # ========================================================================
461
+ generate_btn.click(
462
+ fn=generate_flyer_pipeline,
463
+ inputs=[
464
+ animal_photo,
465
+ scene_choice,
466
+ custom_scene,
467
+ animal_name,
468
+ animal_type,
469
+ breed,
470
+ age,
471
+ traits,
472
+ additional_notes,
473
+ shelter_name,
474
+ shelter_contact
475
+ ],
476
+ outputs=[
477
+ enhanced_photo_output,
478
+ bio_output,
479
+ download_flyer, # Now outputs file path for download
480
+ status_output
481
+ ]
482
+ )
483
+
484
+ regenerate_bio_btn.click(
485
+ fn=regenerate_bio_only,
486
+ inputs=[
487
+ animal_name,
488
+ animal_type,
489
+ breed,
490
+ age,
491
+ traits,
492
+ additional_notes
493
+ ],
494
+ outputs=[
495
+ bio_output,
496
+ bio_status
497
+ ]
498
+ )
499
+
500
+ gr.Markdown("""
501
+ ---
502
+ ### About
503
+
504
+ This app uses:
505
+ - **Background Removal**: RMBG-2.0 (Hugging Face)
506
+ - **Bio Generation**: Zephyr-7B (Hugging Face Inference API)
507
+ - **Image Processing**: Pillow
508
+
509
+ Built for animal shelters to create compelling adoption flyers. 🐾
510
+
511
+ **Note:** If HF_TOKEN is not configured, bio generation will use template mode.
512
+ """)
513
+
514
+
515
+ # ============================================================================
516
+ # LAUNCH CONFIGURATION
517
+ # ============================================================================
518
+ if __name__ == "__main__":
519
+ print("\n" + "="*60)
520
+ print("🐾 Shelter Flyer Generator")
521
+ print("="*60)
522
+ print(f"📁 Base directory: {BASE_DIR}")
523
+ print(f"📁 Backgrounds: {BACKGROUNDS_DIR}")
524
+ print(f"📁 Outputs: {OUTPUTS_DIR}")
525
+ print(f"🔑 HF Token: {'✅ Configured' if HF_TOKEN else '❌ Not found (using fallback mode)'}")
526
+ print("="*60 + "\n")
527
+
528
+ # Launch with proper settings for both local and HF Spaces
529
+ app.launch(
530
+ server_name="0.0.0.0", # Allows external access (needed for HF Spaces)
531
+ server_port=7860, # Standard port
532
+ share=False # Set to True for temporary public link
533
+ )
backgrounds/beach.jpg ADDED

Git LFS Details

  • SHA256: 4ce3be431e6c036271d131e12f5a92bf719dfde783c15c5075b6dfbed418652f
  • Pointer size: 131 Bytes
  • Size of remote file: 499 kB
backgrounds/cozy_home.jpg ADDED

Git LFS Details

  • SHA256: 7e53dc613d1316a3dfcbbd2840bfde3eb512e4f28f037280752d9f52ee67d8d4
  • Pointer size: 131 Bytes
  • Size of remote file: 270 kB
backgrounds/garden.jpg ADDED

Git LFS Details

  • SHA256: b9e8e5a7ece056c8615d2ccb1178f15b083fe244cd4ee4eb491c3665ce11c7b5
  • Pointer size: 131 Bytes
  • Size of remote file: 535 kB
backgrounds/living_room.jpg ADDED

Git LFS Details

  • SHA256: 0f169c01a55f4aee197b4ac0a182aa3053cc7c8428b0ac361282088bd1f0ec88
  • Pointer size: 131 Bytes
  • Size of remote file: 252 kB
backgrounds/park.jpg ADDED

Git LFS Details

  • SHA256: 9058112d9900b5e2059d911a2615fc896ac12397841267b842ae412cfffcaf42
  • Pointer size: 131 Bytes
  • Size of remote file: 386 kB
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 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()
274
+
275
+ print(f"\n{'='*60}")
276
+ print("Bio generation test complete!")
277
+
278
+
279
+ if __name__ == "__main__":
280
+ test_bio_generation()
core/compositing.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ gradio>=4.0
2
+ Pillow>=10.0
3
+ transformers>=4.35
4
+ torch>=2.0
5
+ huggingface-hub>=0.20
6
+ python-dotenv>=1.0
7
+ fpdf2>=2.7
8
+ rembg>=2.0
9
+ numpy>=1.24