fantaxy commited on
Commit
35d3fcb
·
verified ·
1 Parent(s): 3960c92

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -87
app.py CHANGED
@@ -4,18 +4,13 @@ import warnings
4
  import os
5
  import gradio as gr
6
  import numpy as np
 
7
  import torch
8
  from diffusers import FluxControlNetModel
9
  from diffusers.pipelines import FluxControlNetPipeline
10
  from gradio_imageslider import ImageSlider
11
  from PIL import Image
12
  from huggingface_hub import snapshot_download
13
- import gc
14
-
15
- # Clear memory
16
- gc.collect()
17
- if torch.cuda.is_available():
18
- torch.cuda.empty_cache()
19
 
20
  css = """
21
  #col-container {
@@ -24,68 +19,69 @@ css = """
24
  }
25
  """
26
 
27
- # Device configuration
28
- device = "cuda" if torch.cuda.is_available() else "cpu"
29
- dtype = torch.float32
 
 
 
30
 
31
- huggingface_token = os.getenv("HF_TOKEN")
32
 
33
- # Modified model configuration
34
- model_config = {
35
- "low_cpu_mem_usage": True,
36
- "torch_dtype": dtype,
37
- "use_safetensors": False, # Disabled safetensors
38
- }
39
 
40
  model_path = snapshot_download(
41
- repo_id="black-forest-labs/FLUX.1-dev",
42
- repo_type="model",
43
- ignore_patterns=["*.md", "*..gitattributes", "*.bin"],
44
- local_dir="FLUX.1-dev",
45
- token=huggingface_token,
46
  )
47
 
48
- # Load models with modified configuration
49
- try:
50
- controlnet = FluxControlNetModel.from_pretrained(
51
- "jasperai/Flux.1-dev-Controlnet-Upscaler",
52
- **model_config
53
- )
54
- controlnet.to(device)
55
 
56
- pipe = FluxControlNetPipeline.from_pretrained(
57
- model_path,
58
- controlnet=controlnet,
59
- **model_config
60
- )
61
- pipe.to(device)
 
 
62
 
63
- except Exception as e:
64
- print(f"Error loading models: {str(e)}")
65
- raise
66
 
67
- # Enable optimizations
68
- pipe.enable_attention_slicing(1)
69
- pipe.enable_vae_slicing()
70
 
71
- MAX_SEED = 1000000
72
- MAX_PIXEL_BUDGET = 64 * 64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
- def process_input(input_image, upscale_factor):
75
- input_image = input_image.convert('RGB')
76
-
77
  w, h = input_image.size
78
- max_size = int(np.sqrt(MAX_PIXEL_BUDGET))
79
-
80
- new_w = min(w, max_size)
81
- new_h = min(h, max_size)
82
- input_image = input_image.resize((new_w, new_h), Image.LANCZOS)
83
-
84
- w = new_w - new_w % 8
85
- h = new_h - new_h % 8
86
-
87
- return input_image.resize((w, h)), w, h
88
 
 
 
89
  def infer(
90
  seed,
91
  randomize_seed,
@@ -95,38 +91,42 @@ def infer(
95
  controlnet_conditioning_scale,
96
  progress=gr.Progress(track_tqdm=True),
97
  ):
98
- try:
99
- gc.collect()
100
- if torch.cuda.is_available():
101
- torch.cuda.empty_cache()
102
-
103
- if randomize_seed:
104
- seed = random.randint(0, MAX_SEED)
105
-
106
- input_image, w, h = process_input(input_image, upscale_factor)
107
-
108
- with torch.inference_mode():
109
- generator = torch.Generator(device=device).manual_seed(seed)
110
- image = pipe(
111
- prompt="",
112
- control_image=input_image,
113
- controlnet_conditioning_scale=controlnet_conditioning_scale,
114
- num_inference_steps=num_inference_steps,
115
- guidance_scale=1.5,
116
- height=h,
117
- width=w,
118
- generator=generator,
119
- ).images[0]
120
-
121
- gc.collect()
122
- if torch.cuda.is_available():
123
- torch.cuda.empty_cache()
124
-
125
- return [input_image, image, seed]
126
-
127
- except Exception as e:
128
- gr.Error(f"Error: {str(e)}")
129
- return None
 
 
 
 
130
 
131
  with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", css=css) as demo:
132
  with gr.Row():
 
4
  import os
5
  import gradio as gr
6
  import numpy as np
7
+ import spaces
8
  import torch
9
  from diffusers import FluxControlNetModel
10
  from diffusers.pipelines import FluxControlNetPipeline
11
  from gradio_imageslider import ImageSlider
12
  from PIL import Image
13
  from huggingface_hub import snapshot_download
 
 
 
 
 
 
14
 
15
  css = """
16
  #col-container {
 
19
  }
20
  """
21
 
22
+ if torch.cuda.is_available():
23
+ power_device = "GPU"
24
+ device = "cuda"
25
+ else:
26
+ power_device = "CPU"
27
+ device = "cpu"
28
 
 
29
 
30
+ huggingface_token = os.getenv("HUGGINFACE_TOKEN")
 
 
 
 
 
31
 
32
  model_path = snapshot_download(
33
+ repo_id="black-forest-labs/FLUX.1-dev",
34
+ repo_type="model",
35
+ ignore_patterns=["*.md", "*..gitattributes"],
36
+ local_dir="FLUX.1-dev",
37
+ token=huggingface_token, # type a new token-id.
38
  )
39
 
 
 
 
 
 
 
 
40
 
41
+ # Load pipeline
42
+ controlnet = FluxControlNetModel.from_pretrained(
43
+ "jasperai/Flux.1-dev-Controlnet-Upscaler", torch_dtype=torch.bfloat16
44
+ ).to(device)
45
+ pipe = FluxControlNetPipeline.from_pretrained(
46
+ model_path, controlnet=controlnet, torch_dtype=torch.bfloat16
47
+ )
48
+ pipe.to(device)
49
 
50
+ MAX_SEED = 1000000
51
+ MAX_PIXEL_BUDGET = 1024 * 1024
 
52
 
 
 
 
53
 
54
+ def process_input(input_image, upscale_factor, **kwargs):
55
+ w, h = input_image.size
56
+ w_original, h_original = w, h
57
+ aspect_ratio = w / h
58
+
59
+ was_resized = False
60
+
61
+ if w * h * upscale_factor**2 > MAX_PIXEL_BUDGET:
62
+ warnings.warn(
63
+ 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."
64
+ )
65
+ gr.Info(
66
+ 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."
67
+ )
68
+ input_image = input_image.resize(
69
+ (
70
+ int(aspect_ratio * MAX_PIXEL_BUDGET**0.5 // upscale_factor),
71
+ int(MAX_PIXEL_BUDGET**0.5 // aspect_ratio // upscale_factor),
72
+ )
73
+ )
74
+ was_resized = True
75
 
76
+ # resize to multiple of 8
 
 
77
  w, h = input_image.size
78
+ w = w - w % 8
79
+ h = h - h % 8
80
+
81
+ return input_image.resize((w, h)), w_original, h_original, was_resized
 
 
 
 
 
 
82
 
83
+
84
+ @spaces.GPU#(duration=42)
85
  def infer(
86
  seed,
87
  randomize_seed,
 
91
  controlnet_conditioning_scale,
92
  progress=gr.Progress(track_tqdm=True),
93
  ):
94
+ if randomize_seed:
95
+ seed = random.randint(0, MAX_SEED)
96
+ true_input_image = input_image
97
+ input_image, w_original, h_original, was_resized = process_input(
98
+ input_image, upscale_factor
99
+ )
100
+
101
+ # rescale with upscale factor
102
+ w, h = input_image.size
103
+ control_image = input_image.resize((w * upscale_factor, h * upscale_factor))
104
+
105
+ generator = torch.Generator().manual_seed(seed)
106
+
107
+ gr.Info("Upscaling image...")
108
+ image = pipe(
109
+ prompt="",
110
+ control_image=control_image,
111
+ controlnet_conditioning_scale=controlnet_conditioning_scale,
112
+ num_inference_steps=num_inference_steps,
113
+ guidance_scale=3.5,
114
+ height=control_image.size[1],
115
+ width=control_image.size[0],
116
+ generator=generator,
117
+ ).images[0]
118
+
119
+ if was_resized:
120
+ gr.Info(
121
+ f"Resizing output image to targeted {w_original * upscale_factor}x{h_original * upscale_factor} size."
122
+ )
123
+
124
+ # resize to target desired size
125
+ image = image.resize((w_original * upscale_factor, h_original * upscale_factor))
126
+ image.save("output.jpg")
127
+ # convert to numpy
128
+ return [true_input_image, image, seed]
129
+
130
 
131
  with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", css=css) as demo:
132
  with gr.Row():