| """ |
| 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() |
|
|