File size: 10,569 Bytes
689eaa0 | 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 | """
Hugging Face API Client for Byte Dream
Use Byte Dream models directly from Hugging Face Hub
"""
import torch
import requests
import base64
from io import BytesIO
from PIL import Image
from typing import Optional, List, Union
import time
class HuggingFaceAPI:
"""
Client for Hugging Face Inference API
Allows using Byte Dream models without downloading them
"""
def __init__(
self,
repo_id: str,
token: Optional[str] = None,
use_gpu: bool = False,
):
"""
Initialize Hugging Face API client
Args:
repo_id: Repository ID (e.g., "username/ByteDream")
token: Hugging Face API token (optional but recommended)
use_gpu: Request GPU inference (if available)
"""
self.repo_id = repo_id
self.token = token
self.use_gpu = use_gpu
# API endpoints
self.inference_api_url = f"https://api-inference.huggingface.co/models/{repo_id}"
self.headers = {}
if token:
self.headers["Authorization"] = f"Bearer {token}"
print(f"✓ Hugging Face API initialized for: {repo_id}")
def query(
self,
prompt: str,
negative_prompt: str = "",
width: int = 512,
height: int = 512,
num_inference_steps: int = 50,
guidance_scale: float = 7.5,
seed: Optional[int] = None,
) -> Image.Image:
"""
Query the model using Inference API
Args:
prompt: Text prompt
negative_prompt: Negative prompt
width: Image width
height: Image height
num_inference_steps: Number of denoising steps
guidance_scale: Guidance scale
seed: Random seed
Returns:
Generated PIL Image
"""
payload = {
"inputs": prompt,
"parameters": {
"negative_prompt": negative_prompt,
"width": width,
"height": height,
"num_inference_steps": num_inference_steps,
"guidance_scale": guidance_scale,
}
}
if seed is not None:
payload["parameters"]["seed"] = seed
# Make request
response = requests.post(
self.inference_api_url,
headers=self.headers,
json=payload,
)
# Handle errors
if response.status_code == 503:
# Model is loading
print("Model is loading on HF servers. Waiting...")
time.sleep(5)
return self.query(prompt, negative_prompt, width, height,
num_inference_steps, guidance_scale, seed)
response.raise_for_status()
# Parse image
image_bytes = response.content
image = Image.open(BytesIO(image_bytes))
return image
def query_batch(
self,
prompts: List[str],
negative_prompt: str = "",
width: int = 512,
height: int = 512,
num_inference_steps: int = 50,
guidance_scale: float = 7.5,
seeds: Optional[List[int]] = None,
) -> List[Image.Image]:
"""
Generate multiple images
Args:
prompts: List of prompts
negative_prompt: Negative prompt
width: Image width
height: Image height
num_inference_steps: Number of steps
guidance_scale: Guidance scale
seeds: List of seeds
Returns:
List of PIL Images
"""
images = []
for i, prompt in enumerate(prompts):
seed = seeds[i] if seeds and i < len(seeds) else None
print(f"Generating image {i+1}/{len(prompts)}...")
image = self.query(
prompt=prompt,
negative_prompt=negative_prompt,
width=width,
height=height,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
seed=seed,
)
images.append(image)
return images
class ByteDreamHFClient:
"""
High-level client for Byte Dream on Hugging Face
Supports both local inference and API usage
"""
def __init__(
self,
repo_id: str,
token: Optional[str] = None,
use_api: bool = False,
device: str = "cpu",
):
"""
Initialize Byte Dream HF client
Args:
repo_id: Repository ID on Hugging Face
token: HF API token
use_api: Use Inference API instead of local inference
device: Device for local inference
"""
self.repo_id = repo_id
self.token = token
self.use_api = use_api
self.device = device
if use_api:
self.api_client = HuggingFaceAPI(repo_id, token)
print("✓ Using Hugging Face Inference API")
else:
# Load model locally
from bytedream.generator import ByteDreamGenerator
self.generator = ByteDreamGenerator(
hf_repo_id=repo_id,
config_path="config.yaml",
device=device,
)
print("✓ Model loaded locally from Hugging Face")
def generate(
self,
prompt: str,
negative_prompt: str = "",
width: int = 512,
height: int = 512,
num_inference_steps: int = 50,
guidance_scale: float = 7.5,
seed: Optional[int] = None,
) -> Image.Image:
"""
Generate image from prompt
Args:
prompt: Text description
negative_prompt: Things to avoid
width: Image width
height: Image height
num_inference_steps: Number of steps
guidance_scale: Guidance scale
seed: Random seed
Returns:
Generated PIL Image
"""
if self.use_api:
return self.api_client.query(
prompt=prompt,
negative_prompt=negative_prompt,
width=width,
height=height,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
seed=seed,
)
else:
return self.generator.generate(
prompt=prompt,
negative_prompt=negative_prompt if negative_prompt else None,
width=width,
height=height,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
seed=seed,
)
def generate_batch(
self,
prompts: List[str],
negative_prompt: str = "",
width: int = 512,
height: int = 512,
num_inference_steps: int = 50,
guidance_scale: float = 7.5,
seeds: Optional[List[int]] = None,
) -> List[Image.Image]:
"""
Generate multiple images
Args:
prompts: List of text descriptions
negative_prompt: Things to avoid
width: Image width
height: Image height
num_inference_steps: Number of steps
guidance_scale: Guidance scale
seeds: List of random seeds
Returns:
List of PIL Images
"""
if self.use_api:
return self.api_client.query_batch(
prompts=prompts,
negative_prompt=negative_prompt,
width=width,
height=height,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
seeds=seeds,
)
else:
return self.generator.generate_batch(
prompts=prompts,
negative_prompt=negative_prompt if negative_prompt else None,
width=width,
height=height,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
seeds=seeds,
)
# Example usage
if __name__ == "__main__":
# Example 1: Use Inference API
print("=" * 60)
print("Example 1: Using Hugging Face Inference API")
print("=" * 60)
# You need a token for private models or higher rate limits
# token = "hf_xxxxxxxxxxxxx"
try:
client = ByteDreamHFClient(
repo_id="Enzo8930302/ByteDream", # Replace with your repo
# token=token, # Optional but recommended
use_api=True, # Set True to use API
)
image = client.generate(
prompt="A beautiful sunset over mountains, digital art",
negative_prompt="ugly, blurry, low quality",
width=512,
height=512,
num_inference_steps=50,
guidance_scale=7.5,
seed=42,
)
image.save("output_api.png")
print("✓ Image saved to output_api.png")
except Exception as e:
print(f"Error: {e}")
print("Make sure the model exists on Hugging Face")
# Example 2: Download and run locally
print("\n" + "=" * 60)
print("Example 2: Download and run locally on CPU")
print("=" * 60)
try:
client_local = ByteDreamHFClient(
repo_id="Enzo8930302/ByteDream",
use_api=False, # Download and run locally
device="cpu",
)
image_local = client_local.generate(
prompt="A futuristic city at night, cyberpunk style",
width=512,
height=512,
num_inference_steps=30,
)
image_local.save("output_local.png")
print("✓ Image saved to output_local.png")
except Exception as e:
print(f"Error: {e}")
|