Spaces:
Sleeping
Sleeping
File size: 9,011 Bytes
d1df841 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 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 66 67 68 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 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 |
import asyncio
import os
import logging
from PIL import Image
import torch
from transformers import (
CLIPProcessor,
CLIPModel,
BlipProcessor,
BlipForConditionalGeneration,
)
from sentence_transformers import SentenceTransformer
import numpy as np
import aiofiles
import json
from abc import ABC, abstractmethod
from typing import Set, Tuple
from concurrent.futures import ProcessPoolExecutor
from dataclasses import dataclass, field
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
device = "cpu"
@dataclass
class State:
processed_files: Set[str] = field(default_factory=set)
def to_dict(self) -> dict:
return {"processed_files": list(self.processed_files)}
@staticmethod
def from_dict(state_dict: dict) -> "State":
return State(processed_files=set(state_dict.get("processed_files", [])))
class ImageProcessor(ABC):
@abstractmethod
def process(self, image: Image.Image) -> np.ndarray:
pass
class CLIPImageProcessor(ImageProcessor):
def __init__(self):
self.model = CLIPModel.from_pretrained(
"wkcn/TinyCLIP-ViT-8M-16-Text-3M-YFCC15M"
).to(device)
self.processor = CLIPProcessor.from_pretrained(
"wkcn/TinyCLIP-ViT-8M-16-Text-3M-YFCC15M"
)
print("Initialized CLIP model and processor")
def process(self, image: Image.Image) -> np.ndarray:
inputs = self.processor(images=image, return_tensors="pt").to(device)
outputs = self.model.get_image_features(**inputs)
return outputs.detach().cpu().numpy()
class ImageCaptioningProcessor(ImageProcessor):
def __init__(self):
self.image_caption_model = BlipForConditionalGeneration.from_pretrained(
"Salesforce/blip-image-captioning-base"
).to(device)
self.image_caption_processor = BlipProcessor.from_pretrained(
"Salesforce/blip-image-captioning-base"
)
self.text_embedding_model = SentenceTransformer(
"all-MiniLM-L6-v2", device=device
)
print("Initialized BLIP model and processor")
def process(self, image: Image.Image) -> np.ndarray:
inputs = self.image_caption_processor(images=image, return_tensors="pt").to(
device
)
output = self.image_caption_model.generate(**inputs)
caption = self.image_caption_processor.decode(
output[0], skip_special_tokens=True
)
# embedding dim 384
return self.text_embedding_model.encode(caption).flatten()
class ImageFeatureExtractor:
def __init__(
self,
clip_processor: CLIPImageProcessor,
caption_processor: ImageCaptioningProcessor,
max_queue_size: int = 100,
checkpoint_file: str = "checkpoint.json",
):
self.clip_processor = clip_processor
self.caption_processor = caption_processor
self.image_queue = asyncio.Queue(maxsize=max_queue_size)
self.processed_images_queue = asyncio.Queue()
self.checkpoint_file = checkpoint_file
self.state = self.load_state()
self.executor = ProcessPoolExecutor()
self.total_images = 0
self.processed_count = 0
print(
"Initialized ImageFeatureExtractor with checkpoint file:", checkpoint_file
)
async def image_loader(self, input_folder: str):
print(f"Loading images from {input_folder}")
for filename in os.listdir(input_folder):
if "resized_" in filename and filename not in self.state.processed_files:
try:
file_path = os.path.join(input_folder, filename)
await self.image_queue.put((filename, file_path))
self.total_images += 1
print(f"Loaded image {filename} into queue")
except Exception as e:
logger.error(f"Error loading image {filename}: {e}")
await self.image_queue.put(None) # Sentinel to signal end of images
print(f"Total images to process: {self.total_images}")
async def image_processor_worker(self, loop: asyncio.AbstractEventLoop):
while True:
item = await self.image_queue.get()
if item is None:
await self.image_queue.put(None) # Propagate sentinel
break
filename, file_path = item
try:
print(f"Processing image {filename}")
image = Image.open(file_path)
clip_embedding, caption_embedding = await asyncio.gather(
loop.run_in_executor(
self.executor, self.clip_processor.process, image
),
loop.run_in_executor(
self.executor, self.caption_processor.process, image
),
)
await self.processed_images_queue.put(
(filename, clip_embedding, caption_embedding)
)
print(f"Processed image {filename}")
except Exception as e:
logger.error(f"Error processing image {filename}: {e}")
finally:
self.image_queue.task_done()
async def save_processed_images(self, output_folder: str):
while self.processed_count < self.total_images:
filename, clip_embedding, caption_embedding = (
await self.processed_images_queue.get()
)
try:
clip_output_path = os.path.join(
output_folder, f"{os.path.splitext(filename)[0]}_clip.npy"
)
caption_output_path = os.path.join(
output_folder, f"{os.path.splitext(filename)[0]}_caption.npy"
)
await asyncio.gather(
self.save_embedding(clip_output_path, clip_embedding),
self.save_embedding(caption_output_path, caption_embedding),
)
self.state.processed_files.add(filename)
self.save_state()
self.processed_count += 1
print(f"Saved processed embeddings for {filename}")
except Exception as e:
logger.error(f"Error saving processed image {filename}: {e}")
finally:
self.processed_images_queue.task_done()
async def save_embedding(self, output_path: str, embedding: np.ndarray):
async with aiofiles.open(output_path, "wb") as f:
await f.write(embedding.tobytes())
def load_state(self) -> State:
try:
with open(self.checkpoint_file, "r") as f:
state_dict = json.load(f)
print("Loaded state from checkpoint")
return State.from_dict(state_dict)
except (FileNotFoundError, json.JSONDecodeError):
print("No checkpoint found, starting with empty state")
return State()
def save_state(self):
with open(self.checkpoint_file, "w") as f:
json.dump(self.state.to_dict(), f)
print("Saved state to checkpoint")
async def run(
self,
input_folder: str,
output_folder: str,
loop: asyncio.AbstractEventLoop,
num_workers: int = 2,
):
os.makedirs(output_folder, exist_ok=True)
print(f"Output folder {output_folder} created")
tasks = [
loop.create_task(self.image_loader(input_folder)),
loop.create_task(self.save_processed_images(output_folder)),
]
tasks.extend(
[
loop.create_task(self.image_processor_worker(loop))
for _ in range(num_workers)
]
)
await asyncio.gather(*tasks)
class ImageFeatureExtractorFactory:
@staticmethod
def create() -> ImageFeatureExtractor:
print(
"Creating ImageFeatureExtractor with CLIPImageProcessor and ImageCaptioningProcessor"
)
return ImageFeatureExtractor(CLIPImageProcessor(), ImageCaptioningProcessor())
async def main(loop: asyncio.AbstractEventLoop, input_folder: str, output_folder: str):
print("Starting main function")
extractor = ImageFeatureExtractorFactory.create()
try:
await extractor.run(input_folder, output_folder, loop)
except Exception as e:
logger.error(f"An error occurred during execution: {e}")
finally:
logger.info("Image processing completed.")
if __name__ == "__main__":
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parent.parent
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
print("Event loop created and set")
input_folder = str(PROJECT_ROOT / "data/images")
output_folder = str(PROJECT_ROOT / "data/features")
loop.run_until_complete(main(loop, input_folder, output_folder))
loop.close()
print("Event loop closed")
|