Spaces:
Running on Zero
Running on Zero
File size: 3,240 Bytes
f0d9a3e | 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 | """Utility functions for the application."""
import logging
import random
from typing import Optional, Dict, Any
from pathlib import Path
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def generate_seed() -> int:
"""Generate a random seed for image generation.
Returns:
int: Random seed value.
"""
return random.randint(0, 2**32 - 1)
def validate_prompt(prompt: str, max_length: int = 500) -> tuple[bool, Optional[str]]:
"""Validate a prompt string.
Args:
prompt: The prompt to validate.
max_length: Maximum allowed length.
Returns:
Tuple of (is_valid, error_message).
"""
if not prompt or not prompt.strip():
return False, "Prompt cannot be empty"
if len(prompt) > max_length:
return False, f"Prompt exceeds maximum length of {max_length} characters"
return True, None
def validate_dimensions(width: int, height: int) -> tuple[bool, Optional[str]]:
"""Validate image dimensions.
Args:
width: Image width.
height: Image height.
Returns:
Tuple of (is_valid, error_message).
"""
min_dim = 256
max_dim = 2048
if width < min_dim or width > max_dim:
return False, f"Width must be between {min_dim} and {max_dim}"
if height < min_dim or height > max_dim:
return False, f"Height must be between {min_dim} and {max_dim}"
# Check if dimensions are multiples of 8 (common requirement)
if width % 8 != 0 or height % 8 != 0:
return False, "Dimensions must be multiples of 8"
return True, None
def validate_params(params: Dict[str, Any]) -> tuple[bool, Optional[str]]:
"""Validate generation parameters.
Args:
params: Dictionary of parameters to validate.
Returns:
Tuple of (is_valid, error_message).
"""
# Validate guidance scale
guidance = params.get("guidance_scale", 7.5)
if not 1.0 <= guidance <= 20.0:
return False, "Guidance scale must be between 1.0 and 20.0"
# Validate steps
steps = params.get("num_inference_steps", 50)
if not 10 <= steps <= 100:
return False, "Number of steps must be between 10 and 100"
# Validate dimensions
width = params.get("width", 1024)
height = params.get("height", 1024)
is_valid, error = validate_dimensions(width, height)
if not is_valid:
return False, error
return True, None
def format_timestamp(timestamp: float) -> str:
"""Format a timestamp to a readable string.
Args:
timestamp: Unix timestamp.
Returns:
Formatted timestamp string.
"""
from datetime import datetime
return datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")
def ensure_directory(path: Path) -> Path:
"""Ensure a directory exists, creating it if necessary.
Args:
path: Path to the directory.
Returns:
Path object of the created/existing directory.
"""
path.mkdir(parents=True, exist_ok=True)
return path
|