Update app.py
Browse filesdark_mode_4bit_gui
app.py
CHANGED
@@ -1,336 +1,871 @@
|
|
1 |
-
#
|
2 |
-
import
|
3 |
-
|
4 |
-
from torch import nn
|
5 |
-
from transformers import AutoModel, AutoProcessor, AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast, AutoModelForCausalLM
|
6 |
-
from pathlib import Path
|
7 |
import torch
|
8 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
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 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
}
|
64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
HF_TOKEN = os.environ.get("HF_TOKEN", None)
|
66 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
class ImageAdapter(nn.Module):
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
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 |
-
|
|
|
|
|
|
|
|
1 |
+
#dark_mode_4bit_gui
|
2 |
+
import sys
|
3 |
+
import os
|
|
|
|
|
|
|
4 |
import torch
|
5 |
+
from torch import nn
|
6 |
+
from transformers import (
|
7 |
+
AutoModel,
|
8 |
+
AutoProcessor,
|
9 |
+
AutoTokenizer,
|
10 |
+
PreTrainedTokenizer,
|
11 |
+
PreTrainedTokenizerFast,
|
12 |
+
AutoModelForCausalLM,
|
13 |
+
BitsAndBytesConfig,
|
14 |
+
)
|
15 |
from PIL import Image
|
|
|
16 |
import torchvision.transforms.functional as TVF
|
17 |
+
import contextlib
|
18 |
+
from typing import Union, List
|
19 |
+
from pathlib import Path
|
20 |
|
21 |
+
from PyQt5.QtWidgets import (
|
22 |
+
QApplication,
|
23 |
+
QWidget,
|
24 |
+
QLabel,
|
25 |
+
QPushButton,
|
26 |
+
QFileDialog,
|
27 |
+
QLineEdit,
|
28 |
+
QTextEdit,
|
29 |
+
QComboBox,
|
30 |
+
QVBoxLayout,
|
31 |
+
QHBoxLayout,
|
32 |
+
QCheckBox,
|
33 |
+
QListWidget,
|
34 |
+
QListWidgetItem,
|
35 |
+
QMessageBox,
|
36 |
+
QSizePolicy,
|
37 |
+
)
|
38 |
+
from PyQt5.QtGui import QPixmap, QIcon
|
39 |
+
from PyQt5.QtCore import Qt
|
40 |
+
|
41 |
+
# Constants and Mappings
|
42 |
CLIP_PATH = "google/siglip-so400m-patch14-384"
|
|
|
|
|
43 |
CAPTION_TYPE_MAP = {
|
44 |
+
"Descriptive": [
|
45 |
+
"Write a descriptive caption for this image in a formal tone.",
|
46 |
+
"Write a descriptive caption for this image in a formal tone within {word_count} words.",
|
47 |
+
"Write a {length} descriptive caption for this image in a formal tone.",
|
48 |
+
],
|
49 |
+
"Descriptive (Informal)": [
|
50 |
+
"Write a descriptive caption for this image in a casual tone.",
|
51 |
+
"Write a descriptive caption for this image in a casual tone within {word_count} words.",
|
52 |
+
"Write a {length} descriptive caption for this image in a casual tone.",
|
53 |
+
],
|
54 |
+
"Training Prompt": [
|
55 |
+
"Write a stable diffusion prompt for this image.",
|
56 |
+
"Write a stable diffusion prompt for this image within {word_count} words.",
|
57 |
+
"Write a {length} stable diffusion prompt for this image.",
|
58 |
+
],
|
59 |
+
"MidJourney": [
|
60 |
+
"Write a MidJourney prompt for this image.",
|
61 |
+
"Write a MidJourney prompt for this image within {word_count} words.",
|
62 |
+
"Write a {length} MidJourney prompt for this image.",
|
63 |
+
],
|
64 |
+
"Booru tag list": [
|
65 |
+
"Write a list of Booru tags for this image.",
|
66 |
+
"Write a list of Booru tags for this image within {word_count} words.",
|
67 |
+
"Write a {length} list of Booru tags for this image.",
|
68 |
+
],
|
69 |
+
"Booru-like tag list": [
|
70 |
+
"Write a list of Booru-like tags for this image.",
|
71 |
+
"Write a list of Booru-like tags for this image within {word_count} words.",
|
72 |
+
"Write a {length} list of Booru-like tags for this image.",
|
73 |
+
],
|
74 |
+
"Art Critic": [
|
75 |
+
"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.",
|
76 |
+
"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.",
|
77 |
+
"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}.",
|
78 |
+
],
|
79 |
+
"Product Listing": [
|
80 |
+
"Write a caption for this image as though it were a product listing.",
|
81 |
+
"Write a caption for this image as though it were a product listing. Keep it under {word_count} words.",
|
82 |
+
"Write a {length} caption for this image as though it were a product listing.",
|
83 |
+
],
|
84 |
+
"Social Media Post": [
|
85 |
+
"Write a caption for this image as if it were being used for a social media post.",
|
86 |
+
"Write a caption for this image as if it were being used for a social media post. Limit the caption to {word_count} words.",
|
87 |
+
"Write a {length} caption for this image as if it were being used for a social media post.",
|
88 |
+
],
|
89 |
}
|
90 |
|
91 |
+
EXTRA_OPTIONS_LIST = [
|
92 |
+
"If there is a person/character in the image you must refer to them as {name}.",
|
93 |
+
"Do NOT include information about people/characters that cannot be changed (like ethnicity, gender, etc), but do still include changeable attributes (like hair style).",
|
94 |
+
"Include information about lighting.",
|
95 |
+
"Include information about camera angle.",
|
96 |
+
"Include information about whether there is a watermark or not.",
|
97 |
+
"Include information about whether there are JPEG artifacts or not.",
|
98 |
+
"If it is a photo you MUST include information about what camera was likely used and details such as aperture, shutter speed, ISO, etc.",
|
99 |
+
"Do NOT include anything sexual; keep it PG.",
|
100 |
+
"Do NOT mention the image's resolution.",
|
101 |
+
"You MUST include information about the subjective aesthetic quality of the image from low to very high.",
|
102 |
+
"Include information on the image's composition style, such as leading lines, rule of thirds, or symmetry.",
|
103 |
+
"Do NOT mention any text that is in the image.",
|
104 |
+
"Specify the depth of field and whether the background is in focus or blurred.",
|
105 |
+
"If applicable, mention the likely use of artificial or natural lighting sources.",
|
106 |
+
"Do NOT use any ambiguous language.",
|
107 |
+
"Include whether the image is sfw, suggestive, or nsfw.",
|
108 |
+
"ONLY describe the most important elements of the image.",
|
109 |
+
]
|
110 |
+
|
111 |
+
CAPTION_LENGTH_CHOICES = (
|
112 |
+
["any", "very short", "short", "medium-length", "long", "very long"]
|
113 |
+
+ [str(i) for i in range(20, 261, 10)]
|
114 |
+
)
|
115 |
+
|
116 |
HF_TOKEN = os.environ.get("HF_TOKEN", None)
|
117 |
|
118 |
+
# Determine the device to use (GPU if available, else CPU)
|
119 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
120 |
+
if device.type == "cuda":
|
121 |
+
torch_dtype = torch.bfloat16 # or torch.float16 based on compatibility
|
122 |
+
else:
|
123 |
+
torch_dtype = torch.float32
|
124 |
+
|
125 |
+
# Update autocast usage
|
126 |
+
if device.type == "cuda":
|
127 |
+
autocast = lambda: torch.amp.autocast(device_type='cuda', dtype=torch_dtype)
|
128 |
+
else:
|
129 |
+
autocast = contextlib.nullcontext # No autocasting on CPU
|
130 |
|
131 |
class ImageAdapter(nn.Module):
|
132 |
+
def __init__(
|
133 |
+
self,
|
134 |
+
input_features: int,
|
135 |
+
output_features: int,
|
136 |
+
ln1: bool,
|
137 |
+
pos_emb: bool,
|
138 |
+
num_image_tokens: int,
|
139 |
+
deep_extract: bool,
|
140 |
+
):
|
141 |
+
super().__init__()
|
142 |
+
self.deep_extract = deep_extract
|
143 |
+
|
144 |
+
if self.deep_extract:
|
145 |
+
input_features = input_features * 5
|
146 |
+
|
147 |
+
self.linear1 = nn.Linear(input_features, output_features)
|
148 |
+
self.activation = nn.GELU()
|
149 |
+
self.linear2 = nn.Linear(output_features, output_features)
|
150 |
+
self.ln1 = nn.Identity() if not ln1 else nn.LayerNorm(input_features)
|
151 |
+
self.pos_emb = (
|
152 |
+
None if not pos_emb else nn.Parameter(torch.zeros(num_image_tokens, input_features))
|
153 |
+
)
|
154 |
+
|
155 |
+
# Other tokens (<|image_start|>, <|image_end|>, <|eot_id|>)
|
156 |
+
self.other_tokens = nn.Embedding(3, output_features)
|
157 |
+
self.other_tokens.weight.data.normal_(
|
158 |
+
mean=0.0, std=0.02
|
159 |
+
) # Matches HF's implementation of llama3
|
160 |
+
|
161 |
+
def forward(self, vision_outputs: torch.Tensor):
|
162 |
+
if self.deep_extract:
|
163 |
+
x = torch.concat(
|
164 |
+
(
|
165 |
+
vision_outputs[-2],
|
166 |
+
vision_outputs[3],
|
167 |
+
vision_outputs[7],
|
168 |
+
vision_outputs[13],
|
169 |
+
vision_outputs[20],
|
170 |
+
),
|
171 |
+
dim=-1,
|
172 |
+
)
|
173 |
+
assert len(x.shape) == 3, f"Expected 3, got {len(x.shape)}" # batch, tokens, features
|
174 |
+
assert (
|
175 |
+
x.shape[-1] == vision_outputs[-2].shape[-1] * 5
|
176 |
+
), f"Expected {vision_outputs[-2].shape[-1] * 5}, got {x.shape[-1]}"
|
177 |
+
else:
|
178 |
+
x = vision_outputs[-2]
|
179 |
+
|
180 |
+
x = self.ln1(x)
|
181 |
+
|
182 |
+
if self.pos_emb is not None:
|
183 |
+
assert x.shape[-2:] == self.pos_emb.shape, f"Expected {self.pos_emb.shape}, got {x.shape[-2:]}"
|
184 |
+
x = x + self.pos_emb
|
185 |
+
|
186 |
+
x = self.linear1(x)
|
187 |
+
x = self.activation(x)
|
188 |
+
x = self.linear2(x)
|
189 |
+
|
190 |
+
# <|image_start|>, IMAGE, <|image_end|>
|
191 |
+
other_tokens = self.other_tokens(
|
192 |
+
torch.tensor([0, 1], device=self.other_tokens.weight.device).expand(x.shape[0], -1)
|
193 |
+
)
|
194 |
+
assert other_tokens.shape == (
|
195 |
+
x.shape[0],
|
196 |
+
2,
|
197 |
+
x.shape[2],
|
198 |
+
), f"Expected {(x.shape[0], 2, x.shape[2])}, got {other_tokens.shape}"
|
199 |
+
x = torch.cat((other_tokens[:, 0:1], x, other_tokens[:, 1:2]), dim=1)
|
200 |
+
|
201 |
+
return x
|
202 |
+
|
203 |
+
def get_eot_embedding(self):
|
204 |
+
return self.other_tokens(torch.tensor([2], device=self.other_tokens.weight.device)).squeeze(0)
|
205 |
+
|
206 |
+
def load_models(CHECKPOINT_PATH):
|
207 |
+
# Load CLIP
|
208 |
+
print("Loading CLIP")
|
209 |
+
clip_processor = AutoProcessor.from_pretrained(CLIP_PATH)
|
210 |
+
clip_model = AutoModel.from_pretrained(CLIP_PATH)
|
211 |
+
clip_model = clip_model.vision_model
|
212 |
+
|
213 |
+
assert (
|
214 |
+
CHECKPOINT_PATH / "clip_model.pt"
|
215 |
+
).exists(), f"clip_model.pt not found in {CHECKPOINT_PATH}"
|
216 |
+
print("Loading VLM's custom vision model")
|
217 |
+
checkpoint = torch.load(CHECKPOINT_PATH / "clip_model.pt", map_location="cpu")
|
218 |
+
checkpoint = {k.replace("_orig_mod.module.", ""): v for k, v in checkpoint.items()}
|
219 |
+
clip_model.load_state_dict(checkpoint)
|
220 |
+
del checkpoint
|
221 |
+
|
222 |
+
clip_model.eval()
|
223 |
+
clip_model.requires_grad_(False)
|
224 |
+
clip_model.to(device)
|
225 |
+
|
226 |
+
# Tokenizer
|
227 |
+
print("Loading tokenizer")
|
228 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
229 |
+
CHECKPOINT_PATH / "text_model", use_fast=True
|
230 |
+
)
|
231 |
+
assert isinstance(tokenizer, (PreTrainedTokenizer, PreTrainedTokenizerFast)), f"Tokenizer is of type {type(tokenizer)}"
|
232 |
+
|
233 |
+
# Add special tokens to the tokenizer
|
234 |
+
special_tokens_dict = {'additional_special_tokens': ['<|system|>', '<|user|>', '<|end|>', '<|eot_id|>']}
|
235 |
+
num_added_toks = tokenizer.add_special_tokens(special_tokens_dict)
|
236 |
+
print(f"Added {num_added_toks} special tokens.")
|
237 |
+
|
238 |
+
# LLM with 4-bit quantization
|
239 |
+
print("Loading LLM with 4-bit quantization")
|
240 |
+
text_model = AutoModelForCausalLM.from_pretrained(
|
241 |
+
CHECKPOINT_PATH / "text_model",
|
242 |
+
device_map="auto",
|
243 |
+
quantization_config=BitsAndBytesConfig(
|
244 |
+
load_in_4bit=True,
|
245 |
+
bnb_4bit_use_double_quant=True,
|
246 |
+
bnb_4bit_quant_type='nf4',
|
247 |
+
bnb_4bit_compute_dtype=torch.float16
|
248 |
+
)
|
249 |
+
)
|
250 |
+
text_model.eval()
|
251 |
+
# Removed text_model.to(device)
|
252 |
+
|
253 |
+
# Resize token embeddings if new tokens were added
|
254 |
+
if num_added_toks > 0:
|
255 |
+
text_model.resize_token_embeddings(len(tokenizer))
|
256 |
+
|
257 |
+
# Image Adapter
|
258 |
+
print("Loading image adapter")
|
259 |
+
image_adapter = ImageAdapter(
|
260 |
+
clip_model.config.hidden_size, text_model.config.hidden_size, False, False, 38, False
|
261 |
+
)
|
262 |
+
image_adapter.load_state_dict(
|
263 |
+
torch.load(CHECKPOINT_PATH / "image_adapter.pt", map_location="cpu")
|
264 |
+
)
|
265 |
+
image_adapter.eval()
|
266 |
+
image_adapter.to(device) # image_adapter is not quantized, so it's okay
|
267 |
+
|
268 |
+
return clip_processor, clip_model, tokenizer, text_model, image_adapter
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
269 |
|
270 |
+
@torch.no_grad()
|
271 |
+
def generate_caption(
|
272 |
+
input_image: Image.Image,
|
273 |
+
caption_type: str,
|
274 |
+
caption_length: Union[str, int],
|
275 |
+
extra_options: List[str],
|
276 |
+
name_input: str,
|
277 |
+
custom_prompt: str,
|
278 |
+
clip_model,
|
279 |
+
tokenizer,
|
280 |
+
text_model,
|
281 |
+
image_adapter,
|
282 |
+
) -> tuple:
|
283 |
+
if device.type == "cuda":
|
284 |
+
torch.cuda.empty_cache()
|
285 |
+
|
286 |
+
# If a custom prompt is provided, use it directly
|
287 |
+
if custom_prompt.strip() != "":
|
288 |
+
prompt_str = custom_prompt.strip()
|
289 |
+
else:
|
290 |
+
# 'any' means no length specified
|
291 |
+
length = None if caption_length == "any" else caption_length
|
292 |
+
|
293 |
+
if isinstance(length, str):
|
294 |
+
try:
|
295 |
+
length = int(length)
|
296 |
+
except ValueError:
|
297 |
+
pass
|
298 |
+
|
299 |
+
# Build prompt
|
300 |
+
if length is None:
|
301 |
+
map_idx = 0
|
302 |
+
elif isinstance(length, int):
|
303 |
+
map_idx = 1
|
304 |
+
elif isinstance(length, str):
|
305 |
+
map_idx = 2
|
306 |
+
else:
|
307 |
+
raise ValueError(f"Invalid caption length: {length}")
|
308 |
+
|
309 |
+
prompt_str = CAPTION_TYPE_MAP[caption_type][map_idx]
|
310 |
+
|
311 |
+
# Add extra options
|
312 |
+
if len(extra_options) > 0:
|
313 |
+
prompt_str += " " + " ".join(extra_options)
|
314 |
+
|
315 |
+
# Add name, length, word_count
|
316 |
+
prompt_str = prompt_str.format(name=name_input, length=caption_length, word_count=caption_length)
|
317 |
+
|
318 |
+
# For debugging
|
319 |
+
print(f"Prompt: {prompt_str}")
|
320 |
+
|
321 |
+
# Preprocess image
|
322 |
+
image = input_image.resize((384, 384), Image.LANCZOS)
|
323 |
+
pixel_values = TVF.pil_to_tensor(image).unsqueeze(0) / 255.0
|
324 |
+
pixel_values = TVF.normalize(pixel_values, [0.5], [0.5])
|
325 |
+
pixel_values = pixel_values.to(device)
|
326 |
+
|
327 |
+
# Embed image
|
328 |
+
# This results in Batch x Image Tokens x Features
|
329 |
+
with autocast():
|
330 |
+
vision_outputs = clip_model(pixel_values=pixel_values, output_hidden_states=True)
|
331 |
+
embedded_images = image_adapter(vision_outputs.hidden_states)
|
332 |
+
embedded_images = embedded_images.to(device)
|
333 |
+
|
334 |
+
# Build the conversation
|
335 |
+
convo = [
|
336 |
+
{
|
337 |
+
"role": "system",
|
338 |
+
"content": "You are a helpful image captioner.",
|
339 |
+
},
|
340 |
+
{
|
341 |
+
"role": "user",
|
342 |
+
"content": prompt_str,
|
343 |
+
},
|
344 |
+
]
|
345 |
+
|
346 |
+
# Format the conversation
|
347 |
+
# The apply_chat_template method might not be available; handle accordingly
|
348 |
+
if hasattr(tokenizer, "apply_chat_template"):
|
349 |
+
convo_string = tokenizer.apply_chat_template(
|
350 |
+
convo, tokenize=False, add_generation_prompt=True
|
351 |
+
)
|
352 |
+
else:
|
353 |
+
# Simple concatenation if apply_chat_template is not available
|
354 |
+
convo_string = (
|
355 |
+
"<|system|>\n" + convo[0]["content"] + "\n<|end|>\n<|user|>\n" + convo[1]["content"] + "\n<|end|>\n"
|
356 |
+
)
|
357 |
+
|
358 |
+
assert isinstance(convo_string, str)
|
359 |
+
|
360 |
+
# Tokenize the conversation
|
361 |
+
# prompt_str is tokenized separately so we can do the calculations below
|
362 |
+
convo_tokens = tokenizer.encode(
|
363 |
+
convo_string, return_tensors="pt", add_special_tokens=False, truncation=False
|
364 |
+
).to(device)
|
365 |
+
prompt_tokens = tokenizer.encode(
|
366 |
+
prompt_str, return_tensors="pt", add_special_tokens=False, truncation=False
|
367 |
+
).to(device)
|
368 |
+
assert isinstance(convo_tokens, torch.Tensor) and isinstance(prompt_tokens, torch.Tensor)
|
369 |
+
convo_tokens = convo_tokens.squeeze(0) # Squeeze just to make the following easier
|
370 |
+
prompt_tokens = prompt_tokens.squeeze(0)
|
371 |
+
|
372 |
+
# Calculate where to inject the image
|
373 |
+
# Use the indices of the special tokens
|
374 |
+
end_token_id = tokenizer.convert_tokens_to_ids("<|end|>")
|
375 |
+
|
376 |
+
# Ensure end_token_id is valid
|
377 |
+
if end_token_id is None:
|
378 |
+
raise ValueError("The tokenizer does not recognize the '<|end|>' token. Please ensure special tokens are added.")
|
379 |
+
|
380 |
+
end_token_indices = (convo_tokens == end_token_id).nonzero(as_tuple=True)[0].tolist()
|
381 |
+
if len(end_token_indices) >= 2:
|
382 |
+
# The image is to be injected between the system message and the user prompt
|
383 |
+
preamble_len = end_token_indices[0] + 1 # Position after the first <|end|>
|
384 |
+
else:
|
385 |
+
preamble_len = 0 # Fallback to the start if tokens are missing
|
386 |
+
|
387 |
+
# Embed the tokens
|
388 |
+
convo_embeds = text_model.model.embed_tokens(convo_tokens.unsqueeze(0).to(device))
|
389 |
+
|
390 |
+
# Construct the input
|
391 |
+
input_embeds = torch.cat(
|
392 |
+
[
|
393 |
+
convo_embeds[:, :preamble_len], # Part before the prompt
|
394 |
+
embedded_images.to(dtype=convo_embeds.dtype), # Image embeddings
|
395 |
+
convo_embeds[:, preamble_len:], # The prompt and anything after it
|
396 |
+
],
|
397 |
+
dim=1,
|
398 |
+
).to(device)
|
399 |
+
|
400 |
+
input_ids = torch.cat(
|
401 |
+
[
|
402 |
+
convo_tokens[:preamble_len].unsqueeze(0),
|
403 |
+
torch.full((1, embedded_images.shape[1]), tokenizer.pad_token_id, dtype=torch.long, device=device), # Dummy tokens for the image
|
404 |
+
convo_tokens[preamble_len:].unsqueeze(0),
|
405 |
+
],
|
406 |
+
dim=1,
|
407 |
+
).to(device)
|
408 |
+
attention_mask = torch.ones_like(input_ids).to(device)
|
409 |
+
|
410 |
+
# Debugging
|
411 |
+
print(f"Input to model: {repr(tokenizer.decode(input_ids[0]))}")
|
412 |
+
|
413 |
+
# Generate the caption
|
414 |
+
generate_ids = text_model.generate(
|
415 |
+
input_ids=input_ids,
|
416 |
+
inputs_embeds=input_embeds,
|
417 |
+
attention_mask=attention_mask,
|
418 |
+
max_new_tokens=300,
|
419 |
+
do_sample=True,
|
420 |
+
temperature=0.6,
|
421 |
+
top_p=0.9,
|
422 |
+
suppress_tokens=None,
|
423 |
+
)
|
424 |
+
|
425 |
+
# Trim off the prompt
|
426 |
+
generate_ids = generate_ids[:, input_ids.shape[1]:]
|
427 |
+
if generate_ids[0][-1] in [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids("<|end|>")]:
|
428 |
+
generate_ids = generate_ids[:, :-1]
|
429 |
+
|
430 |
+
caption = tokenizer.batch_decode(
|
431 |
+
generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
432 |
+
)[0]
|
433 |
+
|
434 |
+
return prompt_str, caption.strip()
|
435 |
+
|
436 |
+
class CaptionApp(QWidget):
|
437 |
+
def __init__(self):
|
438 |
+
super().__init__()
|
439 |
+
self.setWindowTitle("JoyCaption Alpha Two")
|
440 |
+
self.setGeometry(100, 100, 1200, 800)
|
441 |
+
|
442 |
+
# Set minimum size to maintain GUI consistency
|
443 |
+
self.setMinimumSize(1000, 700)
|
444 |
+
|
445 |
+
self.initUI()
|
446 |
+
|
447 |
+
# Initialize model variables
|
448 |
+
self.clip_processor = None
|
449 |
+
self.clip_model = None
|
450 |
+
self.tokenizer = None
|
451 |
+
self.text_model = None
|
452 |
+
self.image_adapter = None
|
453 |
+
|
454 |
+
# Initialize variables for selected images
|
455 |
+
self.input_dir = None
|
456 |
+
self.single_image_path = None
|
457 |
+
self.selected_image_path = None
|
458 |
+
|
459 |
+
# Theme variables
|
460 |
+
self.dark_mode = False
|
461 |
+
|
462 |
+
def initUI(self):
|
463 |
+
main_layout = QHBoxLayout()
|
464 |
+
|
465 |
+
# Left panel for parameters
|
466 |
+
left_panel = QVBoxLayout()
|
467 |
+
|
468 |
+
# Input directory selection
|
469 |
+
self.input_dir_button = QPushButton("Select Input Directory")
|
470 |
+
self.input_dir_button.clicked.connect(self.select_input_directory)
|
471 |
+
self.input_dir_label = QLabel("No directory selected")
|
472 |
+
left_panel.addWidget(self.input_dir_button)
|
473 |
+
left_panel.addWidget(self.input_dir_label)
|
474 |
+
|
475 |
+
# Single image selection
|
476 |
+
self.single_image_button = QPushButton("Select Single Image")
|
477 |
+
self.single_image_button.clicked.connect(self.select_single_image)
|
478 |
+
self.single_image_label = QLabel("No image selected")
|
479 |
+
left_panel.addWidget(self.single_image_button)
|
480 |
+
left_panel.addWidget(self.single_image_label)
|
481 |
+
|
482 |
+
# Caption Type
|
483 |
+
self.caption_type_combo = QComboBox()
|
484 |
+
self.caption_type_combo.addItems(CAPTION_TYPE_MAP.keys())
|
485 |
+
self.caption_type_combo.setCurrentText("Descriptive")
|
486 |
+
left_panel.addWidget(QLabel("Caption Type:"))
|
487 |
+
left_panel.addWidget(self.caption_type_combo)
|
488 |
+
|
489 |
+
# Caption Length
|
490 |
+
self.caption_length_combo = QComboBox()
|
491 |
+
self.caption_length_combo.addItems(CAPTION_LENGTH_CHOICES)
|
492 |
+
self.caption_length_combo.setCurrentText("long")
|
493 |
+
left_panel.addWidget(QLabel("Caption Length:"))
|
494 |
+
left_panel.addWidget(self.caption_length_combo)
|
495 |
+
|
496 |
+
# Extra Options
|
497 |
+
left_panel.addWidget(QLabel("Extra Options:"))
|
498 |
+
self.extra_options_checkboxes = []
|
499 |
+
for option in EXTRA_OPTIONS_LIST:
|
500 |
+
checkbox = QCheckBox(option)
|
501 |
+
self.extra_options_checkboxes.append(checkbox)
|
502 |
+
left_panel.addWidget(checkbox)
|
503 |
+
|
504 |
+
# Name Input
|
505 |
+
self.name_input_line = QLineEdit()
|
506 |
+
left_panel.addWidget(QLabel("Person/Character Name (if applicable):"))
|
507 |
+
left_panel.addWidget(self.name_input_line)
|
508 |
+
|
509 |
+
# Custom Prompt
|
510 |
+
self.custom_prompt_text = QTextEdit()
|
511 |
+
left_panel.addWidget(QLabel("Custom Prompt (optional):"))
|
512 |
+
left_panel.addWidget(self.custom_prompt_text)
|
513 |
+
|
514 |
+
# Checkpoint Path
|
515 |
+
self.checkpoint_path_line = QLineEdit()
|
516 |
+
self.checkpoint_path_line.setText("cgrkzexw-599808") # Update this path accordingly
|
517 |
+
left_panel.addWidget(QLabel("Checkpoint Path:"))
|
518 |
+
left_panel.addWidget(self.checkpoint_path_line)
|
519 |
+
|
520 |
+
# Load Models Button
|
521 |
+
self.load_models_button = QPushButton("Load Models")
|
522 |
+
self.load_models_button.clicked.connect(self.load_models)
|
523 |
+
left_panel.addWidget(self.load_models_button)
|
524 |
+
|
525 |
+
# Run Buttons
|
526 |
+
self.run_button = QPushButton("Generate Captions for All Images")
|
527 |
+
self.run_button.clicked.connect(self.generate_captions)
|
528 |
+
left_panel.addWidget(self.run_button)
|
529 |
+
|
530 |
+
self.caption_selected_button = QPushButton("Caption Selected Image")
|
531 |
+
self.caption_selected_button.clicked.connect(self.caption_selected_image)
|
532 |
+
self.caption_selected_button.setEnabled(False) # Disabled until an image is selected
|
533 |
+
left_panel.addWidget(self.caption_selected_button)
|
534 |
+
|
535 |
+
self.caption_single_button = QPushButton("Caption Single Image")
|
536 |
+
self.caption_single_button.clicked.connect(self.caption_single_image)
|
537 |
+
self.caption_single_button.setEnabled(False) # Disabled until a single image is selected
|
538 |
+
left_panel.addWidget(self.caption_single_button)
|
539 |
+
|
540 |
+
# Theme Toggle Button
|
541 |
+
self.toggle_theme_button = QPushButton("Toggle Dark Mode")
|
542 |
+
self.toggle_theme_button.clicked.connect(self.toggle_theme)
|
543 |
+
left_panel.addWidget(self.toggle_theme_button)
|
544 |
+
|
545 |
+
# Right panel for image display and captions
|
546 |
+
right_panel = QVBoxLayout()
|
547 |
+
|
548 |
+
# List widget for images
|
549 |
+
self.image_list_widget = QListWidget()
|
550 |
+
self.image_list_widget.itemClicked.connect(self.display_selected_image)
|
551 |
+
right_panel.addWidget(QLabel("Images:"))
|
552 |
+
right_panel.addWidget(self.image_list_widget)
|
553 |
+
|
554 |
+
# Label to display the selected image
|
555 |
+
self.selected_image_label = QLabel()
|
556 |
+
self.selected_image_label.setAlignment(Qt.AlignCenter)
|
557 |
+
|
558 |
+
# Set size policy to expanding to utilize available space
|
559 |
+
self.selected_image_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
|
560 |
+
self.selected_image_label.setMinimumSize(400, 400) # Set a reasonable minimum size
|
561 |
+
|
562 |
+
right_panel.addWidget(QLabel("Selected Image:"))
|
563 |
+
right_panel.addWidget(self.selected_image_label)
|
564 |
+
|
565 |
+
# Adjust stretch factors to allocate more space to the image label
|
566 |
+
main_layout.addLayout(left_panel, 2)
|
567 |
+
main_layout.addLayout(right_panel, 5) # Increased stretch factor for right_panel
|
568 |
+
self.setLayout(main_layout)
|
569 |
+
|
570 |
+
def toggle_theme(self):
|
571 |
+
if self.dark_mode:
|
572 |
+
self.setStyleSheet("") # Reset to default
|
573 |
+
self.dark_mode = False
|
574 |
+
else:
|
575 |
+
# Apply dark theme stylesheet with adjusted properties
|
576 |
+
self.setStyleSheet("""
|
577 |
+
QWidget {
|
578 |
+
background-color: #2E2E2E;
|
579 |
+
color: #FFFFFF;
|
580 |
+
font-family: Arial, sans-serif;
|
581 |
+
/* Removed font-size to prevent resizing */
|
582 |
+
}
|
583 |
+
QPushButton {
|
584 |
+
background-color: #3A3A3A;
|
585 |
+
color: #FFFFFF;
|
586 |
+
border: none;
|
587 |
+
padding: 5px; /* Keep padding minimal */
|
588 |
+
}
|
589 |
+
QPushButton:hover {
|
590 |
+
background-color: #555555;
|
591 |
+
}
|
592 |
+
QLabel {
|
593 |
+
color: #FFFFFF;
|
594 |
+
}
|
595 |
+
QLineEdit, QTextEdit, QComboBox {
|
596 |
+
background-color: #3A3A3A;
|
597 |
+
color: #FFFFFF;
|
598 |
+
border: 1px solid #555555;
|
599 |
+
padding: 5px; /* Keep padding minimal */
|
600 |
+
}
|
601 |
+
QListWidget {
|
602 |
+
background-color: #3A3A3A;
|
603 |
+
color: #FFFFFF;
|
604 |
+
border: 1px solid #555555;
|
605 |
+
}
|
606 |
+
QCheckBox {
|
607 |
+
color: #FFFFFF;
|
608 |
+
}
|
609 |
+
""")
|
610 |
+
self.dark_mode = True
|
611 |
+
|
612 |
+
def select_input_directory(self):
|
613 |
+
directory = QFileDialog.getExistingDirectory(self, "Select Input Directory")
|
614 |
+
if directory:
|
615 |
+
self.input_dir = Path(directory)
|
616 |
+
self.input_dir_label.setText(str(self.input_dir))
|
617 |
+
self.load_images()
|
618 |
+
else:
|
619 |
+
self.input_dir_label.setText("No directory selected")
|
620 |
+
self.input_dir = None
|
621 |
+
|
622 |
+
def select_single_image(self):
|
623 |
+
file_filter = "Image Files (*.jpg *.jpeg *.png *.bmp *.gif *.tiff)"
|
624 |
+
file_path, _ = QFileDialog.getOpenFileName(self, "Select Single Image", "", file_filter)
|
625 |
+
if file_path:
|
626 |
+
self.single_image_path = Path(file_path)
|
627 |
+
self.single_image_label.setText(str(self.single_image_path.name))
|
628 |
+
self.display_image(self.single_image_path)
|
629 |
+
self.caption_single_button.setEnabled(True)
|
630 |
+
else:
|
631 |
+
self.single_image_label.setText("No image selected")
|
632 |
+
self.single_image_path = None
|
633 |
+
self.caption_single_button.setEnabled(False)
|
634 |
+
|
635 |
+
def load_images(self):
|
636 |
+
# List of image file extensions
|
637 |
+
image_extensions = [".jpg", ".jpeg", ".png", ".bmp", ".gif", ".tiff"]
|
638 |
+
|
639 |
+
# Collect all image files in the directory
|
640 |
+
self.image_files = [f for f in self.input_dir.iterdir() if f.suffix.lower() in image_extensions]
|
641 |
+
|
642 |
+
if not self.image_files:
|
643 |
+
QMessageBox.warning(self, "No Images", "No image files found in the selected directory.")
|
644 |
+
return
|
645 |
+
|
646 |
+
self.image_list_widget.clear()
|
647 |
+
for image_path in self.image_files:
|
648 |
+
item = QListWidgetItem(str(image_path.name))
|
649 |
+
pixmap = QPixmap(str(image_path))
|
650 |
+
if not pixmap.isNull():
|
651 |
+
# Increase thumbnail size
|
652 |
+
scaled_pixmap = pixmap.scaled(150, 150, Qt.KeepAspectRatio, Qt.SmoothTransformation)
|
653 |
+
icon = QIcon(scaled_pixmap)
|
654 |
+
item.setIcon(icon)
|
655 |
+
self.image_list_widget.addItem(item)
|
656 |
+
|
657 |
+
def display_selected_image(self, item):
|
658 |
+
# Get the selected image path
|
659 |
+
image_name = item.text()
|
660 |
+
image_path = self.input_dir / image_name
|
661 |
+
pixmap = QPixmap(str(image_path))
|
662 |
+
if not pixmap.isNull():
|
663 |
+
# Scale the pixmap to fit the label while preserving aspect ratio
|
664 |
+
scaled_pixmap = pixmap.scaled(
|
665 |
+
self.selected_image_label.size(),
|
666 |
+
Qt.KeepAspectRatio,
|
667 |
+
Qt.SmoothTransformation
|
668 |
+
)
|
669 |
+
self.selected_image_label.setPixmap(scaled_pixmap)
|
670 |
+
self.caption_selected_button.setEnabled(True)
|
671 |
+
self.selected_image_path = image_path
|
672 |
+
else:
|
673 |
+
self.selected_image_label.clear()
|
674 |
+
self.caption_selected_button.setEnabled(False)
|
675 |
+
self.selected_image_path = None
|
676 |
+
|
677 |
+
def display_image(self, image_path):
|
678 |
+
pixmap = QPixmap(str(image_path))
|
679 |
+
if not pixmap.isNull():
|
680 |
+
# Scale the pixmap to fit the label while preserving aspect ratio
|
681 |
+
scaled_pixmap = pixmap.scaled(
|
682 |
+
self.selected_image_label.size(),
|
683 |
+
Qt.KeepAspectRatio,
|
684 |
+
Qt.SmoothTransformation
|
685 |
+
)
|
686 |
+
self.selected_image_label.setPixmap(scaled_pixmap)
|
687 |
+
else:
|
688 |
+
self.selected_image_label.clear()
|
689 |
+
|
690 |
+
def load_models(self):
|
691 |
+
checkpoint_path = Path(self.checkpoint_path_line.text())
|
692 |
+
if not checkpoint_path.exists():
|
693 |
+
QMessageBox.warning(self, "Checkpoint Error", f"Checkpoint path does not exist: {checkpoint_path}")
|
694 |
+
return
|
695 |
+
|
696 |
+
try:
|
697 |
+
(
|
698 |
+
self.clip_processor,
|
699 |
+
self.clip_model,
|
700 |
+
self.tokenizer,
|
701 |
+
self.text_model,
|
702 |
+
self.image_adapter,
|
703 |
+
) = load_models(checkpoint_path)
|
704 |
+
QMessageBox.information(self, "Models Loaded", "Models have been loaded successfully.")
|
705 |
+
except Exception as e:
|
706 |
+
QMessageBox.critical(self, "Model Loading Error", f"An error occurred while loading models: {e}")
|
707 |
+
|
708 |
+
def collect_parameters(self):
|
709 |
+
# Collect parameters for caption generation
|
710 |
+
caption_type = self.caption_type_combo.currentText()
|
711 |
+
caption_length = self.caption_length_combo.currentText()
|
712 |
+
extra_options = [checkbox.text() for checkbox in self.extra_options_checkboxes if checkbox.isChecked()]
|
713 |
+
name_input = self.name_input_line.text()
|
714 |
+
custom_prompt = self.custom_prompt_text.toPlainText()
|
715 |
+
|
716 |
+
return caption_type, caption_length, extra_options, name_input, custom_prompt
|
717 |
+
|
718 |
+
def generate_captions(self):
|
719 |
+
# Determine which images to process
|
720 |
+
if hasattr(self, 'input_image_path') and self.input_image_path is not None:
|
721 |
+
image_paths = [self.input_image_path]
|
722 |
+
elif hasattr(self, 'image_files') and self.image_files:
|
723 |
+
image_paths = self.image_files
|
724 |
+
else:
|
725 |
+
QMessageBox.warning(self, "No Images", "Please select an image or directory containing images.")
|
726 |
+
return
|
727 |
+
|
728 |
+
if not all([self.clip_processor, self.clip_model, self.tokenizer, self.text_model, self.image_adapter]):
|
729 |
+
QMessageBox.warning(self, "Models Not Loaded", "Please load the models before generating captions.")
|
730 |
+
return
|
731 |
+
|
732 |
+
# Collect parameters
|
733 |
+
caption_type, caption_length, extra_options, name_input, custom_prompt = self.collect_parameters()
|
734 |
+
|
735 |
+
# Process each image
|
736 |
+
for image_path in image_paths:
|
737 |
+
print(f"\nProcessing image: {image_path}")
|
738 |
+
input_image = Image.open(image_path).convert("RGB")
|
739 |
+
|
740 |
+
try:
|
741 |
+
prompt_str, caption = generate_caption(
|
742 |
+
input_image,
|
743 |
+
caption_type,
|
744 |
+
caption_length,
|
745 |
+
extra_options,
|
746 |
+
name_input,
|
747 |
+
custom_prompt,
|
748 |
+
self.clip_model,
|
749 |
+
self.tokenizer,
|
750 |
+
self.text_model,
|
751 |
+
self.image_adapter,
|
752 |
+
)
|
753 |
+
|
754 |
+
# Save the caption in a text file with the same name as the image
|
755 |
+
caption_file = image_path.with_suffix('.txt')
|
756 |
+
with open(caption_file, 'w', encoding='utf-8') as f:
|
757 |
+
# Just write the caption
|
758 |
+
f.write(f"{caption}\n")
|
759 |
+
|
760 |
+
print(f"Caption saved to {caption_file}")
|
761 |
+
|
762 |
+
except Exception as e:
|
763 |
+
print(f"Error processing image {image_path}: {e}")
|
764 |
+
continue
|
765 |
+
|
766 |
+
QMessageBox.information(self, "Captions Generated", "Captions have been generated and saved.")
|
767 |
+
|
768 |
+
def caption_selected_image(self):
|
769 |
+
if not self.selected_image_path:
|
770 |
+
QMessageBox.warning(self, "No Image Selected", "Please select an image from the list.")
|
771 |
+
return
|
772 |
+
|
773 |
+
if not all([self.clip_processor, self.clip_model, self.tokenizer, self.text_model, self.image_adapter]):
|
774 |
+
QMessageBox.warning(self, "Models Not Loaded", "Please load the models before generating captions.")
|
775 |
+
return
|
776 |
+
|
777 |
+
caption_type, caption_length, extra_options, name_input, custom_prompt = self.collect_parameters()
|
778 |
+
|
779 |
+
print(f"\nProcessing image: {self.selected_image_path}")
|
780 |
+
input_image = Image.open(self.selected_image_path).convert("RGB")
|
781 |
+
|
782 |
+
try:
|
783 |
+
prompt_str, caption = generate_caption(
|
784 |
+
input_image,
|
785 |
+
caption_type,
|
786 |
+
caption_length,
|
787 |
+
extra_options,
|
788 |
+
name_input,
|
789 |
+
custom_prompt,
|
790 |
+
self.clip_model,
|
791 |
+
self.tokenizer,
|
792 |
+
self.text_model,
|
793 |
+
self.image_adapter,
|
794 |
+
)
|
795 |
+
|
796 |
+
# Save the caption in a text file with the same name as the image
|
797 |
+
caption_file = self.selected_image_path.with_suffix('.txt')
|
798 |
+
with open(caption_file, 'w', encoding='utf-8') as f:
|
799 |
+
# Just write the caption
|
800 |
+
f.write(f"{caption}\n")
|
801 |
+
|
802 |
+
print(f"Caption saved to {caption_file}")
|
803 |
+
|
804 |
+
except Exception as e:
|
805 |
+
print(f"Error processing image {self.selected_image_path}: {e}")
|
806 |
+
QMessageBox.critical(self, "Error", f"An error occurred: {e}")
|
807 |
+
return
|
808 |
+
|
809 |
+
QMessageBox.information(self, "Caption Generated", f"Caption has been generated and saved for {self.selected_image_path.name}.")
|
810 |
+
|
811 |
+
def caption_single_image(self):
|
812 |
+
if not self.single_image_path:
|
813 |
+
QMessageBox.warning(self, "No Image Selected", "Please select a single image.")
|
814 |
+
return
|
815 |
+
|
816 |
+
if not all([self.clip_processor, self.clip_model, self.tokenizer, self.text_model, self.image_adapter]):
|
817 |
+
QMessageBox.warning(self, "Models Not Loaded", "Please load the models before generating captions.")
|
818 |
+
return
|
819 |
+
|
820 |
+
caption_type, caption_length, extra_options, name_input, custom_prompt = self.collect_parameters()
|
821 |
+
|
822 |
+
print(f"\nProcessing image: {self.single_image_path}")
|
823 |
+
input_image = Image.open(self.single_image_path).convert("RGB")
|
824 |
+
|
825 |
+
try:
|
826 |
+
prompt_str, caption = generate_caption(
|
827 |
+
input_image,
|
828 |
+
caption_type,
|
829 |
+
caption_length,
|
830 |
+
extra_options,
|
831 |
+
name_input,
|
832 |
+
custom_prompt,
|
833 |
+
self.clip_model,
|
834 |
+
self.tokenizer,
|
835 |
+
self.text_model,
|
836 |
+
self.image_adapter,
|
837 |
+
)
|
838 |
+
|
839 |
+
# Save the caption in a text file with the same name as the image
|
840 |
+
caption_file = self.single_image_path.with_suffix('.txt')
|
841 |
+
with open(caption_file, 'w', encoding='utf-8') as f:
|
842 |
+
# Just write the caption
|
843 |
+
f.write(f"{caption}\n")
|
844 |
+
|
845 |
+
print(f"Caption saved to {caption_file}")
|
846 |
+
|
847 |
+
except Exception as e:
|
848 |
+
print(f"Error processing image {self.single_image_path}: {e}")
|
849 |
+
QMessageBox.critical(self, "Error", f"An error occurred: {e}")
|
850 |
+
return
|
851 |
+
|
852 |
+
QMessageBox.information(self, "Caption Generated", f"Caption has been generated and saved for {self.single_image_path.name}.")
|
853 |
+
|
854 |
+
def resizeEvent(self, event):
|
855 |
+
super().resizeEvent(event)
|
856 |
+
if self.selected_image_path and self.selected_image_label.pixmap():
|
857 |
+
pixmap = QPixmap(str(self.selected_image_path))
|
858 |
+
if not pixmap.isNull():
|
859 |
+
# Rescale the pixmap to fit the label size
|
860 |
+
scaled_pixmap = pixmap.scaled(
|
861 |
+
self.selected_image_label.size(),
|
862 |
+
Qt.KeepAspectRatio,
|
863 |
+
Qt.SmoothTransformation
|
864 |
+
)
|
865 |
+
self.selected_image_label.setPixmap(scaled_pixmap)
|
866 |
|
867 |
if __name__ == "__main__":
|
868 |
+
app = QApplication(sys.argv)
|
869 |
+
window = CaptionApp()
|
870 |
+
window.show()
|
871 |
+
sys.exit(app.exec_())
|