multimodalart HF Staff commited on
Commit
623fea3
·
verified ·
1 Parent(s): 77db6d1

Upload caption.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. caption.py +154 -0
caption.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AI captioning + trigger suggestion for the Krea 2 LoRA trainer Space.
2
+
3
+ Runs on the Space itself (cpu-basic) by calling the HF Inference API for a multimodal LLM
4
+ (`google/gemma-4-31B-it`, served with vision by the **novita** provider — the default `auto`
5
+ route lands on an endpoint that returns empty text, so the provider is pinned).
6
+
7
+ The captioning token (`CAPTION_HF_TOKEN` secret) only ever calls the Inference API. It is
8
+ independent of the user's OAuth token (push/dataset) and the gated `KREA_TOKEN` (Krea weights).
9
+
10
+ Caption recipe follows the Krea 2 authors' training guidance:
11
+ * STYLE LoRA — describe only the *content* (subjects, poses, layout, setting), never the
12
+ medium/technique/palette, then append the style trigger phrase (e.g. ", heavy impasto style").
13
+ * OBJECT/CHARACTER LoRA — describe the scene with the subject referred to by its class noun,
14
+ then append a unique trigger token (e.g. " b3@rcup").
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import base64
20
+ import io
21
+ import os
22
+
23
+ from huggingface_hub import InferenceClient
24
+ from PIL import Image
25
+
26
+ CAPTION_MODEL = "google/gemma-4-31B-it"
27
+ CAPTION_PROVIDER = "novita"
28
+ _MAX_SIDE = 768 # downscale before upload to keep the request small / fast
29
+
30
+ # Few-shot exemplars taken from the authors' reference captions (content only — the trigger is
31
+ # appended programmatically, so the examples here deliberately omit the trailing trigger).
32
+ _STYLE_EXAMPLES = [
33
+ "A person is running forward in profile. The figure leans into the motion with their head "
34
+ "tilted slightly down and long hair trailing horizontally behind. The arms are bent at the "
35
+ "elbows, with one arm swung forward and the other pulled back toward the hip. One leg is "
36
+ "extended backward, capturing a mid-stride movement. The figure is positioned centrally in a "
37
+ "void of plain white.",
38
+ "A fishing boat is stationed in a narrow canal between rows of multi-story buildings. The boat "
39
+ "features a central cabin with windows and two vertical masts extending upwards. A red buoy "
40
+ "hangs from the side of the hull. The water in the canal occupies the lower portion of the "
41
+ "scene, while the sky is visible above the rooflines of the structures.",
42
+ "A black sports car is positioned in the center of a wet road through a dense forest. The car "
43
+ "faces forward, with its round headlights visible. The road surface is covered in puddles that "
44
+ "reflect the front end. Tall coniferous trees line both sides of the road and a dense fog fills "
45
+ "the space between the trees behind the vehicle.",
46
+ ]
47
+ _OBJECT_EXAMPLES = [
48
+ "A cup, sitting on a grainy wooden table with a grey door in the background. An iron stand has "
49
+ "grey and black plastic containers in separate piles.",
50
+ "A cup being held by a woman in her hand in the outdoors. The background is a textured patch of "
51
+ "lawn grass.",
52
+ ]
53
+
54
+
55
+ def _token() -> str:
56
+ tok = os.environ.get("CAPTION_HF_TOKEN") or os.environ.get("HF_TOKEN") or ""
57
+ if not tok:
58
+ raise RuntimeError("AI captioning is unavailable: the CAPTION_HF_TOKEN secret is not set.")
59
+ return tok
60
+
61
+
62
+ def _client() -> InferenceClient:
63
+ return InferenceClient(model=CAPTION_MODEL, provider=CAPTION_PROVIDER, token=_token())
64
+
65
+
66
+ def _data_url(path: str) -> str:
67
+ img = Image.open(path).convert("RGB")
68
+ img.thumbnail((_MAX_SIDE, _MAX_SIDE))
69
+ buf = io.BytesIO()
70
+ img.save(buf, "JPEG", quality=90)
71
+ return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode()
72
+
73
+
74
+ def _ask(instruction: str, image_paths: list[str], max_tokens: int = 320,
75
+ temperature: float = 0.4) -> str:
76
+ content: list[dict] = [{"type": "text", "text": instruction}]
77
+ for p in image_paths:
78
+ content.append({"type": "image_url", "image_url": {"url": _data_url(p)}})
79
+ r = _client().chat_completion(
80
+ messages=[{"role": "user", "content": content}],
81
+ max_tokens=max_tokens, temperature=temperature,
82
+ )
83
+ return (r.choices[0].message.content or "").strip()
84
+
85
+
86
+ def _clean(text: str) -> str:
87
+ """Strip wrapping quotes / a leading 'Caption:' the model sometimes adds."""
88
+ t = text.strip().strip('"').strip("'").strip()
89
+ for prefix in ("Caption:", "caption:", "Trigger:", "trigger:"):
90
+ if t.startswith(prefix):
91
+ t = t[len(prefix):].strip()
92
+ return t.rstrip()
93
+
94
+
95
+ def caption_one(image_path: str, concept_type: str, trigger: str) -> str:
96
+ """Caption a single image for the given concept type, appending the trigger."""
97
+ trigger = (trigger or "").strip()
98
+ if concept_type == "style":
99
+ instruction = (
100
+ "You are writing a training caption for a STYLE LoRA. Describe ONLY the literal "
101
+ "content of the image: the subjects, their poses and actions, the key objects, their "
102
+ "spatial arrangement, and the setting or background. Write 2-4 plain declarative "
103
+ "sentences. Do NOT mention the artistic style, medium, technique, brushwork, lighting "
104
+ "mood or palette, and do NOT use words like painting, illustration, drawing, render, "
105
+ "sketch or photo. Match the tone of these examples:\n\n"
106
+ + "\n\n".join(_STYLE_EXAMPLES)
107
+ + "\n\nReturn only the caption sentence(s), with no preamble, labels or quotes."
108
+ )
109
+ cap = _clean(_ask(instruction, [image_path]))
110
+ if trigger:
111
+ cap = f"{cap.rstrip('.')}, {trigger}" if cap else trigger
112
+ return cap
113
+ # object / character
114
+ instruction = (
115
+ "You are writing a training caption for a LoRA of one specific subject. Describe the "
116
+ "scene: where the subject is, what it is doing or how it is positioned, and the background "
117
+ "or setting. Refer to the subject by its generic class noun (e.g. 'a cup', 'a dog'), never "
118
+ "by a name. Write 1-3 plain declarative sentences. Match the tone of these examples:\n\n"
119
+ + "\n\n".join(_OBJECT_EXAMPLES)
120
+ + "\n\nReturn only the caption sentence(s), with no preamble, labels or quotes."
121
+ )
122
+ cap = _clean(_ask(instruction, [image_path]))
123
+ if trigger:
124
+ cap = f"{cap} {trigger}" if cap else trigger
125
+ return cap
126
+
127
+
128
+ def suggest_trigger(image_paths: list[str], concept_type: str) -> str:
129
+ """Suggest a trigger from 2-3 sample images: a style phrase, or a unique object token."""
130
+ sample = list(image_paths)[:3]
131
+ if not sample:
132
+ raise gr_error("Upload images first.")
133
+ if concept_type == "style":
134
+ instruction = (
135
+ "These images share one artistic style. Propose a SHORT distinctive trigger phrase "
136
+ "naming that style: 2 to 5 words, ending with the word 'style'. Examples: 'heavy "
137
+ "impasto style', 'monochrome ink wash style', 'flat pastel vector style'. Return only "
138
+ "the phrase in lowercase, with no quotes or explanation."
139
+ )
140
+ return _clean(_ask(instruction, sample, max_tokens=24, temperature=0.6)).lower()
141
+ instruction = (
142
+ "These images show one specific subject. Propose a SHORT unique trigger for it: a rare "
143
+ "made-up token, optionally followed by its class noun. Examples: 'b3@rcup', 'sks dog', "
144
+ "'zxy sneaker'. Return only the trigger, with no quotes or explanation."
145
+ )
146
+ return _clean(_ask(instruction, sample, max_tokens=16, temperature=0.7))
147
+
148
+
149
+ def gr_error(msg: str): # tiny indirection so this module stays importable without gradio
150
+ try:
151
+ import gradio as gr # noqa: PLC0415
152
+ return gr.Error(msg)
153
+ except Exception: # noqa: BLE001
154
+ return ValueError(msg)