Spaces:
Sleeping
Sleeping
File size: 8,900 Bytes
c1596ac | 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 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 | import os
import json
import random
from pathlib import Path
import torch
from PIL import Image
from tqdm import tqdm
from dotenv import load_dotenv
from transformers import AutoProcessor, Florence2ForConditionalGeneration
# =========================================================
# 1. ์ค์ ๊ฐ
# =========================================================
# ์ ์ฒด ํด๋์ค ์บก์
๋: "data/raw"
# ํน์ ํด๋์ค๋ง ์บก์
๋: "data/raw/apple"
INPUT_IMAGE_DIR = "data/raw"
# image ๊ฐ์ "pizza/hf_pizza_001.jpg" ํํ๋ก ๋ง๋ค๊ธฐ ์ํ ๊ธฐ์ค ๊ฒฝ๋ก
DATA_RAW_ROOT = "data/raw"
# ๊ฒฐ๊ณผ JSON ์ ์ฅ ๊ฒฝ๋ก
OUTPUT_JSON_PATH = "data/annotations/captions_flo_all.json"
# transformers 5.7.0์์๋ florence-community ๋ชจ๋ธ ์ฌ์ฉ ๊ถ์ฅ
# base-ft: ๊ฐ๋ณ๊ณ ๋ค์ด์คํธ๋ฆผ task์ fine-tuning๋ ๋ชจ๋ธ
# large-ft: ๋ ๋ฌด๊ฒ์ง๋ง ํ์ง์ด ๋ ์ข์ ์ ์์
MODEL_ID = "florence-community/Florence-2-base-ft"
# MODEL_ID = "florence-community/Florence-2-large-ft"
# .env ํ์ผ์์ ์ฝ์ Hugging Face ํ ํฐ ์ด๋ฆ
# ๊ณต๊ฐ ๋ชจ๋ธ์ด๋ฉด ์์ด๋ ๋์ํ ์ ์์ง๋ง, ํ ํฐ์ ๋ฃ์ด๋๋ ํธ์ด ์์ ์ ์
๋๋ค.
HF_TOKEN_ENV_NAME = "HF_TOKEN"
# split ๋น์จ: ๊ธฐ๋ณธ 7 : 1.5 : 1.5
TRAIN_RATIO = 0.7
VAL_RATIO = 0.15
TEST_RATIO = 0.15
# split ์ฌํ์ ์ํ seed
RANDOM_SEED = 42
# ์ด๋ฏธ์ง๋น ์บก์
3๊ฐ ์์ฑ
# Florence-2 ๋ฌธ์์์ ์ง์ํ๋ caption task์
๋๋ค.
CAPTION_TASKS = [
"<CAPTION>",
"<DETAILED_CAPTION>",
"<MORE_DETAILED_CAPTION>",
]
# ์์ฑ ์ต์
NUM_BEAMS = 3
MAX_NEW_TOKENS = 64
# ๋ช ์ฅ๋ง๋ค ์ค๊ฐ ์ ์ฅํ ์ง
SAVE_EVERY = 220
# ์ด๋ฏธ JSON์ ์๋ ์ด๋ฏธ์ง๋ ๊ฑด๋๋ธ์ง ์ฌ๋ถ
SKIP_ALREADY_DONE = True
# ํ์ฉ ์ด๋ฏธ์ง ํ์ฅ์
IMAGE_EXTENSIONS = [".jpg", ".jpeg", ".png", ".webp", ".bmp"]
# =========================================================
# 2. ์ด๋ฏธ์ง ๋ชฉ๋ก ๊ฐ์ ธ์ค๊ธฐ
# =========================================================
def get_image_list():
input_dir = Path(INPUT_IMAGE_DIR).resolve()
raw_root = Path(DATA_RAW_ROOT).resolve()
if not input_dir.exists():
raise FileNotFoundError(f"์
๋ ฅ ๊ฒฝ๋ก๊ฐ ์์ต๋๋ค: {input_dir}")
image_list = []
for image_path in sorted(input_dir.rglob("*")):
if image_path.suffix.lower() not in IMAGE_EXTENSIONS:
continue
# ์:
# /workspace/data/raw/pizza/hf_pizza_001.jpg
# -> pizza/hf_pizza_001.jpg
relative_image_path = image_path.resolve().relative_to(raw_root).as_posix()
# ์:
# pizza/hf_pizza_001.jpg
# -> pizza
class_name = relative_image_path.split("/")[0]
image_list.append({
"path": image_path,
"image": relative_image_path,
"class": class_name,
})
return image_list
# =========================================================
# 3. train / val / test ๋๋๊ธฐ
# =========================================================
def add_split(image_list):
random.seed(RANDOM_SEED)
total_ratio = TRAIN_RATIO + VAL_RATIO + TEST_RATIO
result = []
# ํด๋์ค๋ณ๋ก ์ด๋ฏธ์ง ๋ชจ์ผ๊ธฐ
class_map = {}
for item in image_list:
class_name = item["class"]
if class_name not in class_map:
class_map[class_name] = []
class_map[class_name].append(item)
# ํด๋์ค๋ณ๋ก train / val / test ๋๋๊ธฐ
for class_name, items in class_map.items():
random.shuffle(items)
total_count = len(items)
train_count = round(total_count * TRAIN_RATIO / total_ratio)
val_count = round(total_count * VAL_RATIO / total_ratio)
for index, item in enumerate(items):
if index < train_count:
split = "train"
elif index < train_count + val_count:
split = "val"
else:
split = "test"
item["split"] = split
result.append(item)
return result
# =========================================================
# 4. Florence-2 ๋ชจ๋ธ ์ค๋น
# =========================================================
def load_model():
load_dotenv()
hf_token = os.getenv(HF_TOKEN_ENV_NAME)
if torch.cuda.is_available():
device = "cuda"
# GPU๊ฐ bfloat16์ ์ง์ํ๋ฉด bfloat16 ์ฌ์ฉ
# ์๋๋ฉด float16 ์ฌ์ฉ
if torch.cuda.is_bf16_supported():
torch_dtype = torch.bfloat16
else:
torch_dtype = torch.float16
else:
device = "cpu"
torch_dtype = torch.float32
print(f"device: {device}")
print(f"dtype: {torch_dtype}")
print(f"model: {MODEL_ID}")
processor = AutoProcessor.from_pretrained(
MODEL_ID,
token=hf_token,
)
model = Florence2ForConditionalGeneration.from_pretrained(
MODEL_ID,
dtype=torch_dtype,
token=hf_token,
).to(device)
model.eval()
return model, processor, device, torch_dtype
# =========================================================
# 5. ์ด๋ฏธ์ง 1์ฅ ์บก์
๋
# =========================================================
def make_caption(image, task, model, processor, device, torch_dtype):
inputs = processor(
text=task,
images=image,
return_tensors="pt",
)
inputs = inputs.to(device, torch_dtype)
with torch.no_grad():
generated_ids = model.generate(
**inputs,
max_new_tokens=MAX_NEW_TOKENS,
num_beams=NUM_BEAMS,
do_sample=False,
)
generated_text = processor.batch_decode(
generated_ids,
skip_special_tokens=False,
)[0]
parsed_result = processor.post_process_generation(
generated_text,
task=task,
image_size=image.size,
)
caption = parsed_result.get(task, "")
if not isinstance(caption, str):
caption = str(caption)
return caption.strip()
def make_three_captions(image_path, model, processor, device, torch_dtype):
image = Image.open(image_path).convert("RGB")
captions = []
for task in CAPTION_TASKS:
caption = make_caption(
image=image,
task=task,
model=model,
processor=processor,
device=device,
torch_dtype=torch_dtype,
)
captions.append(caption)
return captions
# =========================================================
# 6. ๊ธฐ์กด JSON ์ฝ๊ธฐ / ์ ์ฅํ๊ธฐ
# =========================================================
def load_existing_result():
output_path = Path(OUTPUT_JSON_PATH)
if not output_path.exists():
return {}
with output_path.open("r", encoding="utf-8") as f:
data = json.load(f)
result = {}
for item in data:
result[item["image"]] = item
return result
def save_result(result_map):
output_path = Path(OUTPUT_JSON_PATH)
output_path.parent.mkdir(parents=True, exist_ok=True)
result_list = list(result_map.values())
result_list.sort(key=lambda x: x["image"])
with output_path.open("w", encoding="utf-8") as f:
json.dump(result_list, f, ensure_ascii=False, indent=4)
# =========================================================
# 7. ์คํ
# =========================================================
def main():
print("์ด๋ฏธ์ง ๋ชฉ๋ก์ ์ฝ๋ ์ค์
๋๋ค.")
image_list = get_image_list()
image_list = add_split(image_list)
print(f"์ด ์ด๋ฏธ์ง ์: {len(image_list)}")
result_map = load_existing_result()
model, processor, device, torch_dtype = load_model()
new_count = 0
skip_count = 0
fail_count = 0
for item in tqdm(image_list):
image_key = item["image"]
if SKIP_ALREADY_DONE and image_key in result_map:
skip_count += 1
continue
try:
captions = make_three_captions(
image_path=item["path"],
model=model,
processor=processor,
device=device,
torch_dtype=torch_dtype,
)
result_map[image_key] = {
"image": item["image"],
"class": item["class"],
"captions": captions,
"split": item["split"],
}
new_count += 1
if new_count % SAVE_EVERY == 0:
save_result(result_map)
except Exception as e:
fail_count += 1
print(f"\n์คํจํ ์ด๋ฏธ์ง: {item['path']}")
print(f"์๋ฌ ๋ด์ฉ: {e}")
save_result(result_map)
print("\n์บก์
๋ ์๋ฃ")
print(f"์๋ก ์ฒ๋ฆฌํ ์ด๋ฏธ์ง ์: {new_count}")
print(f"๊ฑด๋๋ด ์ด๋ฏธ์ง ์: {skip_count}")
print(f"์คํจํ ์ด๋ฏธ์ง ์: {fail_count}")
print(f"์ ์ฅ ์์น: {OUTPUT_JSON_PATH}")
if __name__ == "__main__":
main() |