Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
@@ -25,13 +25,17 @@ from pathlib import Path
|
|
25 |
from tqdm import tqdm
|
26 |
from torch import nn
|
27 |
from transformers import AutoModel, AutoProcessor, AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast, AutoModelForCausalLM
|
28 |
-
from typing import List
|
29 |
|
30 |
-
|
|
|
31 |
VLM_PROMPT = "A descriptive caption for this image:\n"
|
32 |
MODEL_PATH = "unsloth/Meta-Llama-3.1-8B-bnb-4bit"
|
33 |
CHECKPOINT_PATH = Path("wpkklhc6")
|
|
|
|
|
34 |
warnings.filterwarnings("ignore", category=UserWarning)
|
|
|
35 |
|
36 |
class ImageAdapter(nn.Module):
|
37 |
def __init__(self, input_features: int, output_features: int):
|
@@ -41,72 +45,53 @@ class ImageAdapter(nn.Module):
|
|
41 |
self.linear2 = nn.Linear(output_features, output_features)
|
42 |
|
43 |
def forward(self, vision_outputs: torch.Tensor):
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
print("Loading LLM π€")
|
65 |
-
logging.getLogger("transformers").setLevel(logging.ERROR)
|
66 |
-
text_model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, device_map="auto", torch_dtype=torch.bfloat16)
|
67 |
-
text_model.eval()
|
68 |
|
69 |
-
# Image Adapter
|
70 |
-
print("Loading image adapter πΌοΈ")
|
71 |
-
image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size)
|
72 |
-
image_adapter.load_state_dict(torch.load(CHECKPOINT_PATH / "image_adapter.pt", map_location="cpu", weights_only=True))
|
73 |
-
image_adapter.eval()
|
74 |
-
image_adapter.to("cuda")
|
75 |
|
76 |
@torch.no_grad()
|
77 |
-
def stream_chat(input_images: List[Image.Image], batch_size
|
|
|
78 |
torch.cuda.empty_cache()
|
79 |
all_captions = []
|
80 |
|
81 |
-
if not isinstance(input_images, list):
|
82 |
-
input_images = [input_images]
|
83 |
-
|
84 |
for i in range(0, len(input_images), batch_size):
|
85 |
batch = input_images[i:i+batch_size]
|
86 |
|
87 |
-
# Preprocess image batch
|
88 |
try:
|
89 |
-
images = clip_processor(images=batch, return_tensors='pt', padding=True).pixel_values
|
90 |
except ValueError as e:
|
91 |
print(f"Error processing image batch: {e}")
|
92 |
print("Skipping this batch and continuing...")
|
93 |
continue
|
94 |
|
95 |
-
images = images.to('cuda')
|
96 |
-
|
97 |
-
# Embed image batch
|
98 |
with torch.amp.autocast_mode.autocast('cuda', enabled=True):
|
99 |
vision_outputs = clip_model(pixel_values=images, output_hidden_states=True)
|
100 |
image_features = vision_outputs.hidden_states[-2]
|
101 |
-
embedded_images = image_adapter(image_features)
|
102 |
-
embedded_images = embedded_images.to(dtype=torch.bfloat16)
|
103 |
|
104 |
-
# Embed prompt
|
105 |
prompt = tokenizer.encode(VLM_PROMPT, return_tensors='pt')
|
106 |
prompt_embeds = text_model.model.embed_tokens(prompt.to('cuda')).to(dtype=torch.bfloat16)
|
107 |
embedded_bos = text_model.model.embed_tokens(torch.tensor([[tokenizer.bos_token_id]], device=text_model.device, dtype=torch.int64)).to(dtype=torch.bfloat16)
|
108 |
|
109 |
-
# Construct prompts
|
110 |
inputs_embeds = torch.cat([
|
111 |
embedded_bos.expand(embedded_images.shape[0], -1, -1),
|
112 |
embedded_images,
|
@@ -131,86 +116,38 @@ def stream_chat(input_images: List[Image.Image], batch_size=4, pbar=None):
|
|
131 |
temperature=0.5,
|
132 |
)
|
133 |
|
134 |
-
if pbar:
|
135 |
-
pbar.update(len(batch))
|
136 |
-
|
137 |
-
# Trim off the prompt
|
138 |
generate_ids = generate_ids[:, input_ids.shape[1]:]
|
139 |
|
140 |
for ids in generate_ids:
|
141 |
-
if ids[-1] == tokenizer.eos_token_id
|
142 |
-
ids = ids[:-1]
|
143 |
-
caption = tokenizer.decode(ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)
|
144 |
-
# Remove any remaining special tokens
|
145 |
caption = caption.replace('<|end_of_text|>', '').replace('<|finetune_right_pad_id|>', '').strip()
|
146 |
all_captions.append(caption)
|
147 |
|
148 |
-
|
149 |
-
|
150 |
-
def preprocess_image(img):
|
151 |
-
return img.convert('RGBA')
|
152 |
-
|
153 |
-
def process_image(image_path, output_path, pbar=None):
|
154 |
-
try:
|
155 |
-
with Image.open(image_path) as img:
|
156 |
-
# Convert image to RGB
|
157 |
-
img = img.convert('RGB')
|
158 |
-
caption = stream_chat([img], pbar=pbar)[0]
|
159 |
-
with open(output_path, 'w', encoding='utf-8') as f:
|
160 |
-
f.write(caption)
|
161 |
-
except Exception as e:
|
162 |
-
print(f"Error processing {image_path}: {e}")
|
163 |
-
if pbar:
|
164 |
-
pbar.update(1)
|
165 |
-
return
|
166 |
-
|
167 |
-
with Image.open(image_path) as img:
|
168 |
-
# Pass the image as a list to stream_chat
|
169 |
-
caption = stream_chat([img], pbar=pbar)[0] # Get the first (and only) caption
|
170 |
-
|
171 |
-
with open(output_path, 'w', encoding='utf-8') as f:
|
172 |
-
f.write(caption)
|
173 |
-
|
174 |
-
def process_directory(input_dir, output_dir, batch_size):
|
175 |
-
input_path = Path(input_dir)
|
176 |
-
output_path = Path(output_dir)
|
177 |
-
output_path.mkdir(parents=True, exist_ok=True)
|
178 |
|
179 |
-
|
180 |
-
image_files = [f for f in input_path.iterdir() if f.suffix.lower() in image_extensions]
|
181 |
|
182 |
-
|
183 |
-
|
|
|
|
|
184 |
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
if not output_file.exists():
|
189 |
-
images_to_process.append(file)
|
190 |
-
else:
|
191 |
-
print(f"Skipping {file.name} - Caption already exists")
|
192 |
|
193 |
-
# Process images in batches
|
194 |
with tqdm(total=len(images_to_process), desc="Processing images", unit="image") as pbar:
|
195 |
for i in range(0, len(images_to_process), batch_size):
|
196 |
batch_files = images_to_process[i:i+batch_size]
|
197 |
-
batch_images = []
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
if batch_images:
|
207 |
-
captions = stream_chat(batch_images, batch_size, pbar)
|
208 |
-
for file, caption in zip(batch_files, captions):
|
209 |
-
output_file = output_path / (file.stem + '.txt')
|
210 |
-
with open(output_file, 'w', encoding='utf-8') as f:
|
211 |
-
f.write(caption)
|
212 |
-
|
213 |
-
# Close the image files
|
214 |
for img in batch_images:
|
215 |
img.close()
|
216 |
|
@@ -221,31 +158,27 @@ def parse_arguments():
|
|
221 |
parser.add_argument("--bs", type=int, default=4, help="Batch size (default: 4)")
|
222 |
return parser.parse_args()
|
223 |
|
224 |
-
def
|
225 |
-
image_extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.webp')
|
226 |
-
return Path(file_path).suffix.lower() in image_extensions
|
227 |
-
|
228 |
-
# Main execution
|
229 |
-
if __name__ == "__main__":
|
230 |
args = parse_arguments()
|
231 |
input_paths = [Path(input_path) for input_path in args.input]
|
232 |
batch_size = args.bs
|
|
|
233 |
|
234 |
for input_path in input_paths:
|
235 |
-
if input_path.is_file() and
|
236 |
-
# Single file processing
|
237 |
output_path = input_path.with_suffix('.txt')
|
238 |
print(f"Processing single image ποΈ: {input_path.name}")
|
239 |
with tqdm(total=1, desc="Processing image", unit="image") as pbar:
|
240 |
-
|
|
|
|
|
241 |
print(f"Output saved to {output_path}")
|
242 |
elif input_path.is_dir():
|
243 |
-
# Directory processing
|
244 |
output_path = Path(args.output) if args.output else input_path
|
245 |
print(f"Processing directory π: {input_path}")
|
246 |
print(f"Output directory π¦: {output_path}")
|
247 |
print(f"Batch size ποΈ: {batch_size}")
|
248 |
-
process_directory(input_path, output_path, batch_size)
|
249 |
else:
|
250 |
print(f"Invalid input: {input_path}")
|
251 |
print("Skipping...")
|
@@ -256,4 +189,7 @@ if __name__ == "__main__":
|
|
256 |
print("For directory (same input/output): python app.py [directory] [--bs batch_size]")
|
257 |
print("For directory (separate input/output): python app.py [directory] --output [output_directory] [--bs batch_size]")
|
258 |
print("For multiple directories: python app.py [directory1] [directory2] ... [--output output_directory] [--bs batch_size]")
|
259 |
-
sys.exit(1)
|
|
|
|
|
|
|
|
25 |
from tqdm import tqdm
|
26 |
from torch import nn
|
27 |
from transformers import AutoModel, AutoProcessor, AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast, AutoModelForCausalLM
|
28 |
+
from typing import List, Union
|
29 |
|
30 |
+
# Constants
|
31 |
+
CLIP_PATH = "OpenGVLab/InternViT-300M-448px"
|
32 |
VLM_PROMPT = "A descriptive caption for this image:\n"
|
33 |
MODEL_PATH = "unsloth/Meta-Llama-3.1-8B-bnb-4bit"
|
34 |
CHECKPOINT_PATH = Path("wpkklhc6")
|
35 |
+
IMAGE_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.bmp', '.webp')
|
36 |
+
|
37 |
warnings.filterwarnings("ignore", category=UserWarning)
|
38 |
+
logging.getLogger("transformers").setLevel(logging.ERROR)
|
39 |
|
40 |
class ImageAdapter(nn.Module):
|
41 |
def __init__(self, input_features: int, output_features: int):
|
|
|
45 |
self.linear2 = nn.Linear(output_features, output_features)
|
46 |
|
47 |
def forward(self, vision_outputs: torch.Tensor):
|
48 |
+
return self.linear2(self.activation(self.linear1(vision_outputs)))
|
49 |
+
|
50 |
+
def load_models():
|
51 |
+
print("Loading CLIP π")
|
52 |
+
clip_processor = AutoProcessor.from_pretrained(CLIP_PATH, trust_remote_code=True)
|
53 |
+
clip_model = AutoModel.from_pretrained(CLIP_PATH, trust_remote_code=True).vision_model.eval().requires_grad_(False).to("cuda")
|
54 |
+
|
55 |
+
print("Loading tokenizer πͺ")
|
56 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, use_fast=False)
|
57 |
+
assert isinstance(tokenizer, (PreTrainedTokenizer, PreTrainedTokenizerFast)), f"Tokenizer is of type {type(tokenizer)}"
|
58 |
+
|
59 |
+
print("Loading LLM π€")
|
60 |
+
text_model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, device_map="auto", torch_dtype=torch.bfloat16).eval()
|
61 |
+
|
62 |
+
print("Loading image adapter πΌοΈ")
|
63 |
+
image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size)
|
64 |
+
image_adapter.load_state_dict(torch.load(CHECKPOINT_PATH / "image_adapter.pt", map_location="cpu", weights_only=True))
|
65 |
+
image_adapter.eval().to("cuda")
|
66 |
+
|
67 |
+
return clip_processor, clip_model, tokenizer, text_model, image_adapter
|
|
|
|
|
|
|
|
|
68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
|
70 |
@torch.no_grad()
|
71 |
+
def stream_chat(input_images: List[Image.Image], batch_size: int, pbar: tqdm, models: tuple) -> List[str]:
|
72 |
+
clip_processor, clip_model, tokenizer, text_model, image_adapter = models
|
73 |
torch.cuda.empty_cache()
|
74 |
all_captions = []
|
75 |
|
|
|
|
|
|
|
76 |
for i in range(0, len(input_images), batch_size):
|
77 |
batch = input_images[i:i+batch_size]
|
78 |
|
|
|
79 |
try:
|
80 |
+
images = clip_processor(images=batch, return_tensors='pt', padding=True).pixel_values.to('cuda')
|
81 |
except ValueError as e:
|
82 |
print(f"Error processing image batch: {e}")
|
83 |
print("Skipping this batch and continuing...")
|
84 |
continue
|
85 |
|
|
|
|
|
|
|
86 |
with torch.amp.autocast_mode.autocast('cuda', enabled=True):
|
87 |
vision_outputs = clip_model(pixel_values=images, output_hidden_states=True)
|
88 |
image_features = vision_outputs.hidden_states[-2]
|
89 |
+
embedded_images = image_adapter(image_features).to(dtype=torch.bfloat16)
|
|
|
90 |
|
|
|
91 |
prompt = tokenizer.encode(VLM_PROMPT, return_tensors='pt')
|
92 |
prompt_embeds = text_model.model.embed_tokens(prompt.to('cuda')).to(dtype=torch.bfloat16)
|
93 |
embedded_bos = text_model.model.embed_tokens(torch.tensor([[tokenizer.bos_token_id]], device=text_model.device, dtype=torch.int64)).to(dtype=torch.bfloat16)
|
94 |
|
|
|
95 |
inputs_embeds = torch.cat([
|
96 |
embedded_bos.expand(embedded_images.shape[0], -1, -1),
|
97 |
embedded_images,
|
|
|
116 |
temperature=0.5,
|
117 |
)
|
118 |
|
|
|
|
|
|
|
|
|
119 |
generate_ids = generate_ids[:, input_ids.shape[1]:]
|
120 |
|
121 |
for ids in generate_ids:
|
122 |
+
caption = tokenizer.decode(ids[:-1] if ids[-1] == tokenizer.eos_token_id else ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)
|
|
|
|
|
|
|
123 |
caption = caption.replace('<|end_of_text|>', '').replace('<|finetune_right_pad_id|>', '').strip()
|
124 |
all_captions.append(caption)
|
125 |
|
126 |
+
if pbar:
|
127 |
+
pbar.update(len(batch))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
128 |
|
129 |
+
return all_captions
|
|
|
130 |
|
131 |
+
def process_directory(input_dir: Path, output_dir: Path, batch_size: int, models: tuple):
|
132 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
133 |
+
image_files = [f for f in input_dir.iterdir() if f.suffix.lower() in IMAGE_EXTENSIONS]
|
134 |
+
images_to_process = [f for f in image_files if not (output_dir / f"{f.stem}.txt").exists()]
|
135 |
|
136 |
+
if not images_to_process:
|
137 |
+
print("No new images to process.")
|
138 |
+
return
|
|
|
|
|
|
|
|
|
139 |
|
|
|
140 |
with tqdm(total=len(images_to_process), desc="Processing images", unit="image") as pbar:
|
141 |
for i in range(0, len(images_to_process), batch_size):
|
142 |
batch_files = images_to_process[i:i+batch_size]
|
143 |
+
batch_images = [Image.open(f).convert('RGB') for f in batch_files]
|
144 |
+
|
145 |
+
captions = stream_chat(batch_images, batch_size, pbar, models)
|
146 |
+
|
147 |
+
for file, caption in zip(batch_files, captions):
|
148 |
+
with open(output_dir / f"{file.stem}.txt", 'w', encoding='utf-8') as f:
|
149 |
+
f.write(caption)
|
150 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
151 |
for img in batch_images:
|
152 |
img.close()
|
153 |
|
|
|
158 |
parser.add_argument("--bs", type=int, default=4, help="Batch size (default: 4)")
|
159 |
return parser.parse_args()
|
160 |
|
161 |
+
def main():
|
|
|
|
|
|
|
|
|
|
|
162 |
args = parse_arguments()
|
163 |
input_paths = [Path(input_path) for input_path in args.input]
|
164 |
batch_size = args.bs
|
165 |
+
models = load_models()
|
166 |
|
167 |
for input_path in input_paths:
|
168 |
+
if input_path.is_file() and input_path.suffix.lower() in IMAGE_EXTENSIONS:
|
|
|
169 |
output_path = input_path.with_suffix('.txt')
|
170 |
print(f"Processing single image ποΈ: {input_path.name}")
|
171 |
with tqdm(total=1, desc="Processing image", unit="image") as pbar:
|
172 |
+
captions = stream_chat([Image.open(input_path).convert('RGB')], 1, pbar, models)
|
173 |
+
with open(output_path, 'w', encoding='utf-8') as f:
|
174 |
+
f.write(captions[0])
|
175 |
print(f"Output saved to {output_path}")
|
176 |
elif input_path.is_dir():
|
|
|
177 |
output_path = Path(args.output) if args.output else input_path
|
178 |
print(f"Processing directory π: {input_path}")
|
179 |
print(f"Output directory π¦: {output_path}")
|
180 |
print(f"Batch size ποΈ: {batch_size}")
|
181 |
+
process_directory(input_path, output_path, batch_size, models)
|
182 |
else:
|
183 |
print(f"Invalid input: {input_path}")
|
184 |
print("Skipping...")
|
|
|
189 |
print("For directory (same input/output): python app.py [directory] [--bs batch_size]")
|
190 |
print("For directory (separate input/output): python app.py [directory] --output [output_directory] [--bs batch_size]")
|
191 |
print("For multiple directories: python app.py [directory1] [directory2] ... [--output output_directory] [--bs batch_size]")
|
192 |
+
sys.exit(1)
|
193 |
+
|
194 |
+
if __name__ == "__main__":
|
195 |
+
main()
|