Spaces:
Running
on
Zero
Running
on
Zero
File size: 29,414 Bytes
da23dfe f3f2fa1 da23dfe f3f2fa1 da23dfe |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 |
"""
Character Sheet Service
=======================
9-stage pipeline for generating 7-view character turnaround sheets.
Layout:
+------------------+------------------+------------------+
| Left Face Profile| Front Face | Right Face Profile| (3:4)
+------------------+------------------+------------------+
| Left Side Body | Front Body | Right Side Body | Back Body | (9:16)
+------------------+------------------+------------------+
"""
import time
import random
import logging
from pathlib import Path
from typing import Optional, Tuple, Dict, Any, Callable, List
from datetime import datetime
from PIL import Image
from .models import (
GenerationRequest,
GenerationResult,
CharacterSheetConfig,
CharacterSheetMetadata
)
from .gemini_client import GeminiClient
from .backend_router import BackendRouter, BackendType
from .utils import ensure_pil_image, save_image, sanitize_filename, preprocess_images_for_backend
logger = logging.getLogger(__name__)
class CharacterSheetService:
"""
Service for generating 7-view character turnaround sheets.
Pipeline (9 stages):
0. Input normalization (face→body or body→face+body)
1. Front face portrait
2. Left face profile (90 degrees)
3. Right face profile (90 degrees)
4. Front full body (from normalized)
5. Back full body
6. Left side full body
7. Right side full body
8. Composite character sheet
"""
def __init__(
self,
api_key: Optional[str] = None,
use_pro_model: bool = False,
config: Optional[CharacterSheetConfig] = None,
backend: Optional[BackendType] = None,
backend_router: Optional[BackendRouter] = None
):
"""
Initialize character sheet service.
Args:
api_key: Gemini API key (for cloud backends)
use_pro_model: Use Gemini Pro model (legacy, use backend param instead)
config: Optional configuration
backend: Specific backend to use
backend_router: Pre-configured backend router
"""
self.config = config or CharacterSheetConfig()
# Determine backend
if backend_router is not None:
self.router = backend_router
self.backend = backend or backend_router.default_backend
else:
# Determine default backend based on params
if backend is not None:
self.backend = backend
elif use_pro_model:
self.backend = BackendType.GEMINI_PRO
else:
self.backend = BackendType.GEMINI_FLASH
self.router = BackendRouter(
gemini_api_key=api_key,
default_backend=self.backend
)
# For backward compatibility
self.use_pro_model = use_pro_model
self.client = self.router.get_client(self.backend)
logger.info(f"CharacterSheetService initialized (backend: {self.backend.value})")
def generate_character_sheet(
self,
initial_image: Optional[Image.Image],
input_type: str = "Face Only",
character_name: str = "Character",
gender_term: str = "character",
costume_description: str = "",
costume_image: Optional[Image.Image] = None,
face_image: Optional[Image.Image] = None,
body_image: Optional[Image.Image] = None,
include_costume_in_faces: bool = True,
progress_callback: Optional[Callable[[int, int, str], None]] = None,
stage_callback: Optional[Callable[[str, Image.Image, Dict[str, Any]], None]] = None,
output_dir: Optional[Path] = None
) -> Tuple[Optional[Image.Image], str, Dict[str, Any]]:
"""
Generate complete 7-view character turnaround sheet.
Args:
initial_image: Starting image (face or body)
input_type: "Face Only", "Full Body", or "Face + Body (Separate)"
character_name: Character name
gender_term: "character", "man", or "woman"
costume_description: Text costume description
costume_image: Optional costume reference
face_image: Face image (for Face + Body mode)
body_image: Body image (for Face + Body mode)
include_costume_in_faces: If True, include costume reference in face views.
Set False for models like FLUX that confuse costume with framing.
progress_callback: Optional callback(stage, total_stages, message)
stage_callback: Optional callback(stage_name, image, stages_dict) called after each
stage completes with the generated image. Enables streaming preview.
output_dir: Optional output directory
Returns:
Tuple of (character_sheet, status_message, metadata)
"""
try:
total_stages = 9
stages = {}
logger.info("=" * 60)
logger.info(f"STARTING CHARACTER SHEET: {character_name}")
logger.info(f"Input type: {input_type}")
logger.info(f"Costume: {costume_description or '(none)'}")
logger.info("=" * 60)
# Build costume instructions - separate for face and body views
# For models like FLUX, costume refs confuse face generation
costume_instruction_body = ""
if costume_description:
costume_instruction_body = f" wearing {costume_description}"
elif costume_image:
costume_instruction_body = " wearing the costume shown in the reference"
# Face views only get costume instruction if flag is set
if include_costume_in_faces:
costume_instruction_face = costume_instruction_body
else:
costume_instruction_face = ""
logger.info("Costume excluded from face views (include_costume_in_faces=False)")
def update_progress(stage: int, message: str):
if progress_callback:
progress_callback(stage, total_stages, message)
logger.info(f"[Stage {stage}/{total_stages}] {message}")
def notify_stage_complete(stage_name: str, image: Image.Image):
"""Notify callback when a stage completes for streaming preview."""
if stage_callback and image is not None:
stage_callback(stage_name, image, stages)
# =================================================================
# Stage 0: Normalize input
# =================================================================
update_progress(0, "Normalizing input images...")
reference_body, reference_face = self._normalize_input(
initial_image=initial_image,
input_type=input_type,
face_image=face_image,
body_image=body_image,
costume_instruction=costume_instruction_body, # Body normalization uses full costume
costume_image=costume_image,
gender_term=gender_term,
stages=stages,
progress_callback=lambda msg: update_progress(0, msg)
)
if reference_body is None or reference_face is None:
return None, "Failed to normalize input images", {}
time.sleep(1)
# =================================================================
# FACE VIEWS (3 portraits)
# =================================================================
# Stage 1: Front face portrait
update_progress(1, "Generating front face portrait...")
if input_type == "Face + Body (Separate)":
prompt = f"Generate a close-up frontal facial portrait showing the {gender_term} from the first image (body/costume reference), extrapolate and extract exact facial details from the second image (face reference). Do NOT transfer clothing or hair style from the second image. The face should fill the entire vertical space, neutral grey background with professional studio lighting."
input_images = [reference_body, reference_face]
else:
prompt = f"Generate a formal portrait view of this {gender_term}{costume_instruction_face} as depicted in the reference images, in front of a neutral grey background with professional studio lighting. The face should fill the entire vertical space. Maintain exact facial features from the reference."
input_images = [reference_face, reference_body]
# Only include costume in face views if flag is set (smarter models)
if costume_image and include_costume_in_faces:
input_images.append(costume_image)
front_face, status = self._generate_stage(
prompt=prompt,
input_images=input_images,
aspect_ratio=self.config.face_aspect_ratio,
temperature=self.config.face_temperature
)
if front_face is None:
return None, f"Stage 1 failed: {status}", {}
stages['front_face'] = front_face
notify_stage_complete('front_face', front_face)
time.sleep(1)
# Stage 2: Left face profile
update_progress(2, "Generating left face profile...")
prompt = f"Create a left side profile view (90 degrees) of this {gender_term}'s face{costume_instruction_face}, showing the left side of the face filling the frame. Professional studio lighting against a neutral grey background. Maintain exact facial features from the reference."
input_images = [front_face, reference_body]
if input_type == "Face + Body (Separate)":
input_images.append(reference_face)
elif costume_image and include_costume_in_faces:
# Only include costume in face views if flag is set (smarter models)
input_images.append(costume_image)
left_face, status = self._generate_stage(
prompt=prompt,
input_images=input_images,
aspect_ratio=self.config.face_aspect_ratio,
temperature=self.config.face_temperature
)
if left_face is None:
return None, f"Stage 2 failed: {status}", {}
stages['left_face'] = left_face
notify_stage_complete('left_face', left_face)
time.sleep(1)
# Stage 3: Right face profile
update_progress(3, "Generating right face profile...")
prompt = f"Create a right side profile view (90 degrees) of this {gender_term}'s face{costume_instruction_face}, showing the right side of the face filling the frame. Professional studio lighting against a neutral grey background. Maintain exact facial features from the reference."
input_images = [front_face, reference_body]
if input_type == "Face + Body (Separate)":
input_images.append(reference_face)
elif costume_image and include_costume_in_faces:
# Only include costume in face views if flag is set (smarter models)
input_images.append(costume_image)
right_face, status = self._generate_stage(
prompt=prompt,
input_images=input_images,
aspect_ratio=self.config.face_aspect_ratio,
temperature=self.config.face_temperature
)
if right_face is None:
return None, f"Stage 3 failed: {status}", {}
stages['right_face'] = right_face
notify_stage_complete('right_face', right_face)
time.sleep(1)
# =================================================================
# BODY VIEWS (4 views)
# =================================================================
# Stage 4: Front body (use normalized reference)
update_progress(4, "Using front body from normalized reference...")
front_body = reference_body
stages['front_body'] = front_body
notify_stage_complete('front_body', front_body)
time.sleep(1)
# Stage 5: Back body
update_progress(5, "Generating back full body...")
prompt = f"Generate a rear view image of this {gender_term}{costume_instruction_body} showing the back in a neutral standing pose against a neutral grey background with professional studio lighting. The full body should fill the vertical space. Maintain consistent appearance from the reference images."
input_images = [reference_body, front_face]
if costume_image:
input_images.append(costume_image)
back_body, status = self._generate_stage(
prompt=prompt,
input_images=input_images,
aspect_ratio=self.config.body_aspect_ratio,
temperature=self.config.body_temperature
)
if back_body is None:
return None, f"Stage 5 failed: {status}", {}
stages['back_body'] = back_body
notify_stage_complete('back_body', back_body)
time.sleep(1)
# Stage 6: Left side body
update_progress(6, "Generating left side full body...")
prompt = f"Generate a left side view body of this {gender_term}{costume_instruction_body} from the left side in front of a neutral grey background. The {gender_term} should be shown from the left side (90 degree angle) in a neutral standing pose. Left side view. Full body fills vertical space. Professional studio lighting."
input_images = [left_face, front_body, reference_body]
left_body, status = self._generate_stage(
prompt=prompt,
input_images=input_images,
aspect_ratio=self.config.body_aspect_ratio,
temperature=self.config.body_temperature
)
if left_body is None:
return None, f"Stage 6 failed: {status}", {}
stages['left_body'] = left_body
notify_stage_complete('left_body', left_body)
time.sleep(1)
# Stage 7: Right side body
update_progress(7, "Generating right side full body...")
prompt = f"Generate a right side view body of this {gender_term}{costume_instruction_body} from the right side in front of a neutral grey background. The {gender_term} should be shown from the right side (90 degree angle) in a neutral standing pose. Right side view. Full body fills vertical space. Professional studio lighting."
input_images = [right_face, front_body, reference_body]
right_body, status = self._generate_stage(
prompt=prompt,
input_images=input_images,
aspect_ratio=self.config.body_aspect_ratio,
temperature=self.config.body_temperature
)
if right_body is None:
return None, f"Stage 7 failed: {status}", {}
stages['right_body'] = right_body
notify_stage_complete('right_body', right_body)
time.sleep(1)
# =================================================================
# Stage 8: Composite character sheet
# =================================================================
update_progress(8, "Compositing character sheet...")
character_sheet = self.composite_character_sheet(
left_face=left_face,
front_face=front_face,
right_face=right_face,
left_body=left_body,
front_body=front_body,
right_body=right_body,
back_body=back_body
)
stages['character_sheet'] = character_sheet
# Build metadata
metadata = CharacterSheetMetadata(
character_name=character_name,
input_type=input_type,
costume_description=costume_description,
backend=self.router.get_active_backend_name(),
stages={
"left_face": {"size": left_face.size},
"front_face": {"size": front_face.size},
"right_face": {"size": right_face.size},
"left_body": {"size": left_body.size},
"front_body": {"size": front_body.size},
"right_body": {"size": right_body.size},
"back_body": {"size": back_body.size},
}
)
success_msg = f"Character sheet generated! 7 views of {character_name}"
# Save to disk if requested
if output_dir:
save_dir = self._save_outputs(
character_name=character_name,
stages=stages,
output_dir=output_dir
)
success_msg += f"\nSaved to: {save_dir}"
update_progress(9, "Complete!")
return character_sheet, success_msg, {"metadata": metadata, "stages": stages}
except Exception as e:
logger.exception(f"Character sheet generation failed: {e}")
return None, f"Error: {str(e)}", {}
def _normalize_input(
self,
initial_image: Optional[Image.Image],
input_type: str,
face_image: Optional[Image.Image],
body_image: Optional[Image.Image],
costume_instruction: str,
costume_image: Optional[Image.Image],
gender_term: str,
stages: dict,
progress_callback: Optional[Callable]
) -> Tuple[Optional[Image.Image], Optional[Image.Image]]:
"""Normalize input images to create reference body and face."""
if input_type == "Face + Body (Separate)":
if face_image is None or body_image is None:
return None, None
if progress_callback:
progress_callback("Normalizing body image...")
prompt = f"Front view full body portrait of this person{costume_instruction}, standing, neutral background"
input_images = [body_image, face_image]
if costume_image:
input_images.append(costume_image)
normalized_body, _ = self._generate_stage(
prompt=prompt,
input_images=input_images,
aspect_ratio=self.config.body_aspect_ratio,
temperature=self.config.normalize_temperature
)
if normalized_body is None:
return None, None
stages['normalized_body'] = normalized_body
return normalized_body, face_image
elif input_type == "Face Only":
if initial_image is None:
return None, None
if progress_callback:
progress_callback("Generating full body from face...")
prompt = f"Create a full body image of the {gender_term}{costume_instruction} standing in a neutral pose in front of a grey background with professional studio lighting. The {gender_term}'s face and features should match the reference image exactly."
input_images = [initial_image]
if costume_image:
input_images.append(costume_image)
full_body, _ = self._generate_stage(
prompt=prompt,
input_images=input_images,
aspect_ratio=self.config.body_aspect_ratio,
temperature=self.config.normalize_temperature
)
if full_body is None:
return None, None
stages['generated_body'] = full_body
return full_body, initial_image
else: # Full Body
if initial_image is None:
return None, None
# Normalize body
if progress_callback:
progress_callback("Normalizing full body...")
prompt = f"Front view full body portrait of this person{costume_instruction}, standing, neutral background"
input_images = [initial_image]
if costume_image:
input_images.append(costume_image)
normalized_body, _ = self._generate_stage(
prompt=prompt,
input_images=input_images,
aspect_ratio=self.config.body_aspect_ratio,
temperature=self.config.normalize_temperature
)
if normalized_body is None:
return None, None
stages['normalized_body'] = normalized_body
time.sleep(1)
# Extract face
if progress_callback:
progress_callback("Generating face closeup...")
prompt = f"Create a frontal closeup portrait of this {gender_term}'s face{costume_instruction}, focusing only on the face and head. Professional studio lighting against a neutral grey background. The face should fill the entire vertical space. Maintain exact facial features from the reference."
input_images = [normalized_body, initial_image]
if costume_image:
input_images.append(costume_image)
face_closeup, _ = self._generate_stage(
prompt=prompt,
input_images=input_images,
aspect_ratio=self.config.face_aspect_ratio,
temperature=self.config.face_temperature
)
if face_closeup is None:
return None, None
stages['extracted_face'] = face_closeup
return normalized_body, face_closeup
def _generate_stage(
self,
prompt: str,
input_images: List[Image.Image],
aspect_ratio: str,
temperature: float,
max_retries: int = 3
) -> Tuple[Optional[Image.Image], str]:
"""Generate single stage with retry logic."""
modified_prompt = prompt
cfg = self.config
# Preprocess images for the current backend
backend_type = self.backend.value if self.backend else "unknown"
processed_images = preprocess_images_for_backend(
input_images, backend_type, aspect_ratio
)
logger.info(f"Preprocessed {len(processed_images)} images for {backend_type}")
for attempt in range(max_retries):
try:
if attempt > 0:
wait_time = cfg.retry_delay
logger.info(f"Retry {attempt + 1}/{max_retries}, waiting {wait_time}s...")
time.sleep(wait_time)
request = GenerationRequest(
prompt=modified_prompt,
input_images=processed_images,
aspect_ratio=aspect_ratio,
temperature=temperature
)
result = self.client.generate(request)
if result.success:
delay = random.uniform(cfg.rate_limit_delay_min, cfg.rate_limit_delay_max)
time.sleep(delay)
return result.image, result.message
# Check for safety block
error_upper = result.message.upper()
if any(kw in error_upper for kw in ['SAFETY', 'BLOCKED', 'PROHIBITED', 'IMAGE_OTHER']):
if 'wearing' not in modified_prompt.lower():
if 'body' in modified_prompt.lower():
modified_prompt = prompt + ", fully clothed in casual wear"
else:
modified_prompt = prompt + ", wearing appropriate clothing"
logger.info("Modified prompt to avoid safety filters")
logger.warning(f"Attempt {attempt + 1} failed: {result.message}")
except Exception as e:
logger.error(f"Attempt {attempt + 1} exception: {e}")
if attempt == max_retries - 1:
return None, str(e)
return None, f"All {max_retries} attempts failed"
def composite_character_sheet(
self,
left_face: Image.Image,
front_face: Image.Image,
right_face: Image.Image,
left_body: Image.Image,
front_body: Image.Image,
right_body: Image.Image,
back_body: Image.Image
) -> Image.Image:
"""
Composite all 7 views into character sheet.
Layout:
+------------------+------------------+------------------+
| Left Face Profile| Front Face | Right Face Profile|
+------------------+------------------+------------------+
| Left Side Body | Front Body | Right Side Body | Back Body |
+------------------+------------------+------------------+
"""
# Normalize all inputs
left_face = ensure_pil_image(left_face, "left_face")
front_face = ensure_pil_image(front_face, "front_face")
right_face = ensure_pil_image(right_face, "right_face")
left_body = ensure_pil_image(left_body, "left_body")
front_body = ensure_pil_image(front_body, "front_body")
right_body = ensure_pil_image(right_body, "right_body")
back_body = ensure_pil_image(back_body, "back_body")
spacing = self.config.spacing
# Calculate dimensions
face_row_width = left_face.width + front_face.width + right_face.width
body_row_width = left_body.width + front_body.width + right_body.width + back_body.width
canvas_width = max(face_row_width, body_row_width)
canvas_height = front_face.height + spacing + front_body.height
# Create canvas
canvas = Image.new('RGB', (canvas_width, canvas_height), color=self.config.background_color)
# Upper row: 3 face portraits
x = 0
canvas.paste(left_face, (x, 0))
x += left_face.width
canvas.paste(front_face, (x, 0))
x += front_face.width
canvas.paste(right_face, (x, 0))
# Lower row: 4 body views
x = 0
y = front_face.height + spacing
canvas.paste(left_body, (x, y))
x += left_body.width
canvas.paste(front_body, (x, y))
x += front_body.width
canvas.paste(right_body, (x, y))
x += right_body.width
canvas.paste(back_body, (x, y))
return canvas
def extract_views_from_sheet(
self,
character_sheet: Image.Image
) -> Dict[str, Image.Image]:
"""
Extract individual views from character sheet.
Returns:
Dictionary with 7 extracted views
"""
sheet_width, sheet_height = character_sheet.size
spacing = self.config.spacing
# Find separator by scanning for dark bar
scan_start = sheet_height // 3
scan_end = (2 * sheet_height) // 3
min_brightness = 255
separator_y = scan_start
for y in range(scan_start, scan_end):
line = character_sheet.crop((0, y, min(200, sheet_width), y + 1))
pixels = list(line.getdata())
avg_brightness = sum(
sum(p[:3]) / 3 if isinstance(p, tuple) else p
for p in pixels
) / len(pixels)
if avg_brightness < min_brightness:
min_brightness = avg_brightness
separator_y = y
face_height = separator_y
body_start_y = separator_y + spacing
body_height = sheet_height - body_start_y
# Calculate widths from aspect ratios
face_width = (face_height * 3) // 4
body_width = (body_height * 9) // 16
# Extract views
views = {
'left_face': character_sheet.crop((0, 0, face_width, face_height)),
'front_face': character_sheet.crop((face_width, 0, 2 * face_width, face_height)),
'right_face': character_sheet.crop((2 * face_width, 0, 3 * face_width, face_height)),
'left_body': character_sheet.crop((0, body_start_y, body_width, body_start_y + body_height)),
'front_body': character_sheet.crop((body_width, body_start_y, 2 * body_width, body_start_y + body_height)),
'right_body': character_sheet.crop((2 * body_width, body_start_y, 3 * body_width, body_start_y + body_height)),
'back_body': character_sheet.crop((3 * body_width, body_start_y, 4 * body_width, body_start_y + body_height)),
}
return views
def _save_outputs(
self,
character_name: str,
stages: dict,
output_dir: Path
) -> Path:
"""Save all outputs to directory."""
output_dir = Path(output_dir)
safe_name = sanitize_filename(character_name)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
char_dir = output_dir / f"{safe_name}_{timestamp}"
char_dir.mkdir(parents=True, exist_ok=True)
for name, image in stages.items():
if isinstance(image, Image.Image):
save_image(image, char_dir, f"{safe_name}_{name}")
logger.info(f"Saved outputs to: {char_dir}")
return char_dir
|