File size: 8,220 Bytes
80b58c8 | 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 | """
Byte Dream - Main Application Interface
Simple Python API for image generation
"""
from bytedream.generator import ByteDreamGenerator
from bytedream.utils import (
load_image,
save_image,
resize_image,
create_image_grid,
)
from typing import Optional, List
from PIL import Image
class ByteDreamApp:
"""
High-level application interface for Byte Dream
Simplifies common tasks like image generation and batch processing
"""
def __init__(
self,
model_path: Optional[str] = None,
device: str = "cpu",
verbose: bool = True,
):
"""
Initialize Byte Dream application
Args:
model_path: Path to model weights
device: Device to run on
verbose: Enable verbose output
"""
self.verbose = verbose
if self.verbose:
print("Initializing Byte Dream Application...")
self.generator = ByteDreamGenerator(
model_path=model_path,
config_path="config.yaml",
device=device,
)
if self.verbose:
print("✓ Application ready!")
def generate(
self,
prompt: str,
output_path: str = "output.png",
negative_prompt: Optional[str] = None,
width: int = 512,
height: int = 512,
steps: int = 50,
guidance: float = 7.5,
seed: Optional[int] = None,
save: bool = True,
) -> Image.Image:
"""
Generate image from prompt and optionally save to file
Args:
prompt: Text description
output_path: Where to save the image
negative_prompt: What to avoid
width: Image width
height: Image height
steps: Inference steps
guidance: Guidance scale
seed: Random seed
save: Whether to save to file
Returns:
Generated PIL Image
"""
# Generate image
image = self.generator.generate(
prompt=prompt,
negative_prompt=negative_prompt,
width=width,
height=height,
num_inference_steps=steps,
guidance_scale=guidance,
seed=seed,
)
# Save if requested
if save:
save_image(image, output_path)
if self.verbose:
print(f"✓ Image saved to: {output_path}")
return image
def generate_multiple(
self,
prompts: List[str],
output_dir: str = "./outputs",
negative_prompt: Optional[str] = None,
width: int = 512,
height: int = 512,
steps: int = 50,
guidance: float = 7.5,
seeds: Optional[List[int]] = None,
create_grid: bool = True,
) -> List[Image.Image]:
"""
Generate multiple images from prompts
Args:
prompts: List of prompts
output_dir: Directory to save images
negative_prompt: Negative prompt for all
width: Image width
height: Image height
steps: Inference steps
guidance: Guidance scale
seeds: Seeds for each image
create_grid: Create grid of all images
Returns:
List of generated images
"""
from pathlib import Path
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
images = []
for i, prompt in enumerate(prompts):
print(f"\n{'='*60}")
print(f"Generating image {i+1}/{len(prompts)}")
print(f"{'='*60}")
seed = seeds[i] if seeds else None
image = self.generate(
prompt=prompt,
output_path=str(output_path / f"image_{i+1:03d}.png"),
negative_prompt=negative_prompt,
width=width,
height=height,
steps=steps,
guidance=guidance,
seed=seed,
save=True,
)
images.append(image)
# Create grid
if create_grid and len(images) > 1:
grid = create_image_grid(images)
grid_path = output_path / "grid.png"
grid.save(grid_path)
print(f"\n✓ Grid saved to: {grid_path}")
return images
def img2img(
self,
input_image_path: str,
prompt: str,
output_path: str = "output_img2img.png",
strength: float = 0.75,
negative_prompt: Optional[str] = None,
steps: int = 50,
guidance: float = 7.5,
seed: Optional[int] = None,
) -> Image.Image:
"""
Image-to-image transformation (placeholder for future implementation)
Args:
input_image_path: Input image path
prompt: Transformation prompt
output_path: Output path
strength: How much to transform (0-1)
negative_prompt: Negative prompt
steps: Inference steps
guidance: Guidance scale
seed: Random seed
Returns:
Transformed image
"""
print("⚠ img2img functionality will be available in a future update")
print(" For now, using text-to-image generation only")
# For now, just generate from prompt
return self.generate(
prompt=prompt,
output_path=output_path,
negative_prompt=negative_prompt,
steps=steps,
guidance=guidance,
seed=seed,
)
def info(self):
"""Print model information"""
info = self.generator.get_model_info()
print("\n" + "="*60)
print("Byte Dream Model Information")
print("="*60)
for key, value in info.items():
print(f"{key.replace('_', ' ').title()}: {value}")
print("="*60)
def demo():
"""Run a quick demo"""
print("\n" + "="*60)
print("Byte Dream - Quick Demo")
print("="*60)
app = ByteDreamApp(device="cpu", verbose=True)
# Demo prompts
prompts = [
"A beautiful sunset over mountains, digital art, vibrant colors",
"Cyberpunk city at night with neon lights, futuristic",
"Fantasy landscape with castle and waterfall, epic",
]
print("\nGenerating sample images...")
images = app.generate_multiple(
prompts=prompts,
output_dir="./demo_outputs",
steps=30, # Fewer steps for demo
guidance=7.5,
create_grid=True,
)
print(f"\n✓ Demo complete! Generated {len(images)} images")
print(" Check ./demo_outputs/ for results")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Byte Dream Application")
parser.add_argument("--demo", action="store_true", help="Run demo")
args = parser.parse_args()
if args.demo:
demo()
else:
# Interactive mode
app = ByteDreamApp()
print("\nByte Dream Interactive Mode")
print("Type 'quit' to exit\n")
while True:
prompt = input("Prompt: ").strip()
if prompt.lower() in ['quit', 'exit', 'q']:
break
if not prompt:
continue
try:
image = app.generate(
prompt=prompt,
output_path=f"output_{len(prompt)}.png",
)
print("✓ Image generated!\n")
except Exception as e:
print(f"Error: {e}\n")
|