Severian commited on
Commit
8b8900a
·
verified ·
1 Parent(s): 8a4f7ca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +531 -229
app.py CHANGED
@@ -10,56 +10,64 @@ from PIL import Image
10
  import os
11
  import torchvision.transforms.functional as TVF
12
 
 
 
 
 
 
 
 
13
 
14
  CLIP_PATH = "google/siglip-so400m-patch14-384"
15
- CHECKPOINT_PATH = Path("cgrkzexw-599808")
16
- TITLE = "<h1><center>JoyCaption Alpha Two (2024-09-26a)</center></h1>"
 
17
  CAPTION_TYPE_MAP = {
18
- "Descriptive": [
19
- "Write a descriptive caption for this image in a formal tone.",
20
- "Write a descriptive caption for this image in a formal tone within {word_count} words.",
21
- "Write a {length} descriptive caption for this image in a formal tone.",
22
- ],
23
- "Descriptive (Informal)": [
24
- "Write a descriptive caption for this image in a casual tone.",
25
- "Write a descriptive caption for this image in a casual tone within {word_count} words.",
26
- "Write a {length} descriptive caption for this image in a casual tone.",
27
- ],
28
- "Training Prompt": [
29
- "Write a stable diffusion prompt for this image.",
30
- "Write a stable diffusion prompt for this image within {word_count} words.",
31
- "Write a {length} stable diffusion prompt for this image.",
32
- ],
33
- "MidJourney": [
34
- "Write a MidJourney prompt for this image.",
35
- "Write a MidJourney prompt for this image within {word_count} words.",
36
- "Write a {length} MidJourney prompt for this image.",
37
- ],
38
- "Booru tag list": [
39
- "Write a list of Booru tags for this image.",
40
- "Write a list of Booru tags for this image within {word_count} words.",
41
- "Write a {length} list of Booru tags for this image.",
42
- ],
43
- "Booru-like tag list": [
44
- "Write a list of Booru-like tags for this image.",
45
- "Write a list of Booru-like tags for this image within {word_count} words.",
46
- "Write a {length} list of Booru-like tags for this image.",
47
- ],
48
- "Art Critic": [
49
- "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.",
50
- "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.",
51
- "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}.",
52
- ],
53
- "Product Listing": [
54
- "Write a caption for this image as though it were a product listing.",
55
- "Write a caption for this image as though it were a product listing. Keep it under {word_count} words.",
56
- "Write a {length} caption for this image as though it were a product listing.",
57
- ],
58
- "Social Media Post": [
59
- "Write a caption for this image as if it were being used for a social media post.",
60
- "Write a caption for this image as if it were being used for a social media post. Limit the caption to {word_count} words.",
61
- "Write a {length} caption for this image as if it were being used for a social media post.",
62
- ],
63
  }
64
 
65
  HF_TOKEN = os.environ.get("HF_TOKEN", None)
@@ -79,6 +87,10 @@ class ImageAdapter(nn.Module):
79
  self.ln1 = nn.Identity() if not ln1 else nn.LayerNorm(input_features)
80
  self.pos_emb = None if not pos_emb else nn.Parameter(torch.zeros(num_image_tokens, input_features))
81
 
 
 
 
 
82
  # Other tokens (<|image_start|>, <|image_end|>, <|eot_id|>)
83
  self.other_tokens = nn.Embedding(3, output_features)
84
  self.other_tokens.weight.data.normal_(mean=0.0, std=0.02) # Matches HF's implementation of llama3
@@ -107,6 +119,11 @@ class ImageAdapter(nn.Module):
107
  x = self.activation(x)
108
  x = self.linear2(x)
109
 
 
 
 
 
 
110
  # <|image_start|>, IMAGE, <|image_end|>
111
  other_tokens = self.other_tokens(torch.tensor([0, 1], device=self.other_tokens.weight.device).expand(x.shape[0], -1))
112
  assert other_tokens.shape == (x.shape[0], 2, x.shape[2]), f"Expected {(x.shape[0], 2, x.shape[2])}, got {other_tokens.shape}"
@@ -125,12 +142,12 @@ clip_processor = AutoProcessor.from_pretrained(CLIP_PATH)
125
  clip_model = AutoModel.from_pretrained(CLIP_PATH)
126
  clip_model = clip_model.vision_model
127
 
128
- assert (CHECKPOINT_PATH / "clip_model.pt").exists()
129
- print("Loading VLM's custom vision model")
130
- checkpoint = torch.load(CHECKPOINT_PATH / "clip_model.pt", map_location='cpu')
131
- checkpoint = {k.replace("_orig_mod.module.", ""): v for k, v in checkpoint.items()}
132
- clip_model.load_state_dict(checkpoint)
133
- del checkpoint
134
 
135
  clip_model.eval()
136
  clip_model.requires_grad_(False)
@@ -139,198 +156,483 @@ clip_model.to("cuda")
139
 
140
  # Tokenizer
141
  print("Loading tokenizer")
142
- tokenizer = AutoTokenizer.from_pretrained(CHECKPOINT_PATH / "text_model", use_fast=True)
143
  assert isinstance(tokenizer, PreTrainedTokenizer) or isinstance(tokenizer, PreTrainedTokenizerFast), f"Tokenizer is of type {type(tokenizer)}"
144
 
145
  # LLM
146
  print("Loading LLM")
147
- print("Loading VLM's custom text model")
148
- text_model = AutoModelForCausalLM.from_pretrained(CHECKPOINT_PATH / "text_model", device_map=0, torch_dtype=torch.bfloat16)
 
 
 
 
149
  text_model.eval()
150
 
151
  # Image Adapter
152
  print("Loading image adapter")
153
  image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size, False, False, 38, False)
154
- image_adapter.load_state_dict(torch.load(CHECKPOINT_PATH / "image_adapter.pt", map_location="cpu"))
155
  image_adapter.eval()
156
  image_adapter.to("cuda")
157
 
158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
  @spaces.GPU()
160
  @torch.no_grad()
161
- def stream_chat(input_image: Image.Image, caption_type: str, caption_length: str | int, extra_options: list[str], name_input: str, custom_prompt: str) -> tuple[str, str]:
162
- torch.cuda.empty_cache()
163
-
164
- # 'any' means no length specified
165
- length = None if caption_length == "any" else caption_length
166
-
167
- if isinstance(length, str):
168
- try:
169
- length = int(length)
170
- except ValueError:
171
- pass
172
-
173
- # Build prompt
174
- if length is None:
175
- map_idx = 0
176
- elif isinstance(length, int):
177
- map_idx = 1
178
- elif isinstance(length, str):
179
- map_idx = 2
180
- else:
181
- raise ValueError(f"Invalid caption length: {length}")
182
-
183
- prompt_str = CAPTION_TYPE_MAP[caption_type][map_idx]
184
-
185
- # Add extra options
186
- if len(extra_options) > 0:
187
- prompt_str += " " + " ".join(extra_options)
188
-
189
- # Add name, length, word_count
190
- prompt_str = prompt_str.format(name=name_input, length=caption_length, word_count=caption_length)
191
-
192
- if custom_prompt.strip() != "":
193
- prompt_str = custom_prompt.strip()
194
-
195
- # For debugging
196
- print(f"Prompt: {prompt_str}")
197
-
198
- # Preprocess image
199
- # NOTE: I found the default processor for so400M to have worse results than just using PIL directly
200
- #image = clip_processor(images=input_image, return_tensors='pt').pixel_values
201
- image = input_image.resize((384, 384), Image.LANCZOS)
202
- pixel_values = TVF.pil_to_tensor(image).unsqueeze(0) / 255.0
203
- pixel_values = TVF.normalize(pixel_values, [0.5], [0.5])
204
- pixel_values = pixel_values.to('cuda')
205
-
206
- # Embed image
207
- # This results in Batch x Image Tokens x Features
208
- with torch.amp.autocast_mode.autocast('cuda', enabled=True):
209
- vision_outputs = clip_model(pixel_values=pixel_values, output_hidden_states=True)
210
- embedded_images = image_adapter(vision_outputs.hidden_states)
211
- embedded_images = embedded_images.to('cuda')
212
-
213
- # Build the conversation
214
- convo = [
215
- {
216
- "role": "system",
217
- "content": "You are a helpful image captioner.",
218
- },
219
- {
220
- "role": "user",
221
- "content": prompt_str,
222
- },
223
- ]
224
-
225
- # Format the conversation
226
- convo_string = tokenizer.apply_chat_template(convo, tokenize = False, add_generation_prompt = True)
227
- assert isinstance(convo_string, str)
228
-
229
- # Tokenize the conversation
230
- # prompt_str is tokenized separately so we can do the calculations below
231
- convo_tokens = tokenizer.encode(convo_string, return_tensors="pt", add_special_tokens=False, truncation=False)
232
- prompt_tokens = tokenizer.encode(prompt_str, return_tensors="pt", add_special_tokens=False, truncation=False)
233
- assert isinstance(convo_tokens, torch.Tensor) and isinstance(prompt_tokens, torch.Tensor)
234
- convo_tokens = convo_tokens.squeeze(0) # Squeeze just to make the following easier
235
- prompt_tokens = prompt_tokens.squeeze(0)
236
-
237
- # Calculate where to inject the image
238
- eot_id_indices = (convo_tokens == tokenizer.convert_tokens_to_ids("<|eot_id|>")).nonzero(as_tuple=True)[0].tolist()
239
- assert len(eot_id_indices) == 2, f"Expected 2 <|eot_id|> tokens, got {len(eot_id_indices)}"
240
-
241
- preamble_len = eot_id_indices[1] - prompt_tokens.shape[0] # Number of tokens before the prompt
242
-
243
- # Embed the tokens
244
- convo_embeds = text_model.model.embed_tokens(convo_tokens.unsqueeze(0).to('cuda'))
245
-
246
- # Construct the input
247
- input_embeds = torch.cat([
248
- convo_embeds[:, :preamble_len], # Part before the prompt
249
- embedded_images.to(dtype=convo_embeds.dtype), # Image
250
- convo_embeds[:, preamble_len:], # The prompt and anything after it
251
- ], dim=1).to('cuda')
252
-
253
- input_ids = torch.cat([
254
- convo_tokens[:preamble_len].unsqueeze(0),
255
- torch.zeros((1, embedded_images.shape[1]), dtype=torch.long), # Dummy tokens for the image (TODO: Should probably use a special token here so as not to confuse any generation algorithms that might be inspecting the input)
256
- convo_tokens[preamble_len:].unsqueeze(0),
257
- ], dim=1).to('cuda')
258
- attention_mask = torch.ones_like(input_ids)
259
-
260
- # Debugging
261
- print(f"Input to model: {repr(tokenizer.decode(input_ids[0]))}")
262
-
263
- #generate_ids = text_model.generate(input_ids, inputs_embeds=inputs_embeds, attention_mask=attention_mask, max_new_tokens=300, do_sample=False, suppress_tokens=None)
264
- #generate_ids = text_model.generate(input_ids, inputs_embeds=inputs_embeds, attention_mask=attention_mask, max_new_tokens=300, do_sample=True, top_k=10, temperature=0.5, suppress_tokens=None)
265
- generate_ids = text_model.generate(input_ids, inputs_embeds=input_embeds, attention_mask=attention_mask, max_new_tokens=300, do_sample=True, suppress_tokens=None) # Uses the default which is temp=0.6, top_p=0.9
266
-
267
- # Trim off the prompt
268
- generate_ids = generate_ids[:, input_ids.shape[1]:]
269
- if generate_ids[0][-1] == tokenizer.eos_token_id or generate_ids[0][-1] == tokenizer.convert_tokens_to_ids("<|eot_id|>"):
270
- generate_ids = generate_ids[:, :-1]
271
-
272
- caption = tokenizer.batch_decode(generate_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)[0]
273
-
274
- return prompt_str, caption.strip()
275
-
276
-
277
- with gr.Blocks() as demo:
278
- gr.HTML(TITLE)
279
-
280
- with gr.Row():
281
- with gr.Column():
282
- input_image = gr.Image(type="pil", label="Input Image")
283
-
284
- caption_type = gr.Dropdown(
285
- choices=["Descriptive", "Descriptive (Informal)", "Training Prompt", "MidJourney", "Booru tag list", "Booru-like tag list", "Art Critic", "Product Listing", "Social Media Post"],
286
- label="Caption Type",
287
- value="Descriptive",
288
- )
289
-
290
- caption_length = gr.Dropdown(
291
- choices=["any", "very short", "short", "medium-length", "long", "very long"] +
292
- [str(i) for i in range(20, 261, 10)],
293
- label="Caption Length",
294
- value="long",
295
- )
296
-
297
- extra_options = gr.CheckboxGroup(
298
- choices=[
299
- "If there is a person/character in the image you must refer to them as {name}.",
300
- "Do NOT include information about people/characters that cannot be changed (like ethnicity, gender, etc), but do still include changeable attributes (like hair style).",
301
- "Include information about lighting.",
302
- "Include information about camera angle.",
303
- "Include information about whether there is a watermark or not.",
304
- "Include information about whether there are JPEG artifacts or not.",
305
- "If it is a photo you MUST include information about what camera was likely used and details such as aperture, shutter speed, ISO, etc.",
306
- "Do NOT include anything sexual; keep it PG.",
307
- "Do NOT mention the image's resolution.",
308
- "You MUST include information about the subjective aesthetic quality of the image from low to very high.",
309
- "Include information on the image's composition style, such as leading lines, rule of thirds, or symmetry.",
310
- "Do NOT mention any text that is in the image.",
311
- "Specify the depth of field and whether the background is in focus or blurred.",
312
- "If applicable, mention the likely use of artificial or natural lighting sources.",
313
- "Do NOT use any ambiguous language.",
314
- "Include whether the image is sfw, suggestive, or nsfw.",
315
- "ONLY describe the most important elements of the image."
316
- ],
317
- label="Extra Options"
318
- )
319
-
320
- name_input = gr.Textbox(label="Person/Character Name (if applicable)")
321
- gr.Markdown("**Note:** Name input is only used if an Extra Option is selected that requires it.")
322
-
323
- custom_prompt = gr.Textbox(label="Custom Prompt (optional, will override all other settings)")
324
- gr.Markdown("**Note:** Alpha Two is not a general instruction follower and will not follow prompts outside its training data well. Use this feature with caution.")
325
-
326
- run_button = gr.Button("Caption")
327
-
328
- with gr.Column():
329
- output_prompt = gr.Textbox(label="Prompt that was used")
330
- output_caption = gr.Textbox(label="Caption")
331
-
332
- run_button.click(fn=stream_chat, inputs=[input_image, caption_type, caption_length, extra_options, name_input, custom_prompt], outputs=[output_prompt, output_caption])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
333
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
334
 
335
  if __name__ == "__main__":
336
  demo.launch()
 
10
  import os
11
  import torchvision.transforms.functional as TVF
12
 
13
+ from dotenv import load_dotenv
14
+
15
+ # Load environment variables from .env file
16
+ load_dotenv()
17
+
18
+ USERNAME = os.getenv("USERNAME")
19
+ PASSWORD = os.getenv("PASSWORD")
20
 
21
  CLIP_PATH = "google/siglip-so400m-patch14-384"
22
+ MODEL_PATH = "meta-llama/Meta-Llama-3.1-8B"
23
+ CHECKPOINT_PATH = Path("9em124t2-499968")
24
+ TITLE = "<h1><center>JoyCaption Alpha One (2024-09-20a)</center></h1>"
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
  HF_TOKEN = os.environ.get("HF_TOKEN", None)
 
87
  self.ln1 = nn.Identity() if not ln1 else nn.LayerNorm(input_features)
88
  self.pos_emb = None if not pos_emb else nn.Parameter(torch.zeros(num_image_tokens, input_features))
89
 
90
+ # Mode token
91
+ #self.mode_token = nn.Embedding(n_modes, output_features)
92
+ #self.mode_token.weight.data.normal_(mean=0.0, std=0.02) # Matches HF's implementation of llama3
93
+
94
  # Other tokens (<|image_start|>, <|image_end|>, <|eot_id|>)
95
  self.other_tokens = nn.Embedding(3, output_features)
96
  self.other_tokens.weight.data.normal_(mean=0.0, std=0.02) # Matches HF's implementation of llama3
 
119
  x = self.activation(x)
120
  x = self.linear2(x)
121
 
122
+ # Mode token
123
+ #mode_token = self.mode_token(mode)
124
+ #assert mode_token.shape == (x.shape[0], mode_token.shape[1], x.shape[2]), f"Expected {(x.shape[0], 1, x.shape[2])}, got {mode_token.shape}"
125
+ #x = torch.cat((x, mode_token), dim=1)
126
+
127
  # <|image_start|>, IMAGE, <|image_end|>
128
  other_tokens = self.other_tokens(torch.tensor([0, 1], device=self.other_tokens.weight.device).expand(x.shape[0], -1))
129
  assert other_tokens.shape == (x.shape[0], 2, x.shape[2]), f"Expected {(x.shape[0], 2, x.shape[2])}, got {other_tokens.shape}"
 
142
  clip_model = AutoModel.from_pretrained(CLIP_PATH)
143
  clip_model = clip_model.vision_model
144
 
145
+ if (CHECKPOINT_PATH / "clip_model.pt").exists():
146
+ print("Loading VLM's custom vision model")
147
+ checkpoint = torch.load(CHECKPOINT_PATH / "clip_model.pt", map_location='cpu')
148
+ checkpoint = {k.replace("_orig_mod.module.", ""): v for k, v in checkpoint.items()}
149
+ clip_model.load_state_dict(checkpoint)
150
+ del checkpoint
151
 
152
  clip_model.eval()
153
  clip_model.requires_grad_(False)
 
156
 
157
  # Tokenizer
158
  print("Loading tokenizer")
159
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, use_fast=False)
160
  assert isinstance(tokenizer, PreTrainedTokenizer) or isinstance(tokenizer, PreTrainedTokenizerFast), f"Tokenizer is of type {type(tokenizer)}"
161
 
162
  # LLM
163
  print("Loading LLM")
164
+ if (CHECKPOINT_PATH / "text_model").exists:
165
+ print("Loading VLM's custom text model")
166
+ text_model = AutoModelForCausalLM.from_pretrained(CHECKPOINT_PATH / "text_model", device_map=0, torch_dtype=torch.bfloat16)
167
+ else:
168
+ text_model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, device_map="auto", torch_dtype=torch.bfloat16)
169
+
170
  text_model.eval()
171
 
172
  # Image Adapter
173
  print("Loading image adapter")
174
  image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size, False, False, 38, False)
175
+ image_adapter.load_state_dict(torch.load(CHECKPOINT_PATH / "image_adapter.pt", map_location="cpu", weights_only=True))
176
  image_adapter.eval()
177
  image_adapter.to("cuda")
178
 
179
 
180
+ def preprocess_image(input_image: Image.Image) -> torch.Tensor:
181
+ """
182
+ Preprocess the input image for the CLIP model.
183
+ """
184
+ image = input_image.resize((384, 384), Image.LANCZOS)
185
+ pixel_values = TVF.pil_to_tensor(image).unsqueeze(0) / 255.0
186
+ pixel_values = TVF.normalize(pixel_values, [0.5], [0.5])
187
+ return pixel_values.to('cuda')
188
+
189
+ def generate_caption(text_model, tokenizer, image_features, prompt_str: str, max_new_tokens: int = 300) -> str:
190
+ """
191
+ Generate a caption based on the image features and prompt.
192
+ """
193
+ prompt = tokenizer.encode(prompt_str, return_tensors='pt', padding=False, truncation=False, add_special_tokens=False)
194
+ prompt_embeds = text_model.model.embed_tokens(prompt.to('cuda'))
195
+ embedded_bos = text_model.model.embed_tokens(torch.tensor([[tokenizer.bos_token_id]], device=text_model.device, dtype=torch.int64))
196
+ eot_embed = image_adapter.get_eot_embedding().unsqueeze(0).to(dtype=text_model.dtype)
197
+
198
+ inputs_embeds = torch.cat([
199
+ embedded_bos.expand(image_features.shape[0], -1, -1),
200
+ image_features.to(dtype=embedded_bos.dtype),
201
+ prompt_embeds.expand(image_features.shape[0], -1, -1),
202
+ eot_embed.expand(image_features.shape[0], -1, -1),
203
+ ], dim=1)
204
+
205
+ input_ids = torch.cat([
206
+ torch.tensor([[tokenizer.bos_token_id]], dtype=torch.long),
207
+ torch.zeros((1, image_features.shape[1]), dtype=torch.long),
208
+ prompt,
209
+ torch.tensor([[tokenizer.convert_tokens_to_ids("<|eot_id|>")]], dtype=torch.long),
210
+ ], dim=1).to('cuda')
211
+ attention_mask = torch.ones_like(input_ids)
212
+
213
+ generate_ids = text_model.generate(input_ids, inputs_embeds=inputs_embeds, attention_mask=attention_mask, max_new_tokens=max_new_tokens, do_sample=True, suppress_tokens=None)
214
+
215
+ generate_ids = generate_ids[:, input_ids.shape[1]:]
216
+ if generate_ids[0][-1] == tokenizer.eos_token_id or generate_ids[0][-1] == tokenizer.convert_tokens_to_ids("<|eot_id|>"):
217
+ generate_ids = generate_ids[:, :-1]
218
+
219
+ return tokenizer.batch_decode(generate_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)[0].strip()
220
+
221
  @spaces.GPU()
222
  @torch.no_grad()
223
+ def stream_chat(input_image: Image.Image, caption_type: str, caption_length: str | int, extra_options: list[str], name_input: str, custom_prompt: str, lens_type: str = "", film_stock: str = "", composition_style: str = "", lighting_aspect: str = "", special_technique: str = "", color_effect: str = "") -> tuple[str, str]:
224
+ torch.cuda.empty_cache()
225
+
226
+ # 'any' means no length specified
227
+ length = None if caption_length == "any" else caption_length
228
+
229
+ if isinstance(length, str):
230
+ try:
231
+ length = int(length)
232
+ except ValueError:
233
+ pass
234
+
235
+ # Build prompt
236
+ if length is None:
237
+ map_idx = 0
238
+ elif isinstance(length, int):
239
+ map_idx = 1
240
+ elif isinstance(length, str):
241
+ map_idx = 2
242
+ else:
243
+ raise ValueError(f"Invalid caption length: {length}")
244
+
245
+ prompt_str = CAPTION_TYPE_MAP[caption_type][map_idx]
246
+
247
+ # Add extra options
248
+ if len(extra_options) > 0:
249
+ prompt_str += " " + " ".join(extra_options)
250
+
251
+ # Add name, length, word_count
252
+ prompt_str = prompt_str.format(name=name_input, length=caption_length, word_count=caption_length)
253
+
254
+ if custom_prompt.strip() != "":
255
+ prompt_str = custom_prompt.strip()
256
+
257
+ # Add style prompt options
258
+ if caption_type == "Style Prompt":
259
+ prompt_str += f" Incorporate the effect of a {lens_type} lens. "
260
+ prompt_str += f"Apply the characteristics of {film_stock} film stock. "
261
+ prompt_str += f"Use a {composition_style} composition style. "
262
+ prompt_str += f"Implement {lighting_aspect} lighting. "
263
+ prompt_str += f"Apply the {special_technique} technique. "
264
+ prompt_str += f"Use a {color_effect} color effect. "
265
+
266
+ # For debugging
267
+ print(f"Prompt: {prompt_str}")
268
+
269
+ pixel_values = preprocess_image(input_image)
270
+
271
+ with torch.amp.autocast_mode.autocast('cuda', enabled=True):
272
+ vision_outputs = clip_model(pixel_values=pixel_values, output_hidden_states=True)
273
+ image_features = vision_outputs.hidden_states
274
+ embedded_images = image_adapter(image_features)
275
+ embedded_images = embedded_images.to('cuda')
276
+
277
+ # Load the model from MODEL_PATH
278
+ text_model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, device_map="auto", torch_dtype=torch.bfloat16)
279
+ text_model.eval()
280
+
281
+ caption = generate_caption(text_model, tokenizer, embedded_images, prompt_str)
282
+
283
+ return prompt_str, caption.strip()
284
+
285
+ css = """
286
+ h1, h2, h3, h4, h5, h6, p, li, ul, ol, a, img {
287
+ text-align: left;
288
+ }
289
+ img {
290
+ display: inline-block;
291
+ vertical-align: middle;
292
+ margin-right: 10px;
293
+ max-width: 100%;
294
+ height: auto;
295
+ }
296
+ .centered-image {
297
+ display: block;
298
+ margin-left: auto;
299
+ margin-right: auto;
300
+ max-width: 100%;
301
+ height: auto;
302
+ }
303
+ ul, ol {
304
+ padding-left: 20px;
305
+ }
306
+ .gradio-container {
307
+ max-width: 100% !important;
308
+ padding: 0 !important;
309
+ }
310
+ .gradio-row {
311
+ margin-left: 0 !important;
312
+ margin-right: 0 !important;
313
+ }
314
+ .gradio-column {
315
+ padding-left: 0 !important;
316
+ padding-right: 0 !important;
317
+ }
318
+ /* Left-align dropdown text */
319
+ .gradio-dropdown > div {
320
+ text-align: left !important;
321
+ }
322
+ /* Left-align checkbox labels */
323
+ .gradio-checkbox label {
324
+ text-align: left !important;
325
+ }
326
+ /* Left-align radio button labels */
327
+ .gradio-radio label {
328
+ text-align: left !important;
329
+ }
330
+ """
331
+
332
+ # Add detailed descriptions for each option
333
+ lens_types_info = {
334
+ "Standard": "A versatile lens with a field of view similar to human vision.",
335
+ "Wide-angle": "Captures a wider field of view, great for landscapes and architecture. Applies moderate to strong lens effect with image warp.",
336
+ "Telephoto": "Used for distant subjects, gives an 'award-winning' or 'National Geographic' look. Creates interesting effects when prompted.",
337
+ "Macro": "For extreme close-up photography, revealing tiny details.",
338
+ "Fish-eye": "Ultra-wide-angle lens that creates a strong bubble-like distortion. Generates panoramic photos with the entire image warping into a bubble.",
339
+ "Tilt-shift": "Allows adjusting the plane of focus, creating a 'miniature' effect. Known for the 'diorama miniature look'.",
340
+ "Zoom lens": "Variable focal length lens. Often zooms in on the subject, perfect for creating a base for inpainting. Interesting effect on landscapes with motion blur.",
341
+ "GoPro": "Wide-angle lens with clean digital look. Excludes film grain and most filter effects, resulting in natural colors and regular saturation.",
342
+ "Pinhole camera": "Creates a unique, foggy, low-detail, historic photograph look. Used since the 1850s, with peak popularity in the 1930s."
343
+ }
344
+
345
+ film_stocks_info = {
346
+ "Kodak Portra": "Professional color negative film known for its natural skin tones and low contrast.",
347
+ "Fujifilm Velvia": "Slide film known for vibrant colors and high saturation, popular among landscape photographers.",
348
+ "Ilford Delta": "Black and white film known for its fine grain and high sharpness.",
349
+ "Kodak Tri-X": "Classic high-speed black and white film, known for its distinctive grain and wide exposure latitude.",
350
+ "Fujifilm Provia": "Color reversal film known for its natural color reproduction and fine grain.",
351
+ "Cinestill": "Color photos with fine/low grain and higher than average resolution. Colors are slightly oversaturated or slightly desaturated.",
352
+ "Ektachrome": "Color photos with fine/low to moderate grain. Colors on the colder part of spectrum or regular, with normal or slightly higher saturation.",
353
+ "Ektar": "Modern Kodak film. Color photos with little to no grain. Results look like regular modern photography with artistic angles.",
354
+ "Film Washi": "Mostly black and white photos with fine/low to moderate grain. Occasionally gives colored photos with low saturation. Distinct style with high black contrast and soft camera lens effect.",
355
+ "Fomapan": "Black and white photos with fine/low to moderate grain, highly artistic exposure and angles. Adds very soft lens effect without distortion, dark photo vignette.",
356
+ "Fujicolor": "Color photos with fine/low to moderate grain. Colors are either very oversaturated or slightly desaturated, with entire color hue shifted in a very distinct manner.",
357
+ "Holga": "Color photos with high grain. Colors are either very oversaturated or slightly desaturated. Distinct contrast of black. Often applies photographic vignette.",
358
+ "Instax": "Instant color photos similar to Polaroid but clearer. Near perfect colors, regular saturation, fine/low to medium grain.",
359
+ "Lomography": "Color photos with high grain. Colors are either very oversaturated or slightly desaturated. Distinct contrast of black. Often applies photographic vignette.",
360
+ "Kodachrome": "Color photos with moderate grain. Colors on either colder part of spectrum or regular, with normal or slightly higher saturation.",
361
+ "Rollei": "Mostly black and white photos, sometimes color with fine/low grain. Can be sepia colored or have unusual hues and desaturation. Great for landscapes."
362
+ }
363
+
364
+ composition_styles_info = {
365
+ "Rule of Thirds": "Divides the frame into a 3x3 grid, placing key elements along the lines or at their intersections.",
366
+ "Golden Ratio": "Uses a spiral based on the golden ratio to create a balanced and aesthetically pleasing composition.",
367
+ "Symmetry": "Creates a mirror-like balance in the image, often used for architectural or nature photography.",
368
+ "Leading Lines": "Uses lines within the frame to draw the viewer's eye to the main subject or through the image.",
369
+ "Framing": "Uses elements within the scene to create a frame around the main subject.",
370
+ "Minimalism": "Simplifies the composition to its essential elements, often with a lot of negative space.",
371
+ "Fill the Frame": "The main subject dominates the entire frame, leaving little to no background.",
372
+ "Negative Space": "Uses empty space around the subject to create a sense of simplicity or isolation.",
373
+ "Centered Composition": "Places the main subject in the center of the frame, creating a sense of stability or importance.",
374
+ "Diagonal Lines": "Uses diagonal elements to create a sense of movement or dynamic tension in the image.",
375
+ "Triangular Composition": "Arranges elements in the frame to form a triangle, creating a sense of stability and harmony.",
376
+ "Radial Balance": "Arranges elements in a circular pattern around a central point, creating a sense of movement or completeness."
377
+ }
378
+
379
+ lighting_aspects_info = {
380
+ "Natural light": "Uses available light from the sun or sky, often creating soft, even illumination.",
381
+ "Studio lighting": "Controlled artificial lighting setup, allowing for precise manipulation of light and shadow.",
382
+ "Back light": "Light source behind the subject, creating silhouettes or rim lighting effects.",
383
+ "Split light": "Strong light source at 90-degree angle, lighting one half of the subject while leaving the other in shadow.",
384
+ "Broad light": "Light source at an angle to the subject, producing well-lit photographs with soft to moderate shadows.",
385
+ "Dim light": "Weak or distant light source, creating lower than average brightness and often dramatic images.",
386
+ "Flash photography": "Uses a brief, intense burst of light. Can be fill flash (even lighting) or harsh flash (strong contrasts).",
387
+ "Sunlight": "Direct light from the sun, often creating strong contrasts and warm tones.",
388
+ "Moonlight": "Soft, cool light from the moon, often creating a mysterious or romantic atmosphere.",
389
+ "Spotlight": "Focused beam of light illuminating a specific area, creating high contrast between light and shadow.",
390
+ "High-key lighting": "Bright, even lighting with minimal shadows, creating a light and airy feel.",
391
+ "Low-key lighting": "Predominantly dark tones with selective lighting, creating a moody or dramatic atmosphere.",
392
+ "Rembrandt lighting": "Classic portrait lighting technique creating a triangle of light on the cheek of the subject."
393
+ }
394
+
395
+ special_techniques_info = {
396
+ "Double exposure": "Superimposes two exposures to create a single image, often resulting in a dreamy or surreal effect.",
397
+ "Long exposure": "Uses a long shutter speed to capture motion over time, often creating smooth, blurred effects for moving elements.",
398
+ "Multiple exposure": "Superimposes multiple exposures, multiplying the subject or its key elements across the image.",
399
+ "HDR": "High Dynamic Range imaging, combining multiple exposures to capture a wider range of light and dark tones.",
400
+ "Bokeh effect": "Creates a soft, out-of-focus background, often with circular highlights.",
401
+ "Silhouette": "Captures the outline of a subject against a brighter background, creating a dramatic contrast.",
402
+ "Panning": "Follows a moving subject with the camera, creating a sharp subject with a blurred background.",
403
+ "Light painting": "Uses long exposure and moving light sources to 'paint' with light in the image.",
404
+ "Infrared photography": "Captures light in the infrared spectrum, often resulting in surreal, otherworldly images.",
405
+ "Ultraviolet photography": "Captures light in the ultraviolet spectrum, often revealing hidden patterns or creating a strong violet glow.",
406
+ "Kirlian photography": "High-voltage photographic technique that captures corona discharges around objects, creating a glowing effect.",
407
+ "Thermography": "Captures infrared radiation to create images based on temperature differences, resulting in false-color heat maps.",
408
+ "Astrophotography": "Specialized technique for capturing astronomical objects and celestial events, often resulting in stunning starry backgrounds.",
409
+ "Underwater photography": "Captures images beneath the surface of water, often in pools, seas, or aquariums.",
410
+ "Aerial photography": "Captures images from an elevated position, such as from drones, helicopters, or planes.",
411
+ "Macro photography": "Extreme close-up photography, revealing tiny details not visible to the naked eye."
412
+ }
413
+
414
+ color_effects_info = {
415
+ "Black and white": "Removes all color, leaving only shades of gray.",
416
+ "Sepia": "Reddish-brown monochrome effect, often associated with vintage photography.",
417
+ "Monochrome": "Uses variations of a single color.",
418
+ "Vintage color": "Muted or faded color palette reminiscent of old photographs.",
419
+ "Cross-processed": "Deliberate processing of film in the wrong chemicals, creating unusual color shifts.",
420
+ "Desaturated": "Reduces the intensity of all colors in the image.",
421
+ "Vivid colors": "Increases the saturation and intensity of colors.",
422
+ "Pastel colors": "Soft, pale colors with a light and airy feel.",
423
+ "High contrast": "Emphasizes the difference between light and dark areas in the image.",
424
+ "Low contrast": "Reduces the difference between light and dark areas, creating a softer look.",
425
+ "Color splash": "Converts most of the image to black and white while leaving one or more elements in color."
426
+ }
427
 
428
+ def get_dropdown_choices(info_dict):
429
+ return [f"{key}: {value}" for key, value in info_dict.items()]
430
+
431
+ def login(username, password):
432
+ if username == USERNAME and password == PASSWORD:
433
+ return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(value="Login successful! You can now access the Caption Captain tab.", visible=True)
434
+ else:
435
+ return gr.update(visible=False), gr.update(visible=True), gr.update(visible=True), gr.update(value="Invalid username or password. Please try again.", visible=True)
436
+
437
+ # Gradio interface
438
+ with gr.Blocks(theme="Hev832/Applio", css=css, fill_width=True, fill_height=True) as demo:
439
+ with gr.Tab("Welcome"):
440
+ with gr.Row(elem_classes="welcome-tab"):
441
+ with gr.Column(scale=2, elem_classes="welcome-content"):
442
+ gr.Markdown(
443
+ """
444
+ <img src="https://cdn-uploads.huggingface.co/production/uploads/64740cf7485a7c8e1bd51ac9/LVZnwLV43UUvKu3HORqSs.webp" alt="UDG" width="250" style="max-width: 100%; height: auto; class="centered-image">
445
+
446
+ # 🎨 Underground Digital's Caption Captain: AI-Powered Art Inspiration
447
+
448
+ ## Accelerate Your Creative Workflow with Intelligent Image Analysis
449
+
450
+ This innovative tool empowers Yamamoto's artists to quickly generate descriptive captions,<br>
451
+ training prompts, and tags from existing artwork, fueling the creative process for GenAI models.
452
+
453
+ ## 🚀 How It Works:
454
+ 1. **Upload Your Inspiration**: Drop in an image (e.g., a charcoal horse picture) that embodies your desired style.
455
+ 2. **Choose Your Output**: Select from descriptive captions, training prompts, and tags.
456
+ 3. **Customize the Results**: Adjust tone, length, and other parameters to fine-tune the output.
457
+ 4. **Generate and Iterate**: Click 'Caption' to analyze your image and use the results to inspire new creations.
458
+ """
459
+ )
460
+
461
+ with gr.Column(scale=1):
462
+ with gr.Row():
463
+ gr.Markdown(
464
+ """
465
+ Login below using the internal<br>
466
+ username and password to access the full app.<br>
467
+
468
+ Once logged in, a new tab will appear named<br>
469
+ "Caption Captain" allowing you to access the app.
470
+ """
471
+ )
472
+
473
+ with gr.Row():
474
+ username = gr.Textbox(label="Username", placeholder="Enter your username")
475
+ with gr.Row():
476
+ password = gr.Textbox(label="Password", type="password", placeholder="Enter your password")
477
+ with gr.Row():
478
+ login_button = gr.Button("Login", size="sm")
479
+ login_message = gr.Markdown(visible=False)
480
+
481
+ caption_captain_tab = gr.Tab("Caption Captain", visible=False)
482
+ with caption_captain_tab:
483
+ with gr.Accordion("How to Use Caption Captain", open=False):
484
+ gr.Markdown("""
485
+ # How to Use Caption Captain
486
+
487
+ <img src="https://cdn-uploads.huggingface.co/production/uploads/64740cf7485a7c8e1bd51ac9/Ce_Z478iOXljvpZ_Fr_Y7.png" alt="Captain" width="100" style="max-width: 100%; height: auto;">
488
+
489
+ Hello, artist! Let's make some fun captions for your pictures. Here's how:
490
+
491
+ 1. **Pick a Picture**: Find a cool picture you want to talk about and upload it.
492
+
493
+ 2. **Choose What You Want**:
494
+ - **Caption Type**:
495
+ * "Descriptive" tells you what's in the picture
496
+ * "Training Prompt" helps computers make similar pictures
497
+ * "RNG-Tags" gives you short words about the picture
498
+ * "Style Prompt" creates detailed prompts for image generation
499
+
500
+ 3. **Pick a Style** (for "Descriptive" and "Style Prompt" only):
501
+ - "Formal" sounds like a teacher talking
502
+ - "Informal" sounds like a friend chatting
503
+
504
+ 4. **Decide How Long**:
505
+ - "Any" lets the computer decide
506
+ - Or pick a size from "very short" to "very long"
507
+ - You can even choose a specific number of words!
508
+
509
+ 5. **Advanced Options** (for "Style Prompt" only):
510
+ - Choose lens type, film stock, composition, and lighting details
511
+
512
+ 6. **Make the Caption**: Click the "Make My Caption!" button and watch the magic happen!
513
+
514
+ Remember, have fun and be creative with your captions!
515
+
516
+ ## Tips for Great Captions:
517
+ - Try different types to see what you like best
518
+ - Experiment with formal and informal tones for fun variations
519
+ - Adjust the length to get just the right amount of detail
520
+ - For "Style Prompt", play with the advanced options for more specific results
521
+ - If you don't like a caption, just click "Make My Caption!" again for a new one
522
+
523
+ Have a great time captioning your art!
524
+ """)
525
+
526
+ with gr.Row():
527
+ with gr.Column():
528
+ input_image = gr.Image(type="pil", label="Input Image")
529
+
530
+ caption_type = gr.Dropdown(
531
+ choices=["Descriptive", "Descriptive (Informal)", "Training Prompt", "MidJourney", "Booru tag list", "Booru-like tag list", "Art Critic", "Product Listing", "Social Media Post", "Style Prompt"],
532
+ label="Caption Type",
533
+ value="Descriptive",
534
+ )
535
+
536
+ caption_length = gr.Dropdown(
537
+ choices=["any", "very short", "short", "medium-length", "long", "very long"] +
538
+ [str(i) for i in range(20, 261, 10)],
539
+ label="Caption Length",
540
+ value="long",
541
+ )
542
+
543
+ extra_options = gr.CheckboxGroup(
544
+ choices=[
545
+ "If there is a person/character in the image you must refer to them as {name}.",
546
+ "Do NOT include information about people/characters that cannot be changed (like ethnicity, gender, etc), but do still include changeable attributes (like hair style).",
547
+ "Include information about lighting.",
548
+ "Include information about camera angle.",
549
+ "Include information about whether there is a watermark or not.",
550
+ "Include information about whether there are JPEG artifacts or not.",
551
+ "If it is a photo you MUST include information about what camera was likely used and details such as aperture, shutter speed, ISO, etc.",
552
+ "Do NOT include anything sexual; keep it PG.",
553
+ "Do NOT mention the image's resolution.",
554
+ "You MUST include information about the subjective aesthetic quality of the image from low to very high.",
555
+ "Include information on the image's composition style, such as leading lines, rule of thirds, or symmetry.",
556
+ "Do NOT mention any text that is in the image.",
557
+ "Specify the depth of field and whether the background is in focus or blurred.",
558
+ "If applicable, mention the likely use of artificial or natural lighting sources.",
559
+ "Do NOT use any ambiguous language.",
560
+ "Include whether the image is sfw, suggestive, or nsfw.",
561
+ "ONLY describe the most important elements of the image."
562
+ ],
563
+ label="Extra Options"
564
+ )
565
+
566
+ name_input = gr.Textbox(label="Person/Character Name (if applicable)")
567
+ gr.Markdown("**Note:** Name input is only used if an Extra Option is selected that requires it.")
568
+
569
+ custom_prompt = gr.Textbox(label="Custom Prompt (optional, will override all other settings)")
570
+ gr.Markdown("**Note:** Alpha Two is not a general instruction follower and will not follow prompts outside its training data well. Use this feature with caution.")
571
+
572
+ # Container for advanced options
573
+ with gr.Column(visible=False) as advanced_options:
574
+ gr.Markdown("### Advanced Options for Style Prompt")
575
+ lens_type = gr.Dropdown(
576
+ choices=get_dropdown_choices(lens_types_info),
577
+ label="Lens Type",
578
+ info="Select a lens type to define the perspective and field of view of the image."
579
+ )
580
+ film_stock = gr.Dropdown(
581
+ choices=get_dropdown_choices(film_stocks_info),
582
+ label="Film Stock",
583
+ info="Choose a film stock to determine the color, grain, and overall look of the image."
584
+ )
585
+ composition_style = gr.Dropdown(
586
+ choices=get_dropdown_choices(composition_styles_info),
587
+ label="Composition Style",
588
+ info="Select a composition style to guide the arrangement of elements in the image."
589
+ )
590
+ lighting_aspect = gr.Dropdown(
591
+ choices=get_dropdown_choices(lighting_aspects_info),
592
+ label="Lighting Aspect",
593
+ info="Choose a lighting style to define the mood and atmosphere of the image."
594
+ )
595
+ special_technique = gr.Dropdown(
596
+ choices=get_dropdown_choices(special_techniques_info),
597
+ label="Special Technique",
598
+ info="Select a special photographic technique to add unique effects to the image."
599
+ )
600
+ color_effect = gr.Dropdown(
601
+ choices=get_dropdown_choices(color_effects_info),
602
+ label="Color Effect",
603
+ info="Choose a color effect to alter the overall color palette of the image."
604
+ )
605
+
606
+ run_button = gr.Button("Make My Caption!")
607
+
608
+ with gr.Column():
609
+ error_message = gr.Markdown(visible=False)
610
+ output_prompt = gr.Textbox(label="Prompt that was used")
611
+ output_caption = gr.Textbox(label="Generated Caption")
612
+
613
+ def update_style_options(caption_type):
614
+ return gr.update(visible=caption_type == "Style Prompt")
615
+
616
+ caption_type.change(update_style_options, inputs=[caption_type], outputs=[advanced_options])
617
+
618
+ def process_and_handle_errors(input_image, caption_type, caption_length, extra_options, name_input, custom_prompt, lens_type, film_stock, composition_style, lighting_aspect, special_technique, color_effect):
619
+ try:
620
+ prompt, result = stream_chat(input_image, caption_type, caption_length, extra_options, name_input, custom_prompt, lens_type, film_stock, composition_style, lighting_aspect, special_technique, color_effect)
621
+ return gr.update(visible=False), prompt, result
622
+ except Exception as e:
623
+ return gr.update(visible=True, value=f"Error: {str(e)}"), "", ""
624
+
625
+ run_button.click(
626
+ fn=process_and_handle_errors,
627
+ inputs=[input_image, caption_type, caption_length, extra_options, name_input, custom_prompt, lens_type, film_stock, composition_style, lighting_aspect, special_technique, color_effect],
628
+ outputs=[error_message, output_prompt, output_caption]
629
+ )
630
+
631
+ login_button.click(
632
+ login,
633
+ inputs=[username, password],
634
+ outputs=[caption_captain_tab, username, password, login_message]
635
+ )
636
 
637
  if __name__ == "__main__":
638
  demo.launch()