patomancodesign commited on
Commit
e7136ef
·
verified ·
1 Parent(s): ab9b588

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -62
app.py CHANGED
@@ -1,49 +1,69 @@
 
 
1
  import gradio as gr
2
  import torch
3
  from transformers import AutoConfig, AutoModelForCausalLM
4
  from janus.models import MultiModalityCausalLM, VLChatProcessor
5
  from janus.utils.io import load_pil_images
6
  from PIL import Image
7
-
8
  import numpy as np
9
  import os
10
  import time
11
  from Upsample import RealESRGAN
12
- import spaces # Import spaces for ZeroGPU compatibility
13
-
14
 
15
- # Load model and processor
16
- model_path = "deepseek-ai/Janus-Pro-7B"
17
- config = AutoConfig.from_pretrained(model_path)
18
- language_config = config.language_config
19
- language_config._attn_implementation = 'eager'
20
- vl_gpt = AutoModelForCausalLM.from_pretrained(model_path,
21
- language_config=language_config,
22
- trust_remote_code=True)
23
- if torch.cuda.is_available():
24
- vl_gpt = vl_gpt.to(torch.bfloat16).cuda()
25
- else:
26
- vl_gpt = vl_gpt.to(torch.float16)
27
 
28
- vl_chat_processor = VLChatProcessor.from_pretrained(model_path)
29
- tokenizer = vl_chat_processor.tokenizer
30
- cuda_device = 'cuda' if torch.cuda.is_available() else 'cpu'
31
-
32
- # SR model
33
- sr_model = RealESRGAN(torch.device('cuda' if torch.cuda.is_available() else 'cpu'), scale=2)
34
- sr_model.load_weights(f'weights/RealESRGAN_x2.pth', download=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
  @torch.inference_mode()
37
- @spaces.GPU(duration=120)
38
- # Multimodal Understanding function
39
  def multimodal_understanding(image, question, seed, top_p, temperature, progress=gr.Progress(track_tqdm=True)):
 
 
 
40
  # Clear CUDA cache before generating
41
  torch.cuda.empty_cache()
42
 
43
  # set seed
44
  torch.manual_seed(seed)
45
  np.random.seed(seed)
46
- torch.cuda.manual_seed(seed)
 
47
 
48
  conversation = [
49
  {
@@ -55,10 +75,13 @@ def multimodal_understanding(image, question, seed, top_p, temperature, progress
55
  ]
56
 
57
  pil_images = [Image.fromarray(image)]
 
 
 
 
58
  prepare_inputs = vl_chat_processor(
59
  conversations=conversation, images=pil_images, force_batchify=True
60
- ).to(cuda_device, dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float16)
61
-
62
 
63
  inputs_embeds = vl_gpt.prepare_inputs_embeds(**prepare_inputs)
64
 
@@ -78,7 +101,6 @@ def multimodal_understanding(image, question, seed, top_p, temperature, progress
78
  answer = tokenizer.decode(outputs[0].cpu().tolist(), skip_special_tokens=True)
79
  return answer
80
 
81
-
82
  def generate(input_ids,
83
  width,
84
  height,
@@ -88,16 +110,19 @@ def generate(input_ids,
88
  image_token_num_per_image: int = 576,
89
  patch_size: int = 16,
90
  progress=gr.Progress(track_tqdm=True)):
 
 
 
91
  # Clear CUDA cache before generating
92
  torch.cuda.empty_cache()
93
 
94
- tokens = torch.zeros((parallel_size * 2, len(input_ids)), dtype=torch.int).to(cuda_device)
95
  for i in range(parallel_size * 2):
96
  tokens[i, :] = input_ids
97
  if i % 2 != 0:
98
  tokens[i, 1:-1] = vl_chat_processor.pad_id
99
  inputs_embeds = vl_gpt.language_model.get_input_embeddings()(tokens)
100
- generated_tokens = torch.zeros((parallel_size, image_token_num_per_image), dtype=torch.int).to(cuda_device)
101
 
102
  pkv = None
103
  for i in range(image_token_num_per_image):
@@ -119,8 +144,6 @@ def generate(input_ids,
119
  img_embeds = vl_gpt.prepare_gen_img_embeds(next_token)
120
  inputs_embeds = img_embeds.unsqueeze(dim=1)
121
 
122
-
123
-
124
  patches = vl_gpt.gen_vision_model.decode_code(generated_tokens.to(dtype=torch.int),
125
  shape=[parallel_size, 8, width // patch_size, height // patch_size])
126
 
@@ -135,22 +158,27 @@ def unpack(dec, width, height, parallel_size=5):
135
 
136
  return visual_img
137
 
138
-
139
-
140
  @torch.inference_mode()
141
- @spaces.GPU(duration=120) # Specify a duration to avoid timeout
142
  def generate_image(prompt,
143
  seed=None,
144
  guidance=5,
145
  t2i_temperature=1.0,
146
  progress=gr.Progress(track_tqdm=True)):
 
 
 
 
147
  # Clear CUDA cache and avoid tracking gradients
148
  torch.cuda.empty_cache()
 
149
  # Set the seed for reproducible results
150
  if seed is not None:
151
  torch.manual_seed(seed)
152
- torch.cuda.manual_seed(seed)
 
153
  np.random.seed(seed)
 
154
  width = 384
155
  height = 384
156
  parallel_size = 4
@@ -175,18 +203,17 @@ def generate_image(prompt,
175
  height // 16 * 16,
176
  parallel_size=parallel_size)
177
 
178
- # return [Image.fromarray(images[i]).resize((768, 768), Image.LANCZOS) for i in range(parallel_size)]
179
- stime = time.time()
180
  ret_images = [image_upsample(Image.fromarray(images[i])) for i in range(parallel_size)]
181
- print(f'upsample time: {time.time() - stime}')
182
  return ret_images
183
 
184
-
185
  @spaces.GPU(duration=60)
186
  def image_upsample(img: Image.Image) -> Image.Image:
187
  if img is None:
188
  raise Exception("Image not uploaded")
189
 
 
 
 
190
  width, height = img.size
191
 
192
  if width >= 5000 or height >= 5000:
@@ -195,14 +222,15 @@ def image_upsample(img: Image.Image) -> Image.Image:
195
  global sr_model
196
  result = sr_model.predict(img.convert('RGB'))
197
  return result
198
-
199
 
200
  # Gradio interface
201
  css = '''
202
  .gradio-container {max-width: 960px !important}
203
  '''
 
204
  with gr.Blocks(css=css) as demo:
205
  gr.Markdown("# Janus Pro 7B")
 
206
  with gr.Tab("Multimodal Understanding"):
207
  gr.Markdown(value="## Multimodal Understanding")
208
  image_input = gr.Image()
@@ -213,29 +241,14 @@ with gr.Blocks(css=css) as demo:
213
  understanding_output = gr.Textbox(label="Response")
214
 
215
  with gr.Accordion("Advanced options", open=False):
216
- und_seed_input = gr.Number(label="Seed", precision=0, value=42)
217
- top_p = gr.Slider(minimum=0, maximum=1, value=0.95, step=0.05, label="top_p")
218
- temperature = gr.Slider(minimum=0, maximum=1, value=0.1, step=0.05, label="temperature")
219
-
220
- examples_inpainting = gr.Examples(
221
- label="Multimodal Understanding examples",
222
- examples=[
223
- [
224
- "explain this meme",
225
- "doge.png",
226
- ],
227
- [
228
- "Convert the formula into latex code.",
229
- "equation.png",
230
- ],
231
- ],
232
- inputs=[question_input, image_input],
233
- )
234
 
235
  with gr.Tab("Text-to-Image Generation"):
236
  gr.Markdown(value="## Text-to-Image Generation")
237
 
238
- prompt_input = gr.Textbox(label="Prompt. (Prompt in more detail can help produce better images!")
239
 
240
  generation_button = gr.Button("Generate Images")
241
 
@@ -246,7 +259,7 @@ with gr.Blocks(css=css) as demo:
246
  cfg_weight_input = gr.Slider(minimum=1, maximum=10, value=5, step=0.5, label="CFG Weight")
247
  t2i_temperature = gr.Slider(minimum=0, maximum=1, value=1.0, step=0.05, label="temperature")
248
  seed_input = gr.Number(label="Seed (Optional)", precision=0, value=1234)
249
-
250
  examples_t2i = gr.Examples(
251
  label="Text to image generation examples.",
252
  examples=[
@@ -254,7 +267,6 @@ with gr.Blocks(css=css) as demo:
254
  "The face of a beautiful girl",
255
  "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
256
  "A cute and adorable baby fox with big brown eyes, autumn leaves in the background enchanting,immortal,fluffy, shiny mane,Petals,fairyism,unreal engine 5 and Octane Render,highly detailed, photorealistic, cinematic, natural colors.",
257
- "The image features an intricately designed eye set against a circular backdrop adorned with ornate swirl patterns that evoke both realism and surrealism. At the center of attention is a strikingly vivid blue iris surrounded by delicate veins radiating outward from the pupil to create depth and intensity. The eyelashes are long and dark, casting subtle shadows on the skin around them which appears smooth yet slightly textured as if aged or weathered over time.\n\nAbove the eye, there's a stone-like structure resembling part of classical architecture, adding layers of mystery and timeless elegance to the composition. This architectural element contrasts sharply but harmoniously with the organic curves surrounding it. Below the eye lies another decorative motif reminiscent of baroque artistry, further enhancing the overall sense of eternity encapsulated within each meticulously crafted detail. \n\nOverall, the atmosphere exudes a mysterious aura intertwined seamlessly with elements suggesting timelessness, achieved through the juxtaposition of realistic textures and surreal artistic flourishes. Each component\u2014from the intricate designs framing the eye to the ancient-looking stone piece above\u2014contributes uniquely towards creating a visually captivating tableau imbued with enigmatic allure.",
258
  ],
259
  inputs=prompt_input,
260
  )
 
1
+ import spaces # ⚠️ DEVE SER O PRIMEIRO - Importante para ZeroGPU!
2
+
3
  import gradio as gr
4
  import torch
5
  from transformers import AutoConfig, AutoModelForCausalLM
6
  from janus.models import MultiModalityCausalLM, VLChatProcessor
7
  from janus.utils.io import load_pil_images
8
  from PIL import Image
 
9
  import numpy as np
10
  import os
11
  import time
12
  from Upsample import RealESRGAN
 
 
13
 
14
+ # Variáveis globais (serão inicializadas dentro das funções)
15
+ vl_gpt = None
16
+ vl_chat_processor = None
17
+ tokenizer = None
18
+ sr_model = None
19
+ model_loaded = False
 
 
 
 
 
 
20
 
21
+ def load_models():
22
+ """Carrega os modelos apenas uma vez, quando necessário"""
23
+ global vl_gpt, vl_chat_processor, tokenizer, sr_model, model_loaded
24
+
25
+ if model_loaded:
26
+ return
27
+
28
+ # Carregar modelo principal
29
+ model_path = "deepseek-ai/Janus-Pro-7B"
30
+ config = AutoConfig.from_pretrained(model_path)
31
+ language_config = config.language_config
32
+ language_config._attn_implementation = 'eager'
33
+ vl_gpt = AutoModelForCausalLM.from_pretrained(model_path,
34
+ language_config=language_config,
35
+ trust_remote_code=True)
36
+
37
+ # Mover para GPU se disponível (sem variável global de device)
38
+ if torch.cuda.is_available():
39
+ vl_gpt = vl_gpt.to(torch.bfloat16).cuda()
40
+ else:
41
+ vl_gpt = vl_gpt.to(torch.float16)
42
+
43
+ vl_chat_processor = VLChatProcessor.from_pretrained(model_path)
44
+ tokenizer = vl_chat_processor.tokenizer
45
+
46
+ # Carregar modelo de upscaling
47
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
48
+ sr_model = RealESRGAN(torch.device(device), scale=2)
49
+ sr_model.load_weights(f'weights/RealESRGAN_x2.pth', download=False)
50
+
51
+ model_loaded = True
52
 
53
  @torch.inference_mode()
54
+ @spaces.GPU(duration=120)
 
55
  def multimodal_understanding(image, question, seed, top_p, temperature, progress=gr.Progress(track_tqdm=True)):
56
+ # Garantir que os modelos estão carregados
57
+ load_models()
58
+
59
  # Clear CUDA cache before generating
60
  torch.cuda.empty_cache()
61
 
62
  # set seed
63
  torch.manual_seed(seed)
64
  np.random.seed(seed)
65
+ if torch.cuda.is_available():
66
+ torch.cuda.manual_seed(seed)
67
 
68
  conversation = [
69
  {
 
75
  ]
76
 
77
  pil_images = [Image.fromarray(image)]
78
+
79
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
80
+ dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float16
81
+
82
  prepare_inputs = vl_chat_processor(
83
  conversations=conversation, images=pil_images, force_batchify=True
84
+ ).to(device, dtype=dtype)
 
85
 
86
  inputs_embeds = vl_gpt.prepare_inputs_embeds(**prepare_inputs)
87
 
 
101
  answer = tokenizer.decode(outputs[0].cpu().tolist(), skip_special_tokens=True)
102
  return answer
103
 
 
104
  def generate(input_ids,
105
  width,
106
  height,
 
110
  image_token_num_per_image: int = 576,
111
  patch_size: int = 16,
112
  progress=gr.Progress(track_tqdm=True)):
113
+
114
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
115
+
116
  # Clear CUDA cache before generating
117
  torch.cuda.empty_cache()
118
 
119
+ tokens = torch.zeros((parallel_size * 2, len(input_ids)), dtype=torch.int).to(device)
120
  for i in range(parallel_size * 2):
121
  tokens[i, :] = input_ids
122
  if i % 2 != 0:
123
  tokens[i, 1:-1] = vl_chat_processor.pad_id
124
  inputs_embeds = vl_gpt.language_model.get_input_embeddings()(tokens)
125
+ generated_tokens = torch.zeros((parallel_size, image_token_num_per_image), dtype=torch.int).to(device)
126
 
127
  pkv = None
128
  for i in range(image_token_num_per_image):
 
144
  img_embeds = vl_gpt.prepare_gen_img_embeds(next_token)
145
  inputs_embeds = img_embeds.unsqueeze(dim=1)
146
 
 
 
147
  patches = vl_gpt.gen_vision_model.decode_code(generated_tokens.to(dtype=torch.int),
148
  shape=[parallel_size, 8, width // patch_size, height // patch_size])
149
 
 
158
 
159
  return visual_img
160
 
 
 
161
  @torch.inference_mode()
162
+ @spaces.GPU(duration=120)
163
  def generate_image(prompt,
164
  seed=None,
165
  guidance=5,
166
  t2i_temperature=1.0,
167
  progress=gr.Progress(track_tqdm=True)):
168
+
169
+ # Garantir que os modelos estão carregados
170
+ load_models()
171
+
172
  # Clear CUDA cache and avoid tracking gradients
173
  torch.cuda.empty_cache()
174
+
175
  # Set the seed for reproducible results
176
  if seed is not None:
177
  torch.manual_seed(seed)
178
+ if torch.cuda.is_available():
179
+ torch.cuda.manual_seed(seed)
180
  np.random.seed(seed)
181
+
182
  width = 384
183
  height = 384
184
  parallel_size = 4
 
203
  height // 16 * 16,
204
  parallel_size=parallel_size)
205
 
 
 
206
  ret_images = [image_upsample(Image.fromarray(images[i])) for i in range(parallel_size)]
 
207
  return ret_images
208
 
 
209
  @spaces.GPU(duration=60)
210
  def image_upsample(img: Image.Image) -> Image.Image:
211
  if img is None:
212
  raise Exception("Image not uploaded")
213
 
214
+ # Garantir que o modelo de upscaling está carregado
215
+ load_models()
216
+
217
  width, height = img.size
218
 
219
  if width >= 5000 or height >= 5000:
 
222
  global sr_model
223
  result = sr_model.predict(img.convert('RGB'))
224
  return result
 
225
 
226
  # Gradio interface
227
  css = '''
228
  .gradio-container {max-width: 960px !important}
229
  '''
230
+
231
  with gr.Blocks(css=css) as demo:
232
  gr.Markdown("# Janus Pro 7B")
233
+
234
  with gr.Tab("Multimodal Understanding"):
235
  gr.Markdown(value="## Multimodal Understanding")
236
  image_input = gr.Image()
 
241
  understanding_output = gr.Textbox(label="Response")
242
 
243
  with gr.Accordion("Advanced options", open=False):
244
+ und_seed_input = gr.Number(label="Seed", precision=0, value=42)
245
+ top_p = gr.Slider(minimum=0, maximum=1, value=0.95, step=0.05, label="top_p")
246
+ temperature = gr.Slider(minimum=0, maximum=1, value=0.1, step=0.05, label="temperature")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
 
248
  with gr.Tab("Text-to-Image Generation"):
249
  gr.Markdown(value="## Text-to-Image Generation")
250
 
251
+ prompt_input = gr.Textbox(label="Prompt. (Prompt in more detail can help produce better images!)")
252
 
253
  generation_button = gr.Button("Generate Images")
254
 
 
259
  cfg_weight_input = gr.Slider(minimum=1, maximum=10, value=5, step=0.5, label="CFG Weight")
260
  t2i_temperature = gr.Slider(minimum=0, maximum=1, value=1.0, step=0.05, label="temperature")
261
  seed_input = gr.Number(label="Seed (Optional)", precision=0, value=1234)
262
+
263
  examples_t2i = gr.Examples(
264
  label="Text to image generation examples.",
265
  examples=[
 
267
  "The face of a beautiful girl",
268
  "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
269
  "A cute and adorable baby fox with big brown eyes, autumn leaves in the background enchanting,immortal,fluffy, shiny mane,Petals,fairyism,unreal engine 5 and Octane Render,highly detailed, photorealistic, cinematic, natural colors.",
 
270
  ],
271
  inputs=prompt_input,
272
  )