stzhao commited on
Commit
0021f95
Β·
verified Β·
1 Parent(s): 6bcb844

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -40
app.py CHANGED
@@ -1,5 +1,6 @@
1
  import os
2
  import gradio as gr
 
3
  import torch
4
  import spaces
5
  from diffusers import Lumina2Pipeline
@@ -12,14 +13,14 @@ else:
12
 
13
  # Load models
14
  def load_models():
15
- model_name = "X-ART/LeX-Enhancer-full"
16
 
17
- model = AutoModelForCausalLM.from_pretrained(
18
- model_name,
19
- torch_dtype=torch.bfloat16,
20
- device_map="auto"
21
- )
22
- tokenizer = AutoTokenizer.from_pretrained(model_name)
23
 
24
  pipe = Lumina2Pipeline.from_pretrained(
25
  "X-ART/LeX-Lumina",
@@ -28,9 +29,10 @@ def load_models():
28
  device = "cuda" if torch.cuda.is_available() else "cpu"
29
  pipe.to("cuda")
30
 
31
- return model, tokenizer, pipe
32
 
33
- model, tokenizer, pipe = load_models()
 
34
 
35
  def truncate_caption_by_tokens(caption, max_tokens=256):
36
  """Truncate the caption to fit within the max token limit"""
@@ -41,39 +43,39 @@ def truncate_caption_by_tokens(caption, max_tokens=256):
41
  print(f"Caption was truncated from {len(tokens)} tokens to {max_tokens} tokens")
42
  return caption
43
 
44
- @spaces.GPU(duration=70)
45
- def generate_enhanced_caption(image_caption, text_caption):
46
- # model.to("cuda")
47
- """Generate enhanced caption using the LeX-Enhancer model"""
48
- combined_caption = f"{image_caption}, with the text on it: {text_caption}."
49
- instruction = """
50
- Below is the simple caption of an image with text. Please deduce the detailed description of the image based on this simple caption. Note: 1. The description should only include visual elements and should not contain any extended meanings. 2. The visual elements should be as rich as possible, such as the main objects in the image, their respective attributes, the spatial relationships between the objects, lighting and shadows, color style, any text in the image and its style, etc. 3. The output description should be a single paragraph and should not be structured. 4. The description should avoid certain situations, such as pure white or black backgrounds, blurry text, excessive rendering of text, or harsh visual styles. 5. The detailed caption should be human readable and fluent. 6. Avoid using vague expressions such as "may be" or "might be"; the generated caption must be in a definitive, narrative tone. 7. Do not use negative sentence structures, such as "there is nothing in the image," etc. The entire caption should directly describe the content of the image. 8. The entire output should be limited to 200 words.
51
- """
52
- messages = [
53
- {"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
54
- {"role": "user", "content": instruction + "\nSimple Caption:\n" + combined_caption}
55
- ]
56
- text = tokenizer.apply_chat_template(
57
- messages,
58
- tokenize=False,
59
- add_generation_prompt=True
60
- )
61
- model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
62
 
63
- generated_ids = model.generate(
64
- **model_inputs,
65
- max_new_tokens=1024
66
- )
67
- generated_ids = [
68
- output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
69
- ]
70
 
71
- response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
72
- enhanced_caption = response.split("</think>", -1)[-1].strip(" ").strip("\n")
73
- model.to("cpu")
74
- torch.cuda.empty_cache()
75
 
76
- return combined_caption, enhanced_caption
77
 
78
  @spaces.GPU(duration=60)
79
  def generate_image(enhanced_caption, seed, num_inference_steps, guidance_scale):
@@ -113,7 +115,8 @@ def run_pipeline(image_caption, text_caption, seed, num_inference_steps, guidanc
113
  combined_caption = f"{image_caption}, with the text on it: {text_caption}."
114
 
115
  if enable_enhancer:
116
- combined_caption, enhanced_caption = generate_enhanced_caption(image_caption, text_caption)
 
117
  else:
118
  enhanced_caption = combined_caption
119
 
 
1
  import os
2
  import gradio as gr
3
+ from gradio_client import Client, handle_file
4
  import torch
5
  import spaces
6
  from diffusers import Lumina2Pipeline
 
13
 
14
  # Load models
15
  def load_models():
16
+ # model_name = "X-ART/LeX-Enhancer-full"
17
 
18
+ # model = AutoModelForCausalLM.from_pretrained(
19
+ # model_name,
20
+ # torch_dtype=torch.bfloat16,
21
+ # device_map="auto"
22
+ # )
23
+ # tokenizer = AutoTokenizer.from_pretrained(model_name)
24
 
25
  pipe = Lumina2Pipeline.from_pretrained(
26
  "X-ART/LeX-Lumina",
 
29
  device = "cuda" if torch.cuda.is_available() else "cpu"
30
  pipe.to("cuda")
31
 
32
+ return pipe
33
 
34
+ pipe = load_models()
35
+ client = Client("stzhao/LeX-Enhancer")
36
 
37
  def truncate_caption_by_tokens(caption, max_tokens=256):
38
  """Truncate the caption to fit within the max token limit"""
 
43
  print(f"Caption was truncated from {len(tokens)} tokens to {max_tokens} tokens")
44
  return caption
45
 
46
+ # @spaces.GPU(duration=70)
47
+ # def generate_enhanced_caption(image_caption, text_caption):
48
+ # # model.to("cuda")
49
+ # """Generate enhanced caption using the LeX-Enhancer model"""
50
+ # combined_caption = f"{image_caption}, with the text on it: {text_caption}."
51
+ # instruction = """
52
+ # Below is the simple caption of an image with text. Please deduce the detailed description of the image based on this simple caption. Note: 1. The description should only include visual elements and should not contain any extended meanings. 2. The visual elements should be as rich as possible, such as the main objects in the image, their respective attributes, the spatial relationships between the objects, lighting and shadows, color style, any text in the image and its style, etc. 3. The output description should be a single paragraph and should not be structured. 4. The description should avoid certain situations, such as pure white or black backgrounds, blurry text, excessive rendering of text, or harsh visual styles. 5. The detailed caption should be human readable and fluent. 6. Avoid using vague expressions such as "may be" or "might be"; the generated caption must be in a definitive, narrative tone. 7. Do not use negative sentence structures, such as "there is nothing in the image," etc. The entire caption should directly describe the content of the image. 8. The entire output should be limited to 200 words.
53
+ # """
54
+ # messages = [
55
+ # {"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
56
+ # {"role": "user", "content": instruction + "\nSimple Caption:\n" + combined_caption}
57
+ # ]
58
+ # text = tokenizer.apply_chat_template(
59
+ # messages,
60
+ # tokenize=False,
61
+ # add_generation_prompt=True
62
+ # )
63
+ # model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
64
 
65
+ # generated_ids = model.generate(
66
+ # **model_inputs,
67
+ # max_new_tokens=1024
68
+ # )
69
+ # generated_ids = [
70
+ # output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
71
+ # ]
72
 
73
+ # response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
74
+ # enhanced_caption = response.split("</think>", -1)[-1].strip(" ").strip("\n")
75
+ # model.to("cpu")
76
+ # torch.cuda.empty_cache()
77
 
78
+ # return combined_caption, enhanced_caption
79
 
80
  @spaces.GPU(duration=60)
81
  def generate_image(enhanced_caption, seed, num_inference_steps, guidance_scale):
 
115
  combined_caption = f"{image_caption}, with the text on it: {text_caption}."
116
 
117
  if enable_enhancer:
118
+ # combined_caption, enhanced_caption = generate_enhanced_caption(image_caption, text_caption)
119
+ combined_caption, enhanced_caption = client.predict(image_caption, text_caption)
120
  else:
121
  enhanced_caption = combined_caption
122