File size: 14,469 Bytes
fcb0cff c0490dd da90319 c0490dd fcb0cff c0490dd baa503f fcb0cff c0490dd fcb0cff c0490dd fcb0cff c0490dd fcb0cff baa503f b1b6827 e5efe2c b1b6827 e5efe2c b1b6827 e5efe2c c0490dd e5efe2c c0490dd fcb0cff c0490dd bfd8827 fcb0cff c0490dd fcb0cff c0490dd bc47113 c0490dd bfd8827 c0490dd fcb0cff c0490dd fcb0cff c0490dd fcb0cff c0490dd fcb0cff c0490dd fcb0cff c0490dd fcb0cff c0490dd bc47113 c0490dd fcb0cff bfd8827 fcb0cff bfd8827 fcb0cff c0490dd |
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 |
# import logging
# import random
# import warnings
# import os
# import gradio as gr
# import numpy as np
# import spaces
# import torch
# from diffusers import FluxControlNetModel
# from diffusers.pipelines import FluxControlNetPipeline
# from gradio_imageslider import ImageSlider
# from PIL import Image
# from huggingface_hub import snapshot_download
# css = """
# #col-container {
# margin: 0 auto;
# max-width: 512px;
# }
# """
# if torch.cuda.is_available():
# power_device = "GPU"
# device = "cuda"
# else:
# power_device = "CPU"
# device = "cpu"
# huggingface_token = os.getenv("HUGGINFACE_TOKEN")
# model_path = snapshot_download(
# repo_id="black-forest-labs/FLUX.1-dev",
# repo_type="model",
# ignore_patterns=["*.md", "*..gitattributes"],
# local_dir="FLUX.1-dev",
# token=huggingface_token, # type a new token-id.
# )
# # Load pipeline
# controlnet = FluxControlNetModel.from_pretrained(
# "jasperai/Flux.1-dev-Controlnet-Upscaler", torch_dtype=torch.bfloat16
# ).to(device)
# pipe = FluxControlNetPipeline.from_pretrained(
# model_path, controlnet=controlnet, torch_dtype=torch.bfloat16
# )
# pipe.to(device)
# MAX_SEED = 1000000
# MAX_PIXEL_BUDGET = 1024 * 1024
# def process_input(input_image, upscale_factor, **kwargs):
# w, h = input_image.size
# w_original, h_original = w, h
# aspect_ratio = w / h
# was_resized = False
# if w * h * upscale_factor**2 > MAX_PIXEL_BUDGET:
# warnings.warn(
# f"Requested output image is too large ({w * upscale_factor}x{h * upscale_factor}). Resizing to ({int(aspect_ratio * MAX_PIXEL_BUDGET ** 0.5 // upscale_factor), int(MAX_PIXEL_BUDGET ** 0.5 // aspect_ratio // upscale_factor)}) pixels."
# )
# gr.Info(
# f"Requested output image is too large ({w * upscale_factor}x{h * upscale_factor}). Resizing input to ({int(aspect_ratio * MAX_PIXEL_BUDGET ** 0.5 // upscale_factor), int(MAX_PIXEL_BUDGET ** 0.5 // aspect_ratio // upscale_factor)}) pixels budget."
# )
# input_image = input_image.resize(
# (
# int(aspect_ratio * MAX_PIXEL_BUDGET**0.5 // upscale_factor),
# int(MAX_PIXEL_BUDGET**0.5 // aspect_ratio // upscale_factor),
# )
# )
# was_resized = True
# # resize to multiple of 8
# w, h = input_image.size
# w = w - w % 8
# h = h - h % 8
# return input_image.resize((w, h)), w_original, h_original, was_resized
# @spaces.GPU#(duration=42)
# def infer(
# seed,
# randomize_seed,
# input_image,
# num_inference_steps,
# upscale_factor,
# controlnet_conditioning_scale,
# progress=gr.Progress(track_tqdm=True),
# ):
# if randomize_seed:
# seed = random.randint(0, MAX_SEED)
# true_input_image = input_image
# input_image, w_original, h_original, was_resized = process_input(
# input_image, upscale_factor
# )
# # rescale with upscale factor
# w, h = input_image.size
# control_image = input_image.resize((w * upscale_factor, h * upscale_factor))
# generator = torch.Generator().manual_seed(seed)
# gr.Info("Upscaling image...")
# image = pipe(
# prompt="",
# control_image=control_image,
# controlnet_conditioning_scale=controlnet_conditioning_scale,
# num_inference_steps=num_inference_steps,
# guidance_scale=3.5,
# height=control_image.size[1],
# width=control_image.size[0],
# generator=generator,
# ).images[0]
# if was_resized:
# gr.Info(
# f"Resizing output image to targeted {w_original * upscale_factor}x{h_original * upscale_factor} size."
# )
# # resize to target desired size
# image = image.resize((w_original * upscale_factor, h_original * upscale_factor))
# image.save("output.jpg")
# # convert to numpy
# return [true_input_image, image, seed]
# with gr.Blocks(css=css) as demo:
# # with gr.Column(elem_id="col-container"):
# gr.Markdown(
# f"""
# # ⚡ Flux.1-dev Upscaler ControlNet ⚡
# This is an interactive demo of [Flux.1-dev Upscaler ControlNet](https://huggingface.co/jasperai/Flux.1-dev-Controlnet-Upscaler) taking as input a low resolution image to generate a high resolution image.
# Currently running on {power_device}.
# *Note*: Even though the model can handle higher resolution images, due to GPU memory constraints, this demo was limited to a generated output not exceeding a pixel budget of 1024x1024. If the requested size exceeds that limit, the input will be first resized keeping the aspect ratio such that the output of the controlNet model does not exceed the allocated pixel budget. The output is then resized to the targeted shape using a simple resizing. This may explain some artifacts for high resolution input. To adress this, run the demo locally or consider implementing a tiling strategy. Happy upscaling! 🚀
# """
# )
# with gr.Row():
# run_button = gr.Button(value="Run")
# with gr.Row():
# with gr.Column(scale=4):
# input_im = gr.Image(label="Input Image", type="pil")
# with gr.Column(scale=1):
# num_inference_steps = gr.Slider(
# label="Number of Inference Steps",
# minimum=8,
# maximum=50,
# step=1,
# value=28,
# )
# upscale_factor = gr.Slider(
# label="Upscale Factor",
# minimum=1,
# maximum=4,
# step=1,
# value=4,
# )
# controlnet_conditioning_scale = gr.Slider(
# label="Controlnet Conditioning Scale",
# minimum=0.1,
# maximum=1.5,
# step=0.1,
# value=0.6,
# )
# seed = gr.Slider(
# label="Seed",
# minimum=0,
# maximum=MAX_SEED,
# step=1,
# value=42,
# )
# randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
# with gr.Row():
# result = ImageSlider(label="Input / Output", type="pil", interactive=True)
# examples = gr.Examples(
# examples=[
# # [42, False, "examples/image_1.jpg", 28, 4, 0.6],
# [42, False, "examples/image_2.jpg", 28, 4, 0.6],
# # [42, False, "examples/image_3.jpg", 28, 4, 0.6],
# [42, False, "examples/image_4.jpg", 28, 4, 0.6],
# # [42, False, "examples/image_5.jpg", 28, 4, 0.6],
# # [42, False, "examples/image_6.jpg", 28, 4, 0.6],
# ],
# inputs=[
# seed,
# randomize_seed,
# input_im,
# num_inference_steps,
# upscale_factor,
# controlnet_conditioning_scale,
# ],
# fn=infer,
# outputs=result,
# cache_examples="lazy",
# )
# # examples = gr.Examples(
# # examples=[
# # #[42, False, "examples/image_1.jpg", 28, 4, 0.6],
# # [42, False, "examples/image_2.jpg", 28, 4, 0.6],
# # #[42, False, "examples/image_3.jpg", 28, 4, 0.6],
# # #[42, False, "examples/image_4.jpg", 28, 4, 0.6],
# # [42, False, "examples/image_5.jpg", 28, 4, 0.6],
# # [42, False, "examples/image_6.jpg", 28, 4, 0.6],
# # [42, False, "examples/image_7.jpg", 28, 4, 0.6],
# # ],
# # inputs=[
# # seed,
# # randomize_seed,
# # input_im,
# # num_inference_steps,
# # upscale_factor,
# # controlnet_conditioning_scale,
# # ],
# # )
# gr.Markdown("**Disclaimer:**")
# gr.Markdown(
# "This demo is only for research purpose. Jasper cannot be held responsible for the generation of NSFW (Not Safe For Work) content through the use of this demo. Users are solely responsible for any content they create, and it is their obligation to ensure that it adheres to appropriate and ethical standards. Jasper provides the tools, but the responsibility for their use lies with the individual user."
# )
# gr.on(
# [run_button.click],
# fn=infer,
# inputs=[
# seed,
# randomize_seed,
# input_im,
# num_inference_steps,
# upscale_factor,
# controlnet_conditioning_scale,
# ],
# outputs=result,
# show_api=False,
# # show_progress="minimal",
# )
# demo.queue().launch(share=False, show_api=False)
import logging
import random
import warnings
import os
import torch
import numpy as np
from diffusers import FluxControlNetModel
from diffusers.pipelines import FluxControlNetPipeline
from PIL import Image
from huggingface_hub import snapshot_download,login
import io
import base64
from flask import Flask, request, jsonify
from concurrent.futures import ThreadPoolExecutor
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
# Add config to store base64 images
app.config['image_outputs'] = {}
# ThreadPoolExecutor for managing image processing threads
executor = ThreadPoolExecutor()
# Determine the device (GPU or CPU)
if torch.cuda.is_available():
device = "cuda"
else:
device = "cpu"
# Load model from Huggingface Hub
huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
if huggingface_token:
login(token=huggingface_token)
else:
print("Hugging Face token not found in environment variables.")
print(huggingface_token)
model_path = snapshot_download(
repo_id="black-forest-labs/FLUX.1-dev",
repo_type="model",
ignore_patterns=["*.md", "*..gitattributes"],
local_dir="FLUX.1-dev",
token=huggingface_token
)
# Load pipeline
controlnet = FluxControlNetModel.from_pretrained(
"jasperai/Flux.1-dev-Controlnet-Upscaler", torch_dtype=torch.bfloat16
).to(device)
pipe = FluxControlNetPipeline.from_pretrained(
model_path, controlnet=controlnet, torch_dtype=torch.bfloat16
)
pipe.to(device)
MAX_SEED = 1000000
MAX_PIXEL_BUDGET = 1024 * 1024
def process_input(input_image, upscale_factor):
w, h = input_image.size
aspect_ratio = w / h
was_resized = False
# Resize if input size exceeds the maximum pixel budget
if w * h * upscale_factor**2 > MAX_PIXEL_BUDGET:
warnings.warn(f"Requested output image is too large. Resizing to fit within pixel budget.")
input_image = input_image.resize(
(
int(aspect_ratio * MAX_PIXEL_BUDGET**0.5 // upscale_factor),
int(MAX_PIXEL_BUDGET**0.5 // aspect_ratio // upscale_factor),
)
)
was_resized = True
# Adjust dimensions to be a multiple of 8
w, h = input_image.size
w = w - w % 8
h = h - h % 8
return input_image.resize((w, h)), was_resized
def run_inference(process_id, input_image, upscale_factor, seed, num_inference_steps, controlnet_conditioning_scale):
input_image, was_resized = process_input(input_image, upscale_factor)
# Rescale image for ControlNet processing
w, h = input_image.size
control_image = input_image.resize((w * upscale_factor, h * upscale_factor))
# Set the random generator for inference
generator = torch.Generator().manual_seed(seed)
# Perform inference using the pipeline
image = pipe(
prompt="",
control_image=control_image,
controlnet_conditioning_scale=controlnet_conditioning_scale,
num_inference_steps=num_inference_steps,
guidance_scale=3.5,
height=control_image.size[1],
width=control_image.size[0],
generator=generator,
).images[0]
# Resize output image back to the original dimensions if needed
if was_resized:
original_size = (input_image.width * upscale_factor, input_image.height * upscale_factor)
image = image.resize(original_size)
# Convert the output image to base64
buffered = io.BytesIO()
image.save(buffered, format="JPEG")
image_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
# Store the result in the shared dictionary
app.config['image_outputs'][process_id] = image_base64
@app.route('/infer', methods=['POST'])
def infer():
data = request.json
seed = data.get("seed", 42)
randomize_seed = data.get("randomize_seed", True)
num_inference_steps = data.get("num_inference_steps", 28)
upscale_factor = data.get("upscale_factor", 4)
controlnet_conditioning_scale = data.get("controlnet_conditioning_scale", 0.6)
# Randomize seed if specified
if randomize_seed:
seed = random.randint(0, MAX_SEED)
# Load and process the input image
input_image_data = base64.b64decode(data['input_image'])
input_image = Image.open(io.BytesIO(input_image_data))
# Create a unique process ID for this request
process_id = str(random.randint(1000, 9999))
# Set the status to 'in_progress'
app.config['image_outputs'][process_id] = None
# Run the inference in a separate thread
executor.submit(run_inference, process_id, input_image, upscale_factor, seed, num_inference_steps, controlnet_conditioning_scale)
# Return the process ID
return jsonify({
"process_id": process_id,
"message": "Processing started"
})
# Modify status endpoint to receive process_id in request body
@app.route('/status', methods=['POST'])
def status():
data = request.json
process_id = data.get('process_id')
# Check if process_id was provided
if not process_id:
return jsonify({
"status": "error",
"message": "Process ID is required"
}), 400
# Check if the process_id exists in the dictionary
if process_id not in app.config['image_outputs']:
return jsonify({
"status": "error",
"message": "Invalid process ID"
}), 404
# Check the status of the image processing
image_base64 = app.config['image_outputs'][process_id]
if image_base64 is None:
return jsonify({
"status": "in_progress"
})
else:
return jsonify({
"status": "completed",
"output_image": image_base64
})
if __name__ == '__main__':
app.run(debug=True)
|