Spaces:
Sleeping
Sleeping
Download src/caption/generate_captions_git.py from ImAMJayKIM/Mini-ImageNet: direct link, hf CLI and curl.
- Browser
- Download file 16.1 kB
-
https://huggingface.co/spaces/ImAMJayKIM/Mini-ImageNet/resolve/b95f88c26f1504fc50af77e2ebf884ba008c8335/src/caption/generate_captions_git.py
- Command line
-
hf download hf://spaces/ImAMJayKIM/Mini-ImageNet@b95f88c26f1504fc50af77e2ebf884ba008c8335/src/caption/generate_captions_git.py
-
curl -L -o generate_captions_git.py https://huggingface.co/spaces/ImAMJayKIM/Mini-ImageNet/resolve/b95f88c26f1504fc50af77e2ebf884ba008c8335/src/caption/generate_captions_git.py
16.1 kB
| import json | |
| import math | |
| import random | |
| import re | |
| from collections import defaultdict | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Dict, List, Tuple | |
| import os | |
| import torch | |
| from dotenv import load_dotenv | |
| from PIL import Image | |
| from tqdm import tqdm | |
| from transformers import AutoModelForCausalLM, AutoProcessor | |
| # ============================================================ | |
| # 1. ์ค์ ๊ฐ | |
| # ============================================================ | |
| load_dotenv() | |
| # .env ์์ HF_TOKEN ์ฝ๊ธฐ | |
| hf_token = os.getenv("HF_TOKEN") | |
| # ์ด๋ฏธ์ง ์๋ณธ ๋ฃจํธ ๊ฒฝ๋ก | |
| # ์: | |
| # - ์ ์ฒด ํด๋์ค ์บก์ ๋: "data/raw" | |
| # - ํน์ ํด๋์ค๋ง ์บก์ ๋: "data/raw/apple" | |
| INPUT_IMAGE_PATH = "data/raw/airplane" | |
| # image ํ๋๋ฅผ ๋ง๋ค ๋ ๊ธฐ์ค์ด ๋๋ root | |
| # JSON์๋ "pizza/hf_pizza_001.jpg" ํํ๋ก ์ ์ฅ๋จ | |
| DATA_RAW_ROOT = "data/raw" | |
| # ๊ฒฐ๊ณผ ์ ์ฅ ๊ฒฝ๋ก | |
| OUTPUT_JSON_PATH = "data/annotations/captions_git.json" | |
| # ์๋ฌ ์ด๋ฏธ์ง ๋ชฉ๋ก ์ ์ฅ ๊ฒฝ๋ก | |
| ERROR_JSON_PATH = "data/annotations/caption_git_errors.json" | |
| # GIT ๋ชจ๋ธ | |
| # ๊ธฐ๋ณธ ์ถ์ฒ: microsoft/git-base-coco | |
| # ๋ ํฐ ๋ชจ๋ธ์ ์ฐ๊ณ ์ถ์ผ๋ฉด: microsoft/git-large-coco | |
| MODEL_NAME = "microsoft/git-large-coco" | |
| # ์ด๋ฏธ์ง๋น ์์ฑํ ์บก์ ๊ฐ์ | |
| CAPTIONS_PER_IMAGE = 3 | |
| # split ๋น์จ | |
| # ๊ธฐ๋ณธ 7 : 1.5 : 1.5 | |
| SPLIT_RATIO = { | |
| "train": 0.7, | |
| "val": 0.15, | |
| "test": 0.15, | |
| } | |
| # split ์ฌํ์ฑ์ ์ํ seed | |
| RANDOM_SEED = 42 | |
| # ์ถ๋ก ๋ฐฐ์น ํฌ๊ธฐ | |
| # GPU ๋ฉ๋ชจ๋ฆฌ๊ฐ ๋ถ์กฑํ๋ฉด 8 -> 4 -> 2 -> 1 ์์๋ก ์ค์ด๊ธฐ | |
| BATCH_SIZE = 8 | |
| # ์ฅ์น ์ค์ | |
| # "auto": CUDA ๊ฐ๋ฅํ๋ฉด GPU, ์๋๋ฉด CPU | |
| # ์ง์ ์ง์ ๊ฐ๋ฅ: "cuda", "cpu" | |
| DEVICE = "auto" | |
| # dtype ์ค์ | |
| # "auto": CUDA๋ฉด float16, CPU๋ฉด float32 | |
| # ์ง์ ์ง์ ๊ฐ๋ฅ: "float32", "float16", "bfloat16" | |
| TORCH_DTYPE = "auto" | |
| # ์ค๊ฐ ์ ์ฅ ๊ฐ๊ฒฉ | |
| # ์ด๋ฏธ์ง๊ฐ ๋ง์ ๋ ์ค๊ฐ์ ์ค๋ฅ๊ฐ ๋๋ ์ผ๋ถ ๊ฒฐ๊ณผ๋ฅผ ๋ณด์กดํ๊ธฐ ์ํ ์ค์ | |
| SAVE_EVERY_N_IMAGES = 100 | |
| # ๊ธฐ์กด OUTPUT_JSON_PATH๊ฐ ์์ผ๋ฉด ์ด๋ฏธ ์บก์ ๋๋ ์ด๋ฏธ์ง๋ ๊ฑด๋๋ธ์ง ์ฌ๋ถ | |
| RESUME_FROM_EXISTING_JSON = True | |
| # ์ง์ ์ด๋ฏธ์ง ํ์ฅ์ | |
| SUPPORTED_EXTENSIONS = { | |
| ".jpg", ".jpeg", ".png", ".webp", ".bmp" | |
| } | |
| # ์บก์ ์์ฑ ์ค์ | |
| # num_beams >= num_return_sequences ์ฌ์ผ ํจ | |
| # num_beam_groups๋ฅผ ์ฌ์ฉํด์ ์๋ก ์กฐ๊ธ ๋ค๋ฅธ caption์ ์์ฑํ๋๋ก ํจ | |
| GENERATION_CONFIG = { | |
| "max_length": 40, | |
| "num_beams": 5, | |
| "num_return_sequences": CAPTIONS_PER_IMAGE, | |
| "early_stopping": True, | |
| "no_repeat_ngram_size": 2, | |
| } | |
| # beam search ๊ฒฐ๊ณผ๊ฐ ๋๋ฌด ์ค๋ณต๋ ๋ ์ถ๊ฐ ์ํ๋ง์ผ๋ก ๋ณด์ํ ์ง ์ฌ๋ถ | |
| ENABLE_SAMPLING_FALLBACK = True | |
| SAMPLING_FALLBACK_CONFIG = { | |
| "max_length": 40, | |
| "do_sample": True, | |
| "top_p": 0.9, | |
| "temperature": 0.8, | |
| "num_return_sequences": CAPTIONS_PER_IMAGE, | |
| "no_repeat_ngram_size": 2, | |
| } | |
| # ============================================================ | |
| # 2. ๋ฐ์ดํฐ ๊ตฌ์กฐ | |
| # ============================================================ | |
| class ImageItem: | |
| path: Path | |
| image_field: str | |
| class_name: str | |
| split: str = "" | |
| # ============================================================ | |
| # 3. ์ ํธ ํจ์ | |
| # ============================================================ | |
| def resolve_device() -> torch.device: | |
| if DEVICE == "auto": | |
| return torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| return torch.device(DEVICE) | |
| def resolve_dtype(device: torch.device) -> torch.dtype: | |
| if TORCH_DTYPE == "auto": | |
| return torch.float16 if device.type == "cuda" else torch.float32 | |
| dtype_map = { | |
| "float32": torch.float32, | |
| "float16": torch.float16, | |
| "bfloat16": torch.bfloat16, | |
| } | |
| if TORCH_DTYPE not in dtype_map: | |
| raise ValueError(f"์ง์ํ์ง ์๋ TORCH_DTYPE์ ๋๋ค: {TORCH_DTYPE}") | |
| if device.type == "cpu" and TORCH_DTYPE in {"float16", "bfloat16"}: | |
| print("[WARN] CPU์์๋ float16/bfloat16์ด ๋ถ์์ ํ ์ ์์ด float32๋ก ๋ณ๊ฒฝํฉ๋๋ค.") | |
| return torch.float32 | |
| return dtype_map[TORCH_DTYPE] | |
| def normalize_caption(text: str) -> str: | |
| text = text.strip() | |
| text = re.sub(r"\s+", " ", text) | |
| return text | |
| def deduplicate_captions(captions: List[str]) -> List[str]: | |
| result = [] | |
| seen = set() | |
| for caption in captions: | |
| caption = normalize_caption(caption) | |
| if not caption: | |
| continue | |
| key = caption.lower() | |
| if key in seen: | |
| continue | |
| seen.add(key) | |
| result.append(caption) | |
| return result | |
| def ensure_caption_count(captions: List[str], target_count: int) -> List[str]: | |
| captions = deduplicate_captions(captions) | |
| if len(captions) >= target_count: | |
| return captions[:target_count] | |
| if len(captions) == 0: | |
| return [""] * target_count | |
| while len(captions) < target_count: | |
| captions.append(captions[-1]) | |
| return captions | |
| def save_json(path: Path, data: List[dict]) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| with path.open("w", encoding="utf-8") as f: | |
| json.dump(data, f, ensure_ascii=False, indent=2) | |
| def load_existing_json(path: Path) -> Dict[str, dict]: | |
| if not path.exists(): | |
| return {} | |
| with path.open("r", encoding="utf-8") as f: | |
| data = json.load(f) | |
| result = {} | |
| for item in data: | |
| image_key = item.get("image") | |
| if image_key: | |
| result[image_key] = item | |
| return result | |
| # ============================================================ | |
| # 4. ์ด๋ฏธ์ง ์์ง | |
| # ============================================================ | |
| def collect_images(input_path: Path, data_raw_root: Path) -> List[ImageItem]: | |
| if not input_path.exists(): | |
| raise FileNotFoundError(f"์ ๋ ฅ ๊ฒฝ๋ก๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค: {input_path}") | |
| image_paths = sorted([ | |
| path | |
| for path in input_path.rglob("*") | |
| if path.is_file() and path.suffix.lower() in SUPPORTED_EXTENSIONS | |
| ]) | |
| if not image_paths: | |
| raise RuntimeError(f"์ด๋ฏธ์ง๋ฅผ ์ฐพ์ง ๋ชปํ์ต๋๋ค: {input_path}") | |
| items = [] | |
| for image_path in image_paths: | |
| try: | |
| relative_path = image_path.relative_to(data_raw_root) | |
| except ValueError: | |
| raise ValueError( | |
| f"์ด๋ฏธ์ง ๊ฒฝ๋ก๊ฐ DATA_RAW_ROOT ํ์์ ์์ด์ผ ํฉ๋๋ค.\n" | |
| f"image_path={image_path}\n" | |
| f"DATA_RAW_ROOT={data_raw_root}" | |
| ) | |
| if len(relative_path.parts) < 2: | |
| raise ValueError( | |
| f"์ด๋ฏธ์ง๋ ํด๋์ค ํด๋ ํ์์ ์์ด์ผ ํฉ๋๋ค: {image_path}\n" | |
| f"์: data/raw/pizza/hf_pizza_001.jpg" | |
| ) | |
| class_name = relative_path.parts[0] | |
| image_field = relative_path.as_posix() | |
| items.append( | |
| ImageItem( | |
| path=image_path, | |
| image_field=image_field, | |
| class_name=class_name, | |
| ) | |
| ) | |
| return items | |
| # ============================================================ | |
| # 5. split ๋ถ๋ฆฌ | |
| # ============================================================ | |
| def calculate_split_counts(total_count: int) -> Dict[str, int]: | |
| ratio_sum = sum(SPLIT_RATIO.values()) | |
| raw_counts = { | |
| split_name: total_count * ratio / ratio_sum | |
| for split_name, ratio in SPLIT_RATIO.items() | |
| } | |
| counts = { | |
| split_name: int(math.floor(count)) | |
| for split_name, count in raw_counts.items() | |
| } | |
| remaining = total_count - sum(counts.values()) | |
| # ์์์ ์ด ํฐ split๋ถํฐ ๋จ์ ๊ฐ์ ๋ฐฐ๋ถ | |
| sorted_splits = sorted( | |
| raw_counts.keys(), | |
| key=lambda split_name: raw_counts[split_name] - counts[split_name], | |
| reverse=True, | |
| ) | |
| for split_name in sorted_splits[:remaining]: | |
| counts[split_name] += 1 | |
| return counts | |
| def assign_splits(items: List[ImageItem]) -> List[ImageItem]: | |
| rng = random.Random(RANDOM_SEED) | |
| class_map = defaultdict(list) | |
| for item in items: | |
| class_map[item.class_name].append(item) | |
| for class_name, class_items in class_map.items(): | |
| rng.shuffle(class_items) | |
| counts = calculate_split_counts(len(class_items)) | |
| start = 0 | |
| for split_name in ["train", "val", "test"]: | |
| end = start + counts.get(split_name, 0) | |
| for item in class_items[start:end]: | |
| item.split = split_name | |
| start = end | |
| return items | |
| # ============================================================ | |
| # 6. ๋ชจ๋ธ ๋ก๋ | |
| # ============================================================ | |
| def load_model(): | |
| device = resolve_device() | |
| torch_dtype = resolve_dtype(device) | |
| print(f"[INFO] device={device}") | |
| print(f"[INFO] dtype={torch_dtype}") | |
| print(f"[INFO] model={MODEL_NAME}") | |
| processor = AutoProcessor.from_pretrained(MODEL_NAME, token=hf_token) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| MODEL_NAME, | |
| dtype=torch_dtype, | |
| token=hf_token | |
| ) | |
| model.to(device) | |
| model.eval() | |
| return model, processor, device, torch_dtype | |
| # ============================================================ | |
| # 7. ์บก์ ๋ | |
| # ============================================================ | |
| def load_batch_images(batch_items: List[ImageItem]) -> Tuple[List[Image.Image], List[ImageItem], List[dict]]: | |
| images = [] | |
| valid_items = [] | |
| errors = [] | |
| for item in batch_items: | |
| try: | |
| with Image.open(item.path) as img: | |
| images.append(img.convert("RGB")) | |
| valid_items.append(item) | |
| except Exception as e: | |
| errors.append({ | |
| "image": item.image_field, | |
| "class": item.class_name, | |
| "split": item.split, | |
| "error": str(e), | |
| }) | |
| return images, valid_items, errors | |
| def generate_batch_captions( | |
| model, | |
| processor, | |
| device: torch.device, | |
| torch_dtype: torch.dtype, | |
| images: List[Image.Image], | |
| ) -> List[List[str]]: | |
| inputs = processor(images=images, return_tensors="pt") | |
| inputs = { | |
| key: value.to(device) | |
| for key, value in inputs.items() | |
| } | |
| if "pixel_values" in inputs: | |
| inputs["pixel_values"] = inputs["pixel_values"].to(dtype=torch_dtype) | |
| generated_ids = model.generate( | |
| **inputs, | |
| **GENERATION_CONFIG, | |
| ) | |
| decoded = processor.batch_decode( | |
| generated_ids, | |
| skip_special_tokens=True, | |
| ) | |
| grouped_captions = [] | |
| for i in range(len(images)): | |
| start = i * CAPTIONS_PER_IMAGE | |
| end = start + CAPTIONS_PER_IMAGE | |
| captions = decoded[start:end] | |
| captions = deduplicate_captions(captions) | |
| grouped_captions.append(captions) | |
| return grouped_captions | |
| def generate_sampling_fallback_captions( | |
| model, | |
| processor, | |
| device: torch.device, | |
| torch_dtype: torch.dtype, | |
| image: Image.Image, | |
| ) -> List[str]: | |
| inputs = processor(images=[image], return_tensors="pt") | |
| inputs = { | |
| key: value.to(device) | |
| for key, value in inputs.items() | |
| } | |
| if "pixel_values" in inputs: | |
| inputs["pixel_values"] = inputs["pixel_values"].to(dtype=torch_dtype) | |
| generated_ids = model.generate( | |
| **inputs, | |
| **SAMPLING_FALLBACK_CONFIG, | |
| ) | |
| decoded = processor.batch_decode( | |
| generated_ids, | |
| skip_special_tokens=True, | |
| ) | |
| return deduplicate_captions(decoded) | |
| def make_result_item(item: ImageItem, captions: List[str]) -> dict: | |
| return { | |
| "image": item.image_field, | |
| "class": item.class_name, | |
| "captions": captions, | |
| "split": item.split, | |
| } | |
| def caption_images( | |
| model, | |
| processor, | |
| device: torch.device, | |
| torch_dtype: torch.dtype, | |
| items: List[ImageItem], | |
| existing_result_map: Dict[str, dict], | |
| ) -> Tuple[Dict[str, dict], List[dict]]: | |
| result_map = dict(existing_result_map) | |
| error_list = [] | |
| target_items = [ | |
| item | |
| for item in items | |
| if item.image_field not in result_map | |
| ] | |
| print(f"[INFO] ์ ์ฒด ์ด๋ฏธ์ง ์: {len(items)}") | |
| print(f"[INFO] ๊ธฐ์กด ๊ฒฐ๊ณผ ์: {len(existing_result_map)}") | |
| print(f"[INFO] ์๋ก ์บก์ ๋ํ ์ด๋ฏธ์ง ์: {len(target_items)}") | |
| processed_count = 0 | |
| for batch_start in tqdm(range(0, len(target_items), BATCH_SIZE), desc="Captioning"): | |
| batch_items = target_items[batch_start:batch_start + BATCH_SIZE] | |
| images, valid_items, errors = load_batch_images(batch_items) | |
| error_list.extend(errors) | |
| if not images: | |
| continue | |
| try: | |
| batch_captions = generate_batch_captions( | |
| model=model, | |
| processor=processor, | |
| device=device, | |
| torch_dtype=torch_dtype, | |
| images=images, | |
| ) | |
| for image, item, captions in zip(images, valid_items, batch_captions): | |
| if ENABLE_SAMPLING_FALLBACK and len(captions) < CAPTIONS_PER_IMAGE: | |
| fallback_captions = generate_sampling_fallback_captions( | |
| model=model, | |
| processor=processor, | |
| device=device, | |
| torch_dtype=torch_dtype, | |
| image=image, | |
| ) | |
| captions = deduplicate_captions(captions + fallback_captions) | |
| captions = ensure_caption_count( | |
| captions=captions, | |
| target_count=CAPTIONS_PER_IMAGE, | |
| ) | |
| result_map[item.image_field] = make_result_item( | |
| item=item, | |
| captions=captions, | |
| ) | |
| processed_count += 1 | |
| except Exception as e: | |
| print("[ERROR] ๋ฐฐ์น ์บก์ ๋ ์คํจ") | |
| print(f"[ERROR] {type(e).__name__}: {e}") | |
| for item in valid_items: | |
| error_list.append({ | |
| "image": item.image_field, | |
| "class": item.class_name, | |
| "split": item.split, | |
| "error": str(e), | |
| }) | |
| if SAVE_EVERY_N_IMAGES > 0 and processed_count > 0: | |
| if processed_count % SAVE_EVERY_N_IMAGES == 0: | |
| current_results = [ | |
| result_map[item.image_field] | |
| for item in items | |
| if item.image_field in result_map | |
| ] | |
| save_json(Path(OUTPUT_JSON_PATH), current_results) | |
| save_json(Path(ERROR_JSON_PATH), error_list) | |
| return result_map, error_list | |
| # ============================================================ | |
| # 8. main | |
| # ============================================================ | |
| def main(): | |
| input_path = Path(INPUT_IMAGE_PATH).resolve() | |
| data_raw_root = Path(DATA_RAW_ROOT).resolve() | |
| output_json_path = Path(OUTPUT_JSON_PATH) | |
| error_json_path = Path(ERROR_JSON_PATH) | |
| items = collect_images( | |
| input_path=input_path, | |
| data_raw_root=data_raw_root, | |
| ) | |
| items = assign_splits(items) | |
| existing_result_map = {} | |
| if RESUME_FROM_EXISTING_JSON: | |
| existing_result_map = load_existing_json(output_json_path) | |
| model, processor, device, torch_dtype = load_model() | |
| result_map, error_list = caption_images( | |
| model=model, | |
| processor=processor, | |
| device=device, | |
| torch_dtype=torch_dtype, | |
| items=items, | |
| existing_result_map=existing_result_map, | |
| ) | |
| final_results = [ | |
| result_map[item.image_field] | |
| for item in items | |
| if item.image_field in result_map | |
| ] | |
| save_json(output_json_path, final_results) | |
| save_json(error_json_path, error_list) | |
| print("[DONE] ์บก์ ๋ ์๋ฃ") | |
| print(f"[DONE] ๊ฒฐ๊ณผ ์ ์ฅ: {output_json_path}") | |
| print(f"[DONE] ์๋ฌ ์ ์ฅ: {error_json_path}") | |
| print(f"[DONE] ์ ์ ๊ฒฐ๊ณผ ์: {len(final_results)}") | |
| print(f"[DONE] ์๋ฌ ์: {len(error_list)}") | |
| if __name__ == "__main__": | |
| main() |