File size: 4,641 Bytes
b373569
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Caption images using Anthropic Claude Opus 4.6 API.
Generates detailed descriptions for fine-tuning Flux.
"""
import os
import json
import base64
import argparse
import time
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed

import anthropic
from tqdm import tqdm

INPUT_DIR = Path("/home/adminuser/chungcat/data/raw/unsplash")
OUTPUT_DIR = Path("/home/adminuser/chungcat/data/captions")

CAPTION_PROMPT = """Describe this image in detail for an AI image generation model. Include:
- Main subject and composition
- Colors, lighting, mood
- Style (photographic, artistic, etc.)
- Important details and textures
- Background elements

Write a single detailed paragraph, 2-4 sentences. Be specific and descriptive."""


def encode_image(image_path):
    with open(image_path, "rb") as f:
        return base64.standard_b64encode(f.read()).decode("utf-8")


def caption_image(client, image_path, model="claude-opus-4-6-20250219"):
    img_data = encode_image(image_path)
    suffix = image_path.suffix.lower()
    media_type = "image/jpeg" if suffix in [".jpg", ".jpeg"] else "image/png"

    response = client.messages.create(
        model=model,
        max_tokens=300,
        messages=[
            {
                "role": "user",
                "content": [
                    {
                        "type": "image",
                        "source": {
                            "type": "base64",
                            "media_type": media_type,
                            "data": img_data,
                        },
                    },
                    {"type": "text", "text": CAPTION_PROMPT},
                ],
            }
        ],
    )
    return response.content[0].text


def process_batch(client, images, output_dir, model, max_retries=3):
    results = []
    for img_path in images:
        output_path = output_dir / f"{img_path.stem}.json"
        if output_path.exists():
            continue

        for attempt in range(max_retries):
            try:
                caption = caption_image(client, img_path, model)
                result = {
                    "image": str(img_path),
                    "caption": caption,
                    "filename": img_path.name,
                }
                output_path.write_text(json.dumps(result, ensure_ascii=False))
                results.append(result)
                break
            except anthropic.RateLimitError:
                time.sleep(2 ** attempt)
            except Exception as e:
                print(f"Error {img_path.name}: {e}")
                if attempt == max_retries - 1:
                    print(f"  Skipping after {max_retries} retries")
                time.sleep(1)

    return results


def main():
    parser = argparse.ArgumentParser(description="Caption images with Claude Opus")
    parser.add_argument("--input-dir", type=Path, default=INPUT_DIR)
    parser.add_argument("--output-dir", type=Path, default=OUTPUT_DIR)
    parser.add_argument("--model", default="claude-opus-4-6-20250219")
    parser.add_argument("--batch-size", type=int, default=10)
    parser.add_argument("--workers", type=int, default=5)
    parser.add_argument("--max-images", type=int, default=None)
    args = parser.parse_args()

    api_key = os.environ.get("ANTHROPIC_API_KEY")
    if not api_key:
        raise ValueError("Set ANTHROPIC_API_KEY environment variable")

    client = anthropic.Anthropic(api_key=api_key)
    args.output_dir.mkdir(parents=True, exist_ok=True)

    images = sorted(args.input_dir.glob("*.jpg")) + sorted(args.input_dir.glob("*.png"))
    if args.max_images:
        images = images[:args.max_images]

    already_done = len(list(args.output_dir.glob("*.json")))
    images = [img for img in images if not (args.output_dir / f"{img.stem}.json").exists()]

    print(f"Total images: {len(images) + already_done}")
    print(f"Already captioned: {already_done}")
    print(f"To caption: {len(images)}")

    batches = [images[i:i+args.batch_size] for i in range(0, len(images), args.batch_size)]

    total_captioned = 0
    with ThreadPoolExecutor(max_workers=args.workers) as executor:
        futures = [
            executor.submit(process_batch, client, batch, args.output_dir, args.model)
            for batch in batches
        ]
        for future in tqdm(as_completed(futures), total=len(futures)):
            results = future.result()
            total_captioned += len(results)

    print(f"\nDone! Captioned {total_captioned} new images")
    print(f"Total captions: {already_done + total_captioned}")


if __name__ == "__main__":
    main()