Spaces:
Running on Zero
Running on Zero
Download caption.py from Jayasurya23/photo-culling: direct link, hf CLI and curl.
- Browser
- Download file 9.67 kB
-
https://huggingface.co/spaces/Jayasurya23/photo-culling/resolve/main/caption.py
- Command line
-
hf download hf://spaces/Jayasurya23/photo-culling/caption.py
-
curl -L -o caption.py https://huggingface.co/spaces/Jayasurya23/photo-culling/resolve/main/caption.py
9.67 kB
| """Step 5 - Instagram captions from a local Ollama VLM, cached per image id. | |
| Fully offline: no API key, no network beyond localhost. | |
| """ | |
| import base64, io, json, logging, os | |
| from pathlib import Path | |
| import requests | |
| from PIL import Image | |
| from config import (CACHE_DIR, CAPTION_BACKEND, CAPTION_CACHE, CAPTION_MAX_EDGE, | |
| CAPTION_MAX_TOKENS, OLLAMA_MODEL, OLLAMA_TIMEOUT, OLLAMA_URL, | |
| OPENAI_MODEL, OPENAI_TIMEOUT) | |
| from ingest import exif_line | |
| log = logging.getLogger(__name__) | |
| # Small local models follow instructions less reliably than a frontier API, so the | |
| # prompt is short, names the keys inline, and decoding is constrained with format=json. | |
| # Getting structured output from a 3B model took three attempts, and both failure modes | |
| # are worth recording: | |
| # 1. An empty template ("hashtags":[], "alt_text":"") -> the model copied the empty | |
| # values back, so every photo returned no tags and no alt text. | |
| # 2. A filled-in example -> the model copied the EXAMPLE's content verbatim, so every | |
| # photo got the same sunset caption regardless of what was in the frame. | |
| # The fix is to stop showing examples at all and constrain the shape with a JSON schema | |
| # passed to Ollama's `format`. Structure is enforced by the decoder; content stays free. | |
| SCHEMA = { | |
| "type": "object", | |
| "properties": { | |
| "captions": { | |
| "type": "array", "minItems": 3, "maxItems": 3, | |
| "items": { | |
| "type": "object", | |
| "properties": {"style": {"type": "string", "enum": ["witty", "descriptive", "minimal"]}, | |
| "text": {"type": "string"}}, | |
| "required": ["style", "text"], | |
| }, | |
| }, | |
| "hashtags": {"type": "array", "minItems": 6, "maxItems": 12, | |
| "items": {"type": "string"}}, | |
| "alt_text": {"type": "string"}, | |
| }, | |
| "required": ["captions", "hashtags", "alt_text"], | |
| } | |
| PROMPT = ( | |
| "Look at this photograph and write Instagram captions for it.\n" | |
| "EXIF: {exif}\n{context}" | |
| "Base everything on what is actually visible in this specific image - the people, " | |
| "setting, clothing, light and mood you can see. Do not describe a generic scene.\n" | |
| "Provide three captions: one witty, one descriptive, one minimal. " | |
| "Then 6-12 relevant hashtags, and one sentence of alt text." | |
| ) | |
| RETRY_PROMPT = ( | |
| "Describe this specific photograph: who or what is in it, where it appears to be, " | |
| "and the mood. Then give three Instagram captions (witty, descriptive, minimal), " | |
| "6-12 hashtags, and one sentence of alt text." | |
| ) | |
| def check_ollama() -> tuple[bool, str]: | |
| """Health check for the local backend. Returns (ok, message).""" | |
| try: | |
| r = requests.get(f"{OLLAMA_URL}/api/tags", timeout=5) | |
| r.raise_for_status() | |
| tags = [m["name"] for m in r.json().get("models", [])] | |
| except Exception: | |
| return False, f"Ollama is not reachable at {OLLAMA_URL} - start it with `ollama serve`." | |
| if not any(t.split(":")[0] == OLLAMA_MODEL.split(":")[0] for t in tags): | |
| return False, f"Ollama is running but `{OLLAMA_MODEL}` is not pulled. Installed: {', '.join(tags) or 'none'}" | |
| return True, f"Ollama ready - {OLLAMA_MODEL}" | |
| def check_openai() -> tuple[bool, str]: | |
| """Health check for the hosted backend. Never logs or returns the key itself.""" | |
| key = os.environ.get("OPENAI_API_KEY", "").strip() | |
| if not key: | |
| return False, "OPENAI_API_KEY is not set - export it (never paste it into the app)." | |
| # A copied-but-unedited .env passes a bare truthiness test and then fails at the | |
| # API with a confusing 401, so reject the template value explicitly. | |
| if "replace-me" in key or key == "sk-proj-replace-me": | |
| return False, ("OPENAI_API_KEY is still the placeholder from .env.example - " | |
| "paste your real key into .env.") | |
| if len(key) < 40: | |
| return False, (f"OPENAI_API_KEY looks too short ({len(key)} chars) - " | |
| "check .env has the full key on one line.") | |
| try: | |
| import openai # noqa: F401 | |
| except ImportError: | |
| return False, "The `openai` package is not installed - pip install openai" | |
| return True, f"OpenAI ready - {OPENAI_MODEL}" | |
| def check_backend() -> tuple[bool, str]: | |
| """Health check for whichever backend is configured.""" | |
| if CAPTION_BACKEND == "openai": | |
| return check_openai() | |
| if CAPTION_BACKEND == "ollama": | |
| return check_ollama() | |
| return False, f"Unknown CAPTION_BACKEND `{CAPTION_BACKEND}` - expected 'ollama' or 'openai'." | |
| def _cache() -> dict: | |
| if CAPTION_CACHE.exists(): | |
| try: | |
| return json.loads(CAPTION_CACHE.read_text()) | |
| except Exception: | |
| log.warning("Caption cache unreadable - starting fresh") | |
| return {} | |
| def _save(cache: dict) -> None: | |
| CACHE_DIR.mkdir(parents=True, exist_ok=True) | |
| CAPTION_CACHE.write_text(json.dumps(cache, indent=2)) | |
| def _parse(text: str) -> dict: | |
| body = text.strip() | |
| if body.startswith("```"): # strip markdown fences | |
| body = body.split("```")[1] | |
| body = body[4:] if body.lower().startswith("json") else body | |
| start, end = body.find("{"), body.rfind("}") | |
| return json.loads(body[start:end + 1]) | |
| def _encode(proxy_path: str) -> str: | |
| """Qwen2.5-VL tokenises at native resolution, so the image size drives most of the | |
| latency. Downscaling the 512px proxy before sending cuts visual tokens sharply and | |
| costs nothing for caption quality - the model only needs the gist of the scene. | |
| """ | |
| im = Image.open(proxy_path).convert("RGB") | |
| im.thumbnail((CAPTION_MAX_EDGE, CAPTION_MAX_EDGE), Image.LANCZOS) | |
| buf = io.BytesIO() | |
| im.save(buf, "JPEG", quality=85) | |
| return base64.b64encode(buf.getvalue()).decode() | |
| def _call_ollama(b64: str, prompt: str) -> dict: | |
| r = requests.post( | |
| f"{OLLAMA_URL}/api/generate", | |
| json={"model": OLLAMA_MODEL, "prompt": prompt, "images": [b64], | |
| "stream": False, "format": SCHEMA, | |
| "options": {"num_predict": CAPTION_MAX_TOKENS, "temperature": 0.7}}, | |
| timeout=OLLAMA_TIMEOUT, | |
| ) | |
| r.raise_for_status() | |
| return _parse(r.json()["response"]) | |
| def _openai_schema() -> dict: | |
| """OpenAI's strict json_schema mode requires additionalProperties:false on every | |
| object and every property listed in `required`. The base SCHEMA is written for | |
| Ollama, which doesn't care, so tighten a copy rather than complicating the original.""" | |
| import copy | |
| s = copy.deepcopy(SCHEMA) | |
| s["additionalProperties"] = False | |
| item = s["properties"]["captions"]["items"] | |
| item["additionalProperties"] = False | |
| return s | |
| def _call_openai(b64: str, prompt: str) -> dict: | |
| """Reads OPENAI_API_KEY from the environment. The key is never logged, cached, | |
| or written to disk - only the generated captions are.""" | |
| from openai import OpenAI | |
| client = OpenAI(timeout=OPENAI_TIMEOUT) | |
| kwargs = { | |
| "model": OPENAI_MODEL, | |
| "max_completion_tokens": CAPTION_MAX_TOKENS, | |
| "messages": [{"role": "user", "content": [ | |
| {"type": "text", "text": prompt}, | |
| {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64}"}}, | |
| ]}], | |
| } | |
| try: | |
| r = client.chat.completions.create( | |
| response_format={"type": "json_schema", "json_schema": { | |
| "name": "instagram_captions", "strict": True, "schema": _openai_schema()}}, | |
| **kwargs, | |
| ) | |
| except Exception as exc: | |
| # Older or non-4o-family models reject strict json_schema; json_object is the | |
| # widely supported fallback, and _parse() already tolerates loose output. | |
| log.warning("json_schema mode rejected (%s) - retrying with json_object", exc) | |
| r = client.chat.completions.create(response_format={"type": "json_object"}, **kwargs) | |
| return _parse(r.choices[0].message.content) | |
| def _call(b64: str, prompt: str) -> dict: | |
| if CAPTION_BACKEND == "openai": | |
| return _call_openai(b64, prompt) | |
| return _call_ollama(b64, prompt) | |
| def generate_captions(row, context_prompt: str = "", force: bool = False) -> dict: | |
| key = str(row["id"]) | |
| cache = _cache() | |
| if not force and key in cache: | |
| return cache[key] | |
| ok, msg = check_backend() | |
| if not ok: | |
| return {"error": msg} | |
| b64 = _encode(row["proxy_path"]) | |
| prompt = PROMPT.format( | |
| exif=exif_line(row), | |
| context=f"Shoot context: {context_prompt.strip()}\n" if context_prompt.strip() else "", | |
| ) | |
| try: | |
| raw = _call(b64, prompt) | |
| except Exception as exc: | |
| log.warning("Caption attempt 1 failed for %s: %s - retrying tersely", key, exc) | |
| try: | |
| raw = _call(b64, RETRY_PROMPT) | |
| except Exception as exc2: | |
| log.warning("Caption retry failed for %s: %s", key, exc2) | |
| return {"error": f"Caption failed: {exc2}"} | |
| # the model is inconsistent about the leading '#', so normalise rather than re-prompt | |
| tags = [] | |
| for t in raw.get("hashtags", []): | |
| t = str(t).strip().lstrip("#").replace(" ", "") | |
| if t: | |
| tags.append("#" + t) | |
| result = {"captions": raw.get("captions", [])[:3], | |
| "hashtags": tags, | |
| "alt_text": raw.get("alt_text", "")} | |
| cache[key] = result | |
| _save(cache) | |
| return result | |