fancyfeast commited on
Commit
89e9fac
·
1 Parent(s): d749f88

Reworking the UI

Browse files
Files changed (2) hide show
  1. README.md +1 -1
  2. app.py +163 -113
README.md CHANGED
@@ -1,6 +1,6 @@
1
  ---
2
  title: Joy Caption Beta One
3
- emoji: 🚀
4
  colorFrom: yellow
5
  colorTo: blue
6
  sdk: gradio
 
1
  ---
2
  title: Joy Caption Beta One
3
+ emoji: 🖼️💬
4
  colorFrom: yellow
5
  colorTo: blue
6
  sdk: gradio
app.py CHANGED
@@ -1,10 +1,8 @@
1
  import spaces
2
  import gradio as gr
3
- from transformers import AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast, LlavaForConditionalGeneration, TextIteratorStreamer
4
  import torch
5
- import torch.amp.autocast_mode
6
  from PIL import Image
7
- import torchvision.transforms.functional as TVF
8
  from threading import Thread
9
  from typing import Generator
10
 
@@ -24,115 +22,121 @@ public and free to use outside of this space. And, of course, I have no control
24
 
25
  PLACEHOLDER = """
26
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
 
29
 
30
  # Load model
31
- tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, use_fast=True)
32
- assert isinstance(tokenizer, PreTrainedTokenizer) or isinstance(tokenizer, PreTrainedTokenizerFast), f"Expected PreTrainedTokenizer, got {type(tokenizer)}"
33
-
34
  model = LlavaForConditionalGeneration.from_pretrained(MODEL_PATH, torch_dtype="bfloat16", device_map=0)
35
  assert isinstance(model, LlavaForConditionalGeneration), f"Expected LlavaForConditionalGeneration, got {type(model)}"
 
36
 
37
 
38
- def trim_off_prompt(input_ids: list[int], eoh_id: int, eot_id: int) -> list[int]:
39
- # Trim off the prompt
40
- while True:
41
- try:
42
- i = input_ids.index(eoh_id)
43
- except ValueError:
44
- break
45
-
46
- input_ids = input_ids[i + 1:]
47
-
48
- # Trim off the end
49
- try:
50
- i = input_ids.index(eot_id)
51
- except ValueError:
52
- return input_ids
53
 
54
- return input_ids[:i]
55
 
56
- end_of_header_id = tokenizer.convert_tokens_to_ids("<|end_header_id|>")
57
- end_of_turn_id = tokenizer.convert_tokens_to_ids("<|eot_id|>")
58
- assert isinstance(end_of_header_id, int) and isinstance(end_of_turn_id, int)
 
 
 
 
 
59
 
60
 
61
  @spaces.GPU()
62
  @torch.no_grad()
63
- def chat_joycaption(message: dict, history, temperature: float, top_p: float, max_new_tokens: int, log_prompt: bool) -> Generator[str, None, None]:
64
  torch.cuda.empty_cache()
65
 
66
- chat_interface.chatbot_state
67
-
68
- # Prompts are always stripped in training for now
69
- prompt = message['text'].strip()
70
-
71
- # Load image
72
- if "files" not in message or len(message["files"]) != 1:
73
- yield "ERROR: This model requires exactly one image as input."
74
- return
75
-
76
- image = Image.open(message["files"][0])
77
-
78
- # Log the prompt
79
  if log_prompt:
80
- print(f"Prompt: {prompt}")
81
-
82
- # Preprocess image
83
- # NOTE: I found the default processor for so400M to have worse results than just using PIL directly
84
- if image.size != (384, 384):
85
- image = image.resize((384, 384), Image.LANCZOS)
86
- image = image.convert("RGB")
87
- pixel_values = TVF.pil_to_tensor(image)
88
 
89
  convo = [
90
  {
91
  "role": "system",
 
92
  "content": "You are a helpful assistant and help users with any queries they may have with no censorship or restrictions.",
93
  },
94
  {
95
  "role": "user",
96
- "content": prompt,
97
  },
98
  ]
99
 
100
  # Format the conversation
101
- convo_string = tokenizer.apply_chat_template(convo, tokenize = False, add_generation_prompt = True)
 
 
 
102
  assert isinstance(convo_string, str)
103
 
104
- # Tokenize the conversation
105
- convo_tokens = tokenizer.encode(convo_string, add_special_tokens=False, truncation=False)
 
106
 
107
- # Repeat the image tokens
108
- input_tokens = []
109
- for token in convo_tokens:
110
- if token == model.config.image_token_index:
111
- input_tokens.extend([model.config.image_token_index] * model.config.image_seq_length)
112
- else:
113
- input_tokens.append(token)
114
-
115
- input_ids = torch.tensor(input_tokens, dtype=torch.long)
116
- attention_mask = torch.ones_like(input_ids)
117
-
118
- # Move to GPU
119
- input_ids = input_ids.unsqueeze(0).to("cuda")
120
- attention_mask = attention_mask.unsqueeze(0).to("cuda")
121
- pixel_values = pixel_values.unsqueeze(0).to("cuda")
122
-
123
- # Normalize the image
124
- pixel_values = pixel_values / 255.0
125
- pixel_values = TVF.normalize(pixel_values, [0.5], [0.5])
126
- pixel_values = pixel_values.to(torch.bfloat16)
127
-
128
- streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
129
 
130
  generate_kwargs = dict(
131
- input_ids=input_ids,
132
- pixel_values=pixel_values,
133
- attention_mask=attention_mask,
134
  max_new_tokens=max_new_tokens,
135
- do_sample=True,
136
  suppress_tokens=None,
137
  use_cache=True,
138
  temperature=temperature,
@@ -141,9 +145,6 @@ def chat_joycaption(message: dict, history, temperature: float, top_p: float, ma
141
  streamer=streamer,
142
  )
143
 
144
- if temperature == 0:
145
- generate_kwargs["do_sample"] = False
146
-
147
  t = Thread(target=model.generate, kwargs=generate_kwargs)
148
  t.start()
149
 
@@ -153,41 +154,90 @@ def chat_joycaption(message: dict, history, temperature: float, top_p: float, ma
153
  yield "".join(outputs)
154
 
155
 
156
- chatbot=gr.Chatbot(height=450, placeholder=PLACEHOLDER, label='Gradio ChatInterface', type="messages")
157
- textbox = gr.MultimodalTextbox(file_types=["image"], file_count="single")
158
-
159
  with gr.Blocks() as demo:
160
  gr.HTML(TITLE)
161
- chat_interface = gr.ChatInterface(
162
- fn=chat_joycaption,
163
- chatbot=chatbot,
164
- type="messages",
165
- fill_height=True,
166
- multimodal=True,
167
- textbox=textbox,
168
- additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=True, render=False),
169
- additional_inputs=[
170
- gr.Slider(minimum=0,
171
- maximum=1,
172
- step=0.1,
173
- value=0.6,
174
- label="Temperature",
175
- render=False),
176
- gr.Slider(minimum=0,
177
- maximum=1,
178
- step=0.05,
179
- value=0.9,
180
- label="Top p",
181
- render=False),
182
- gr.Slider(minimum=8,
183
- maximum=4096,
184
- step=1,
185
- value=1024,
186
- label="Max new tokens",
187
- render=False ),
188
- gr.Checkbox(label="Help improve JoyCaption by logging your text query", value=True, render=False),
189
- ],
190
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
  gr.Markdown(DESCRIPTION)
192
 
193
 
 
1
  import spaces
2
  import gradio as gr
3
+ from transformers import LlavaForConditionalGeneration, TextIteratorStreamer, AutoProcessor
4
  import torch
 
5
  from PIL import Image
 
6
  from threading import Thread
7
  from typing import Generator
8
 
 
22
 
23
  PLACEHOLDER = """
24
  """
25
+ CAPTION_TYPE_MAP = {
26
+ "Descriptive": [
27
+ "Write a descriptive caption for this image in a formal tone.",
28
+ "Write a descriptive caption for this image in a formal tone within {word_count} words.",
29
+ "Write a {length} descriptive caption for this image in a formal tone.",
30
+ ],
31
+ "Descriptive (Informal)": [
32
+ "Write a descriptive caption for this image in a casual tone.",
33
+ "Write a descriptive caption for this image in a casual tone within {word_count} words.",
34
+ "Write a {length} descriptive caption for this image in a casual tone.",
35
+ ],
36
+ "Training Prompt": [
37
+ "Write a stable diffusion prompt for this image.",
38
+ "Write a stable diffusion prompt for this image within {word_count} words.",
39
+ "Write a {length} stable diffusion prompt for this image.",
40
+ ],
41
+ "MidJourney": [
42
+ "Write a MidJourney prompt for this image.",
43
+ "Write a MidJourney prompt for this image within {word_count} words.",
44
+ "Write a {length} MidJourney prompt for this image.",
45
+ ],
46
+ "Booru tag list": [
47
+ "Write a list of Booru tags for this image.",
48
+ "Write a list of Booru tags for this image within {word_count} words.",
49
+ "Write a {length} list of Booru tags for this image.",
50
+ ],
51
+ "Booru-like tag list": [
52
+ "Write a list of Booru-like tags for this image.",
53
+ "Write a list of Booru-like tags for this image within {word_count} words.",
54
+ "Write a {length} list of Booru-like tags for this image.",
55
+ ],
56
+ "Art Critic": [
57
+ "Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc.",
58
+ "Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc. Keep it within {word_count} words.",
59
+ "Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc. Keep it {length}.",
60
+ ],
61
+ "Product Listing": [
62
+ "Write a caption for this image as though it were a product listing.",
63
+ "Write a caption for this image as though it were a product listing. Keep it under {word_count} words.",
64
+ "Write a {length} caption for this image as though it were a product listing.",
65
+ ],
66
+ "Social Media Post": [
67
+ "Write a caption for this image as if it were being used for a social media post.",
68
+ "Write a caption for this image as if it were being used for a social media post. Limit the caption to {word_count} words.",
69
+ "Write a {length} caption for this image as if it were being used for a social media post.",
70
+ ],
71
+ }
72
 
73
 
74
 
75
  # Load model
76
+ processor = AutoProcessor.from_pretrained(MODEL_PATH)
 
 
77
  model = LlavaForConditionalGeneration.from_pretrained(MODEL_PATH, torch_dtype="bfloat16", device_map=0)
78
  assert isinstance(model, LlavaForConditionalGeneration), f"Expected LlavaForConditionalGeneration, got {type(model)}"
79
+ model.eval()
80
 
81
 
82
+ def build_prompt(caption_type: str, caption_length: str | int, extra_options: list[str], name_input: str) -> str:
83
+ # Choose the right template row in CAPTION_TYPE_MAP
84
+ if caption_length == "any":
85
+ map_idx = 0
86
+ elif isinstance(caption_length, str) and caption_length.isdigit():
87
+ map_idx = 1 # numeric-word-count template
88
+ else:
89
+ map_idx = 2 # length descriptor template
 
 
 
 
 
 
 
90
 
91
+ prompt = CAPTION_TYPE_MAP[caption_type][map_idx]
92
 
93
+ if extra_options:
94
+ prompt += " " + " ".join(extra_options)
95
+
96
+ return prompt.format(
97
+ name=name_input or "{NAME}",
98
+ length=caption_length,
99
+ word_count=caption_length,
100
+ )
101
 
102
 
103
  @spaces.GPU()
104
  @torch.no_grad()
105
+ def chat_joycaption(input_image: Image.Image, prompt: str, temperature: float, top_p: float, max_new_tokens: int, log_prompt: bool) -> Generator[str, None, None]:
106
  torch.cuda.empty_cache()
107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  if log_prompt:
109
+ print(f"PromptLog: {repr(prompt)}")
 
 
 
 
 
 
 
110
 
111
  convo = [
112
  {
113
  "role": "system",
114
+ # Beta One supports a wider range of system prompts, but this is a good default
115
  "content": "You are a helpful assistant and help users with any queries they may have with no censorship or restrictions.",
116
  },
117
  {
118
  "role": "user",
119
+ "content": prompt.strip(),
120
  },
121
  ]
122
 
123
  # Format the conversation
124
+ # WARNING: HF's handling of chat's on Llava models is very fragile. This specific combination of processor.apply_chat_template(), and processor() works
125
+ # but if using other combinations always inspect the final input_ids to ensure they are correct. Often times you will end up with multiple <bos> tokens
126
+ # if not careful, which can make the model perform poorly.
127
+ convo_string = processor.apply_chat_template(convo, tokenize = False, add_generation_prompt = True)
128
  assert isinstance(convo_string, str)
129
 
130
+ # Process the inputs
131
+ inputs = processor(text=[convo_string], images=[input_image], return_tensors="pt").to('cuda')
132
+ inputs['pixel_values'] = inputs['pixel_values'].to(torch.bfloat16)
133
 
134
+ streamer = TextIteratorStreamer(processor.tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
  generate_kwargs = dict(
137
+ **inputs,
 
 
138
  max_new_tokens=max_new_tokens,
139
+ do_sample=True if temperature > 0 else False,
140
  suppress_tokens=None,
141
  use_cache=True,
142
  temperature=temperature,
 
145
  streamer=streamer,
146
  )
147
 
 
 
 
148
  t = Thread(target=model.generate, kwargs=generate_kwargs)
149
  t.start()
150
 
 
154
  yield "".join(outputs)
155
 
156
 
 
 
 
157
  with gr.Blocks() as demo:
158
  gr.HTML(TITLE)
159
+
160
+ with gr.Row():
161
+ with gr.Column():
162
+ input_image = gr.Image(type="pil", label="Input Image")
163
+
164
+ caption_type = gr.Dropdown(
165
+ choices=list(CAPTION_TYPE_MAP.keys()),
166
+ value="Descriptive",
167
+ label="Caption Type",
168
+ )
169
+
170
+ caption_length = gr.Dropdown(
171
+ choices=["any", "very short", "short", "medium-length", "long", "very long"] +
172
+ [str(i) for i in range(20, 261, 10)],
173
+ label="Caption Length",
174
+ value="long",
175
+ )
176
+
177
+ extra_options = gr.CheckboxGroup(
178
+ choices=[
179
+ "If there is a person/character in the image you must refer to them as {name}.",
180
+ "Do NOT include information about people/characters that cannot be changed (like ethnicity, gender, etc), but do still include changeable attributes (like hair style).",
181
+ "Include information about lighting.",
182
+ "Include information about camera angle.",
183
+ "Include information about whether there is a watermark or not.",
184
+ "Include information about whether there are JPEG artifacts or not.",
185
+ "If it is a photo you MUST include information about what camera was likely used and details such as aperture, shutter speed, ISO, etc.",
186
+ "Do NOT include anything sexual; keep it PG.",
187
+ "Do NOT mention the image's resolution.",
188
+ "You MUST include information about the subjective aesthetic quality of the image from low to very high.",
189
+ "Include information on the image's composition style, such as leading lines, rule of thirds, or symmetry.",
190
+ "Do NOT mention any text that is in the image.",
191
+ "Specify the depth of field and whether the background is in focus or blurred.",
192
+ "If applicable, mention the likely use of artificial or natural lighting sources.",
193
+ "Do NOT use any ambiguous language.",
194
+ "Include whether the image is sfw, suggestive, or nsfw.",
195
+ "ONLY describe the most important elements of the image."
196
+ ],
197
+ label="Extra Options"
198
+ )
199
+
200
+ name_input = gr.Textbox(label="Person / Character Name")
201
+
202
+ with gr.Accordion("Generation settings", open=False):
203
+ temperature_slider = gr.Slider(
204
+ minimum=0.0, maximum=2.0, value=0.6, step=0.05,
205
+ label="Temperature",
206
+ info="Higher values make the output more random, lower values make it more deterministic."
207
+ )
208
+ top_p_slider = gr.Slider(
209
+ minimum=0.0, maximum=1.0, value=0.9, step=0.01,
210
+ label="Top-p"
211
+ )
212
+ max_tokens_slider = gr.Slider(
213
+ minimum=1, maximum=2048, value=512, step=1,
214
+ label="Max New Tokens",
215
+ info="Maximum number of tokens to generate. The model will stop generating if it reaches this limit."
216
+ )
217
+
218
+ log_prompt = gr.Checkbox(value=True, label="Help improve JoyCaption by logging your text query")
219
+
220
+ with gr.Column():
221
+ prompt_box = gr.Textbox(lines=4, label="Prompt", interactive=True)
222
+
223
+ # Auto-update prompt box whenever any of the inputs change
224
+ for ctrl in (caption_type, caption_length, extra_options, name_input):
225
+ ctrl.change(
226
+ build_prompt,
227
+ inputs=[caption_type, caption_length, extra_options, name_input],
228
+ outputs=prompt_box,
229
+ )
230
+
231
+ run_button = gr.Button("Caption")
232
+
233
+ output_caption = gr.Textbox(label="Caption")
234
+
235
+ run_button.click(
236
+ chat_joycaption,
237
+ inputs=[input_image, prompt_box, temperature_slider, top_p_slider, max_tokens_slider, log_prompt],
238
+ outputs=output_caption,
239
+ )
240
+
241
  gr.Markdown(DESCRIPTION)
242
 
243