dsadaq commited on
Commit
7ca24bc
·
verified ·
1 Parent(s): 7b2011e

Upload hintgenerate_gemma2.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. hintgenerate_gemma2.py +1055 -0
hintgenerate_gemma2.py ADDED
@@ -0,0 +1,1055 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ Gemma-based hint generation entrypoint.
6
+
7
+ This is a dedicated wrapper around `hintgenerate.py` with Gemma-local defaults.
8
+ It keeps the same processing pipeline and most CLI flags, but changes:
9
+
10
+ 1. default `--model-name` to the provided Gemma checkpoint
11
+ 2. local HF loader preference for Gemma-family models
12
+ 3. default `--workers` to 1 for local inference stability
13
+
14
+ Example:
15
+
16
+ python3 hintgenerate_gemma.py \
17
+ --use-json \
18
+ --json-path /path/to/editing.json \
19
+ --image-root /path/to/images \
20
+ --out-root ./gemma_hint_runs \
21
+ --grid-mode auto \
22
+ --model-max-tokens 4096
23
+ """
24
+
25
+ import argparse
26
+ import copy
27
+ import inspect
28
+ import io
29
+ import os
30
+ import re
31
+ import sys
32
+ from typing import Any, Dict, List, Optional
33
+
34
+ import hintgenerate as hg
35
+
36
+ from hintgenerate import (
37
+ GATEWAY_BASE_URL,
38
+ DEFAULT_TIMEOUT,
39
+ MAX_RETRIES_ENV,
40
+ GeminiGatewayClient,
41
+ KeyedRateLimiter,
42
+ _patch_bitsandbytes_compat,
43
+ _patch_torch_distributed_tensor_compat,
44
+ _patch_torch_module_compat,
45
+ assert_local_openai_server_ready,
46
+ is_local_model_name,
47
+ is_local_openai_base_url,
48
+ logger,
49
+ resolve_model_name,
50
+ run_json_mode,
51
+ run_parquet_mode,
52
+ )
53
+
54
+
55
+ GEMMA_MODEL_PATH = "/mnt/bn/yuanpengtu/svgthink/google/gemma-4-31B-it/"
56
+ _GEMMA_REFINE_ROUNDS = 3
57
+
58
+
59
+ class GemmaHintClient(GeminiGatewayClient):
60
+ """
61
+ Official Gemma 4 local loader.
62
+
63
+ Per the official Hugging Face Gemma 4 docs:
64
+ - processor: AutoProcessor / Gemma4Processor
65
+ - multimodal model: AutoModelForMultimodalLM
66
+ """
67
+
68
+ def __init__(self, *args, local_processor_path: str = "", local_processor_class: str = "", **kwargs):
69
+ self.local_processor_path = str(local_processor_path or "").strip()
70
+ self.local_processor_class = str(local_processor_class or "").strip()
71
+ self.local_device_map = str(kwargs.pop("local_device_map", "auto") or "auto").strip()
72
+ self.local_max_memory_per_gpu_gb = kwargs.pop("local_max_memory_per_gpu_gb", None)
73
+
74
+ sig = inspect.signature(GeminiGatewayClient.__init__)
75
+ allowed = set(sig.parameters.keys()) - {"self"}
76
+ filtered_kwargs = {k: v for k, v in kwargs.items() if k in allowed}
77
+ super().__init__(*args, **filtered_kwargs)
78
+
79
+ # Old hintgenerate.py may not know these attributes.
80
+ self.local_processor_path = str(local_processor_path or getattr(self, "local_processor_path", "")).strip()
81
+ self.local_processor_class = str(local_processor_class or getattr(self, "local_processor_class", "")).strip()
82
+
83
+ def _select_local_loader_candidates(self, transformers_mod):
84
+ auto_multimodal = getattr(transformers_mod, "AutoModelForMultimodalLM", None)
85
+ gemma4_cond = getattr(transformers_mod, "Gemma4ForConditionalGeneration", None)
86
+ auto_image_text = getattr(transformers_mod, "AutoModelForImageTextToText", None)
87
+ auto_vision2seq = getattr(transformers_mod, "AutoModelForVision2Seq", None)
88
+ auto_causal_lm = getattr(transformers_mod, "AutoModelForCausalLM", None)
89
+ auto_model = getattr(transformers_mod, "AutoModel", None)
90
+
91
+ return [
92
+ loader
93
+ for loader in (
94
+ auto_multimodal,
95
+ gemma4_cond,
96
+ auto_image_text,
97
+ auto_vision2seq,
98
+ auto_causal_lm,
99
+ auto_model,
100
+ )
101
+ if loader is not None
102
+ ]
103
+
104
+ def _get_local_processor_candidates(self, transformers_mod):
105
+ proc_path = self.local_processor_path or self.model
106
+ candidates = []
107
+ seen = set()
108
+
109
+ def _push(name: str):
110
+ if not name or name in seen:
111
+ return
112
+ klass = getattr(transformers_mod, name, None)
113
+ if klass is not None:
114
+ candidates.append((name, klass, proc_path))
115
+ seen.add(name)
116
+
117
+ if self.local_processor_class:
118
+ _push(self.local_processor_class)
119
+
120
+ for name in ("Gemma4Processor", "AutoProcessor"):
121
+ _push(name)
122
+
123
+ if candidates:
124
+ return candidates
125
+ return super()._get_local_processor_candidates(transformers_mod)
126
+
127
+ @staticmethod
128
+ def _load_from_pretrained(factory, path: str, trust_remote_code: bool = True, use_fast: Optional[bool] = None):
129
+ kwargs: Dict[str, Any] = {}
130
+ if trust_remote_code:
131
+ kwargs["trust_remote_code"] = True
132
+ if use_fast is not None:
133
+ kwargs["use_fast"] = use_fast
134
+
135
+ try:
136
+ return factory.from_pretrained(path, **kwargs)
137
+ except TypeError:
138
+ kwargs.pop("use_fast", None)
139
+ try:
140
+ return factory.from_pretrained(path, **kwargs)
141
+ except TypeError:
142
+ kwargs.pop("trust_remote_code", None)
143
+ return factory.from_pretrained(path, **kwargs)
144
+
145
+ def _load_local_processor(self, transformers_mod):
146
+ tried = []
147
+ for label, factory, path in self._get_local_processor_candidates(transformers_mod):
148
+ if factory is None or not path:
149
+ continue
150
+ try:
151
+ proc = self._load_from_pretrained(factory, path, trust_remote_code=True, use_fast=None)
152
+ logger.info(f"Loaded local processor via {label}: path={path}")
153
+ return proc
154
+ except Exception as e:
155
+ tried.append(f"{label}@{path}: {e}")
156
+
157
+ dir_snaps = []
158
+ seen_paths = []
159
+ for _, _, path in self._get_local_processor_candidates(transformers_mod):
160
+ if not path or path in seen_paths or not os.path.isdir(path):
161
+ continue
162
+ seen_paths.append(path)
163
+ try:
164
+ names = sorted(os.listdir(path))
165
+ if len(names) > 24:
166
+ names = names[:24] + ["..."]
167
+ dir_snaps.append(f"{path}: {names}")
168
+ except Exception:
169
+ continue
170
+
171
+ detail = "\n".join(f"- {x}" for x in tried) if tried else "- no processor candidates available"
172
+ snapshot = ("\nDirectory snapshot:\n" + "\n".join(dir_snaps)) if dir_snaps else ""
173
+ raise RuntimeError(
174
+ "Failed to load a local processor for official Gemma 4 multimodal inference.\n"
175
+ f"Tried:\n{detail}{snapshot}\n"
176
+ "Use the official Gemma 4 path or model id (for example `google/gemma-4-31B-it`) "
177
+ "with a recent `transformers` version that provides `Gemma4Processor` and "
178
+ "`AutoModelForMultimodalLM`."
179
+ )
180
+
181
+ def _ensure_local_model_loaded(self):
182
+ if self._local_load_error is not None:
183
+ raise self._local_load_error
184
+
185
+ if self._local_model is not None and self._processor is not None:
186
+ return
187
+
188
+ with self._local_lock:
189
+ if self._local_load_error is not None:
190
+ raise self._local_load_error
191
+ if self._local_model is not None and self._processor is not None:
192
+ return
193
+
194
+ try:
195
+ import torch
196
+ import transformers
197
+ except Exception as e:
198
+ raise RuntimeError(
199
+ "Local model mode requires torch and transformers to be installed in this environment."
200
+ ) from e
201
+
202
+ self._torch = torch
203
+ _patch_torch_module_compat(torch)
204
+ _patch_torch_distributed_tensor_compat(torch)
205
+
206
+ if getattr(transformers, "Gemma4Processor", None) is None and getattr(transformers, "AutoProcessor", None) is None:
207
+ raise RuntimeError(
208
+ "This transformers build does not provide Gemma4Processor/AutoProcessor for Gemma 4. "
209
+ "Upgrade transformers to a version with official Gemma 4 support."
210
+ )
211
+
212
+ loader_candidates = self._select_local_loader_candidates(transformers)
213
+ if not loader_candidates:
214
+ version = getattr(transformers, "__version__", "unknown")
215
+ raise RuntimeError(
216
+ "This transformers build does not provide any usable Gemma 4 model loader "
217
+ f"(checked AutoModelForMultimodalLM, Gemma4ForConditionalGeneration, "
218
+ f"AutoModelForImageTextToText, AutoModelForVision2Seq, AutoModelForCausalLM, AutoModel). "
219
+ f"Current transformers version: {version}. "
220
+ "Upgrade transformers to a version with official Gemma 4 support."
221
+ )
222
+
223
+ bits_and_bytes_config = getattr(transformers, "BitsAndBytesConfig", None)
224
+
225
+ model_kwargs: Dict[str, Any] = {
226
+ "trust_remote_code": True,
227
+ "device_map": self.local_device_map or "auto",
228
+ "low_cpu_mem_usage": True,
229
+ }
230
+
231
+ if self.local_max_memory_per_gpu_gb:
232
+ try:
233
+ gpu_count = int(torch.cuda.device_count())
234
+ except Exception:
235
+ gpu_count = 0
236
+ if gpu_count > 0:
237
+ per_gpu = f"{int(self.local_max_memory_per_gpu_gb)}GiB"
238
+ model_kwargs["max_memory"] = {idx: per_gpu for idx in range(gpu_count)}
239
+ model_kwargs["max_memory"]["cpu"] = "256GiB"
240
+
241
+ torch_dtype = self._resolve_local_torch_dtype(torch)
242
+ if torch_dtype is not None:
243
+ model_kwargs["dtype"] = torch_dtype
244
+
245
+ if self.local_load_in_4bit or self.local_load_in_8bit:
246
+ _patch_bitsandbytes_compat()
247
+ if bits_and_bytes_config is None:
248
+ raise RuntimeError("bitsandbytes support requires a recent transformers installation.")
249
+ quant_kwargs = {
250
+ "load_in_4bit": self.local_load_in_4bit,
251
+ "load_in_8bit": self.local_load_in_8bit,
252
+ }
253
+ if self.local_cpu_offload:
254
+ quant_kwargs["llm_int8_enable_fp32_cpu_offload"] = True
255
+ if self.local_load_in_4bit:
256
+ quant_kwargs["bnb_4bit_compute_dtype"] = torch_dtype or torch.bfloat16
257
+ quant_kwargs["bnb_4bit_quant_type"] = "nf4"
258
+ quant_kwargs["bnb_4bit_use_double_quant"] = True
259
+ model_kwargs["quantization_config"] = bits_and_bytes_config(**quant_kwargs)
260
+ model_kwargs.pop("dtype", None)
261
+ if self.local_cpu_offload:
262
+ offload_dir = self.local_offload_dir or os.path.join(os.getcwd(), ".hf_offload")
263
+ os.makedirs(offload_dir, exist_ok=True)
264
+ model_kwargs["offload_folder"] = offload_dir
265
+ model_kwargs["offload_state_dict"] = True
266
+
267
+ self._processor = self._load_local_processor(transformers)
268
+
269
+ last_err = None
270
+ loader_names = [getattr(loader, "__name__", str(loader)) for loader in loader_candidates]
271
+ logger.info(f"Local loader order: {loader_names}")
272
+ for loader in loader_candidates:
273
+ if loader is None:
274
+ continue
275
+ try:
276
+ self._local_model = loader.from_pretrained(self.model, **model_kwargs)
277
+ break
278
+ except Exception as e:
279
+ last_err = e
280
+
281
+ if self._local_model is None:
282
+ self._local_load_error = last_err or RuntimeError("unknown local model load error")
283
+ raise RuntimeError(f"Failed to load local model from {self.model}: {last_err}") from last_err
284
+
285
+ self._local_model.eval()
286
+ self._local_load_error = None
287
+
288
+ if hasattr(self._local_model, "hf_device_map"):
289
+ for dev in self._local_model.hf_device_map.values():
290
+ if dev not in ("cpu", "disk", "meta"):
291
+ if isinstance(dev, int):
292
+ dev = f"cuda:{dev}"
293
+ self._local_input_device = dev
294
+ break
295
+
296
+ if self._local_input_device is None:
297
+ model_device = getattr(self._local_model, "device", None)
298
+ if model_device is not None:
299
+ if isinstance(model_device, int):
300
+ model_device = f"cuda:{model_device}"
301
+ self._local_input_device = model_device
302
+
303
+ gpu_count = 0
304
+ try:
305
+ gpu_count = int(torch.cuda.device_count())
306
+ except Exception:
307
+ gpu_count = 0
308
+ logger.info(
309
+ f"Loaded local HF model: model={self.model} "
310
+ f"dtype={self.local_dtype} 4bit={self.local_load_in_4bit} 8bit={self.local_load_in_8bit} "
311
+ f"device_map={self.local_device_map or 'auto'} visible_gpus={gpu_count} "
312
+ f"cpu_offload={self.local_cpu_offload} offload_dir={self.local_offload_dir or 'auto'}"
313
+ )
314
+ if hasattr(self._local_model, "hf_device_map"):
315
+ logger.info(f"HF device map: {self._local_model.hf_device_map}")
316
+
317
+ def _generate_local(self, messages: List[dict], max_tokens: int) -> str:
318
+ inputs = self._messages_to_local_inputs(messages)
319
+
320
+ do_sample = self.temperature > 0
321
+ generate_kwargs: Dict[str, Any] = {
322
+ "max_new_tokens": max(64, int(max_tokens)),
323
+ "use_cache": True,
324
+ "do_sample": do_sample,
325
+ "return_dict_in_generate": False,
326
+ }
327
+
328
+ generation_config = copy.deepcopy(getattr(self._local_model, "generation_config", None))
329
+ if generation_config is not None:
330
+ for name in ("top_k", "top_p", "typical_p", "min_p", "epsilon_cutoff", "eta_cutoff"):
331
+ if hasattr(generation_config, name):
332
+ setattr(generation_config, name, None)
333
+ if hasattr(generation_config, "do_sample"):
334
+ generation_config.do_sample = do_sample
335
+ if hasattr(generation_config, "temperature"):
336
+ generation_config.temperature = max(0.01, float(self.temperature)) if do_sample else None
337
+ generate_kwargs["generation_config"] = generation_config
338
+
339
+ if do_sample:
340
+ generate_kwargs["temperature"] = max(0.01, float(self.temperature))
341
+ else:
342
+ generate_kwargs["temperature"] = None
343
+
344
+ tokenizer = getattr(self._processor, "tokenizer", None)
345
+ pad_token_id = getattr(tokenizer, "pad_token_id", None)
346
+ eos_token_id = getattr(tokenizer, "eos_token_id", None)
347
+ if pad_token_id is None and eos_token_id is not None:
348
+ pad_token_id = eos_token_id
349
+ if pad_token_id is not None:
350
+ generate_kwargs["pad_token_id"] = pad_token_id
351
+ if eos_token_id is not None:
352
+ generate_kwargs["eos_token_id"] = eos_token_id
353
+
354
+ with self._torch.inference_mode():
355
+ output_ids = self._local_model.generate(**inputs, **generate_kwargs)
356
+
357
+ input_ids = inputs.get("input_ids") if hasattr(inputs, "get") else None
358
+ if input_ids is not None and getattr(output_ids, "shape", None) is not None:
359
+ prompt_len = input_ids.shape[-1]
360
+ output_ids = output_ids[:, prompt_len:]
361
+
362
+ decoded = self._processor.batch_decode(output_ids, skip_special_tokens=True)
363
+ text = (decoded[0] if decoded else "").strip()
364
+ if text:
365
+ return text
366
+
367
+ decoded_raw = self._processor.batch_decode(output_ids, skip_special_tokens=False)
368
+ return (decoded_raw[0] if decoded_raw else "").strip()
369
+
370
+
371
+ GEMMA_SYSTEM_PROMPT = """You are a precise SVG hint generator for general image edits.
372
+
373
+ Your task is to generate an SVG hint that highlights the true edited region between the original image and the edited image.
374
+
375
+ Rules:
376
+ - Use the ORIGINAL image and EDITED image as the main source of truth.
377
+ - Use the EDGES image only to refine the boundary of a real edited region after comparing the original and edited images.
378
+ - You may also receive an automatically extracted REFERENCE OVERLAY and a REFERENCE CROP. Treat them only as weak localization hints.
379
+ - Ignore obvious registration noise, border artifacts, decorative frame edges, shadows, and repeated texture patterns.
380
+ - Mark the edited region with 1 to 3 concise shapes unless the edit is clearly disconnected.
381
+ - Prefer compact outer contours over noisy scribbles.
382
+ - Do not outline unchanged background structure.
383
+ - Use numeric absolute coordinates in the 0..1000 viewBox. Do not use percentages.
384
+ - Use only <polygon>, <polyline>, or <path>.
385
+ - Do not output <text>, labels, legends, or callout boxes.
386
+ - Return exactly one JSON object with key "svg".
387
+ """
388
+
389
+ GEMMA_REFINE_SYSTEM_PROMPT = """You are refining an existing SVG hint for a general image edit.
390
+
391
+ You will be given:
392
+ 1. ORIGINAL image
393
+ 2. EDITED image
394
+ 3. EDGES image
395
+ 4. REFERENCE OVERLAY
396
+ 5. REFERENCE CROP
397
+ 6. CURRENT HINT OVERLAY
398
+ 7. CURRENT SVG text
399
+
400
+ Refinement rules:
401
+ - Preserve parts of the current hint that already align with the real edited region.
402
+ - Remove strokes that point to unchanged structure, borders, shadows, or decorative elements.
403
+ - If the current hint is badly misplaced, replace it completely with a better compact hint.
404
+ - Use the reference images only as weak localization hints.
405
+ - Use numeric absolute coordinates in the 0..1000 viewBox. Do not use percentages.
406
+ - Use only <polygon>, <polyline>, or <path>.
407
+ - Return exactly one JSON object with key "svg".
408
+ """
409
+
410
+
411
+ def _gemma_extract_reference_regions(mask_u8, topk: int = 3):
412
+ if mask_u8 is None or getattr(mask_u8, "size", 0) == 0:
413
+ return []
414
+
415
+ cnts, _ = hg.cv2.findContours(mask_u8, hg.cv2.RETR_EXTERNAL, hg.cv2.CHAIN_APPROX_SIMPLE)
416
+ if not cnts:
417
+ return []
418
+
419
+ h, w = mask_u8.shape[:2]
420
+ min_area = max(12.0, w * h * 0.00035)
421
+ regions = []
422
+ for c in cnts:
423
+ area = float(hg.cv2.contourArea(c))
424
+ if area < min_area:
425
+ continue
426
+ epsilon = max(2.0, 0.015 * hg.cv2.arcLength(c, True))
427
+ approx = hg.cv2.approxPolyDP(c, epsilon, True)
428
+ pts = [(float(pt[0]), float(pt[1])) for pt in approx.reshape(-1, 2)]
429
+ if len(pts) < 3:
430
+ x, y, bw, bh = hg.cv2.boundingRect(c)
431
+ pts = [
432
+ (float(x), float(y)),
433
+ (float(x + bw), float(y)),
434
+ (float(x + bw), float(y + bh)),
435
+ (float(x), float(y + bh)),
436
+ ]
437
+ x, y, bw, bh = hg.cv2.boundingRect(c)
438
+ regions.append(
439
+ {
440
+ "bbox": [int(x), int(y), int(x + bw), int(y + bh)],
441
+ "area": area,
442
+ "points": pts,
443
+ }
444
+ )
445
+
446
+ regions.sort(key=lambda item: item["area"], reverse=True)
447
+ return regions[: max(1, int(topk))]
448
+
449
+
450
+ def _gemma_render_reference_overlay(base_img, regions, size):
451
+ overlay = base_img.convert("RGBA").resize(size, hg.Image.LANCZOS)
452
+ draw = hg.ImageDraw.Draw(overlay, "RGBA")
453
+ for idx, region in enumerate(regions, start=1):
454
+ pts = region.get("points") or []
455
+ if len(pts) >= 3:
456
+ draw.polygon(pts, outline=(255, 196, 0, 255), fill=(255, 196, 0, 36))
457
+ draw.line(pts + [pts[0]], fill=(255, 196, 0, 255), width=4)
458
+ bbox = region.get("bbox") or []
459
+ if len(bbox) == 4:
460
+ x1, y1, x2, y2 = bbox
461
+ draw.rectangle((x1, y1, x2, y2), outline=(0, 255, 255, 255), width=2)
462
+ font = hg._get_font(max(18, int(round(min(size) * 0.035))))
463
+ draw.text((x1 + 4, max(0, y1 - 24)), f"R{idx}", font=font, fill=(0, 255, 255, 255))
464
+ return overlay.convert("RGB")
465
+
466
+
467
+ def _gemma_build_reference_crop(o_small, e_small, regions, size):
468
+ w, h = size
469
+ if regions:
470
+ x1, y1, x2, y2 = regions[0].get("bbox", [0, 0, w, h])
471
+ else:
472
+ x1, y1, x2, y2 = 0, 0, w, h
473
+
474
+ pad_x = max(12, int(round((x2 - x1) * 0.18)))
475
+ pad_y = max(12, int(round((y2 - y1) * 0.18)))
476
+ cx1 = max(0, x1 - pad_x)
477
+ cy1 = max(0, y1 - pad_y)
478
+ cx2 = min(w, x2 + pad_x)
479
+ cy2 = min(h, y2 + pad_y)
480
+
481
+ crop_o = o_small.crop((cx1, cy1, cx2, cy2)).convert("RGBA")
482
+ crop_e = e_small.crop((cx1, cy1, cx2, cy2)).convert("RGBA")
483
+ crop_ref = crop_o.copy()
484
+ draw = hg.ImageDraw.Draw(crop_ref, "RGBA")
485
+ for idx, region in enumerate(regions, start=1):
486
+ bbox = region.get("bbox") or []
487
+ pts = region.get("points") or []
488
+ adj_pts = []
489
+ for x, y in pts:
490
+ xx = float(x) - cx1
491
+ yy = float(y) - cy1
492
+ if 0 <= xx <= (cx2 - cx1) and 0 <= yy <= (cy2 - cy1):
493
+ adj_pts.append((xx, yy))
494
+ if len(adj_pts) >= 3:
495
+ draw.polygon(adj_pts, outline=(255, 196, 0, 255), fill=(255, 196, 0, 36))
496
+ draw.line(adj_pts + [adj_pts[0]], fill=(255, 196, 0, 255), width=4)
497
+ if len(bbox) == 4:
498
+ bx1, by1, bx2, by2 = bbox
499
+ bx1 -= cx1
500
+ by1 -= cy1
501
+ bx2 -= cx1
502
+ by2 -= cy1
503
+ if bx2 >= 0 and by2 >= 0 and bx1 <= (cx2 - cx1) and by1 <= (cy2 - cy1):
504
+ draw.rectangle((bx1, by1, bx2, by2), outline=(0, 255, 255, 255), width=2)
505
+ font = hg._get_font(max(18, int(round(min(crop_ref.size) * 0.06))))
506
+ draw.text((max(0, bx1 + 4), max(0, by1 - 24)), f"R{idx}", font=font, fill=(0, 255, 255, 255))
507
+
508
+ panel = hg.Image.new("RGB", (crop_o.width * 3, crop_o.height), (0, 0, 0))
509
+ panel.paste(crop_o.convert("RGB"), (0, 0))
510
+ panel.paste(crop_e.convert("RGB"), (crop_o.width, 0))
511
+ panel.paste(crop_ref.convert("RGB"), (crop_o.width * 2, 0))
512
+ return panel
513
+
514
+
515
+ def build_gemma_messages(du_o, du_e, du_edges, du_ref_overlay, du_ref_crop, w, h, instruction, regions):
516
+ ref_text = "none"
517
+ if regions:
518
+ items = []
519
+ for idx, region in enumerate(regions[:3], start=1):
520
+ bbox = region.get("bbox") or []
521
+ if len(bbox) == 4:
522
+ items.append(f"R{idx}=({bbox[0]},{bbox[1]})-({bbox[2]},{bbox[3]})")
523
+ if items:
524
+ ref_text = "; ".join(items)
525
+
526
+ user_text = (
527
+ f"Instruction: {instruction}\n"
528
+ f"Canvas: {w}x{h} pixels.\n"
529
+ "Inputs:\n"
530
+ "1. ORIGINAL image\n"
531
+ "2. EDITED image\n"
532
+ "3. EDGES image derived from the edited image\n\n"
533
+ "4. REFERENCE OVERLAY with auto-extracted candidate regions\n"
534
+ "5. REFERENCE CROP panel: original crop | edited crop | reference overlay crop\n\n"
535
+ f"Reference regions: {ref_text}\n\n"
536
+ "Guidelines:\n"
537
+ "1. Compare ORIGINAL and EDITED first to determine the real semantic edit.\n"
538
+ "2. Use the EDGES image only to tighten the boundary of a region that is visibly edited in the EDITED image.\n"
539
+ "3. Use the REFERENCE OVERLAY and REFERENCE CROP only as weak localization hints. If they disagree with the actual visible edit, trust the ORIGINAL and EDITED images.\n"
540
+ "4. Ignore isolated thin artifacts near image borders or decorative structures unless they are clearly part of the real edit.\n"
541
+ "5. Produce a compact hint around the real edited region.\n"
542
+ "6. Use numeric absolute coordinates in the 0..1000 viewBox. Do not use percentages.\n"
543
+ "7. Return only the JSON object with the svg field.\n"
544
+ )
545
+ return [
546
+ {"role": "system", "content": GEMMA_SYSTEM_PROMPT},
547
+ {
548
+ "role": "user",
549
+ "content": [
550
+ {"type": "text", "text": user_text},
551
+ {"type": "image_url", "image_url": {"url": du_o}},
552
+ {"type": "image_url", "image_url": {"url": du_e}},
553
+ {"type": "image_url", "image_url": {"url": du_edges}},
554
+ {"type": "image_url", "image_url": {"url": du_ref_overlay}},
555
+ {"type": "image_url", "image_url": {"url": du_ref_crop}},
556
+ ],
557
+ },
558
+ ]
559
+
560
+
561
+ def build_gemma_refine_messages(
562
+ du_o,
563
+ du_e,
564
+ du_edges,
565
+ du_ref_overlay,
566
+ du_ref_crop,
567
+ du_hint_overlay,
568
+ w,
569
+ h,
570
+ instruction,
571
+ current_svg,
572
+ round_idx: int,
573
+ ):
574
+ svg_text = str(current_svg or "").strip()
575
+ if len(svg_text) > 6000:
576
+ svg_text = svg_text[:6000]
577
+
578
+ user_text = (
579
+ f"Instruction: {instruction}\n"
580
+ f"Canvas: {w}x{h} pixels.\n"
581
+ f"Refinement round: {round_idx}\n\n"
582
+ "Task:\n"
583
+ "Refine the CURRENT HINT OVERLAY so it better matches the real edit between ORIGINAL and EDITED.\n\n"
584
+ "Guidelines:\n"
585
+ "1. Compare ORIGINAL and EDITED first.\n"
586
+ "2. Inspect CURRENT HINT OVERLAY and identify wrong strokes or missing coverage.\n"
587
+ "3. Use EDGES only to tighten a boundary that is visibly part of the edit.\n"
588
+ "4. Use REFERENCE OVERLAY and REFERENCE CROP only as weak hints.\n"
589
+ "5. Output a complete corrected SVG, not a delta.\n"
590
+ "6. Use numeric absolute coordinates in the 0..1000 viewBox. Do not use percentages.\n\n"
591
+ f"Current SVG candidate:\n{svg_text}"
592
+ )
593
+ return [
594
+ {"role": "system", "content": GEMMA_REFINE_SYSTEM_PROMPT},
595
+ {
596
+ "role": "user",
597
+ "content": [
598
+ {"type": "text", "text": user_text},
599
+ {"type": "image_url", "image_url": {"url": du_o}},
600
+ {"type": "image_url", "image_url": {"url": du_e}},
601
+ {"type": "image_url", "image_url": {"url": du_edges}},
602
+ {"type": "image_url", "image_url": {"url": du_ref_overlay}},
603
+ {"type": "image_url", "image_url": {"url": du_ref_crop}},
604
+ {"type": "image_url", "image_url": {"url": du_hint_overlay}},
605
+ ],
606
+ },
607
+ ]
608
+
609
+
610
+ def _gemma_filter_shapes(shapes: List[dict]) -> List[dict]:
611
+ return [s for s in (shapes or []) if s.get("type") != "text"]
612
+
613
+
614
+ def _gemma_parse_shapes_safe(svg_raw: str, w: int, h: int) -> List[dict]:
615
+ if not svg_raw:
616
+ return []
617
+ try:
618
+ return _gemma_filter_shapes(hg._parse_svg_shapes(svg_raw, w, h))
619
+ except Exception:
620
+ return []
621
+
622
+
623
+ def _gemma_shapes_mask(shapes: List[dict], w: int, h: int):
624
+ canvas = hg.Image.new("L", (w, h), 0)
625
+ draw = hg.ImageDraw.Draw(canvas)
626
+ line_w = max(4, int(round(min(w, h) * 0.01)))
627
+ for s in shapes:
628
+ t = str(s.get("type") or "")
629
+ if t in ("polygon", "polyline"):
630
+ pts = [(float(x), float(y)) for x, y in (s.get("points") or [])]
631
+ if len(pts) >= 3:
632
+ draw.polygon(pts, fill=255)
633
+ draw.line(pts + [pts[0]], fill=255, width=line_w)
634
+ elif len(pts) >= 2:
635
+ draw.line(pts, fill=255, width=line_w)
636
+ return hg.np.array(canvas, dtype=hg.np.uint8)
637
+
638
+
639
+ def _gemma_mask_bbox(mask_arr) -> Optional[List[int]]:
640
+ ys, xs = hg.np.where(mask_arr > 0)
641
+ if len(xs) == 0 or len(ys) == 0:
642
+ return None
643
+ return [int(xs.min()), int(ys.min()), int(xs.max()), int(ys.max())]
644
+
645
+
646
+ def _gemma_bbox_iou(a: Optional[List[int]], b: Optional[List[int]]) -> float:
647
+ if not a or not b:
648
+ return 0.0
649
+ ax1, ay1, ax2, ay2 = a
650
+ bx1, by1, bx2, by2 = b
651
+ ix1 = max(ax1, bx1)
652
+ iy1 = max(ay1, by1)
653
+ ix2 = min(ax2, bx2)
654
+ iy2 = min(ay2, by2)
655
+ iw = max(0, ix2 - ix1 + 1)
656
+ ih = max(0, iy2 - iy1 + 1)
657
+ inter = iw * ih
658
+ if inter <= 0:
659
+ return 0.0
660
+ area_a = max(1, (ax2 - ax1 + 1) * (ay2 - ay1 + 1))
661
+ area_b = max(1, (bx2 - bx1 + 1) * (by2 - by1 + 1))
662
+ return float(inter) / float(max(1, area_a + area_b - inter))
663
+
664
+
665
+ def _gemma_score_shapes(shapes: List[dict], reference_mask_u8, w: int, h: int) -> float:
666
+ if not shapes:
667
+ return -1.0
668
+ pred_mask = _gemma_shapes_mask(shapes, w, h) > 0
669
+ ref_mask = reference_mask_u8 > 0
670
+ pred_area = int(pred_mask.sum())
671
+ ref_area = int(ref_mask.sum())
672
+ if pred_area <= 0 or ref_area <= 0:
673
+ return -1.0
674
+ inter = int((pred_mask & ref_mask).sum())
675
+ precision = float(inter) / float(max(1, pred_area))
676
+ recall = float(inter) / float(max(1, ref_area))
677
+ f1 = 0.0 if (precision + recall) <= 0 else (2.0 * precision * recall / (precision + recall))
678
+ pred_bbox = _gemma_mask_bbox(pred_mask)
679
+ ref_bbox = _gemma_mask_bbox(ref_mask)
680
+ bbox_iou = _gemma_bbox_iou(pred_bbox, ref_bbox)
681
+ total_points = sum(len(s.get("points") or []) for s in shapes)
682
+ complexity_penalty = max(0, len(shapes) - 4) * 0.03 + max(0, total_points - 180) * 0.0004
683
+ return (0.65 * f1) + (0.20 * precision) + (0.15 * bbox_iou) - complexity_penalty
684
+
685
+
686
+ def _process_row_gemma(
687
+ client: GeminiGatewayClient,
688
+ row,
689
+ out_dir: str,
690
+ idx_tag: str,
691
+ max_side_start: int,
692
+ grid_mode: str = "auto",
693
+ grid_cell: int = 64,
694
+ stroke_width: int = 5,
695
+ label_scale: float = 0.045,
696
+ verify: bool = False,
697
+ verify_threshold: float = 0.65,
698
+ reject_dir: Optional[str] = None,
699
+ roi_topk: int = 5,
700
+ model_max_tokens: int = 4096,
701
+ ):
702
+ sid = str(getattr(row, "image_id", idx_tag))
703
+ sid = re.sub(r"[^A-Za-z0-9._-]+", "", sid)
704
+
705
+ os.makedirs(out_dir, exist_ok=True)
706
+ png_path = os.path.join(out_dir, f"hints_{sid}.png")
707
+ html_path = os.path.join(out_dir, f"hints_{sid}.html")
708
+
709
+ try:
710
+ in_cell = getattr(row, "image_file", None)
711
+ tgt_cell = getattr(row, "edited_file", None)
712
+ o_bytes = hg._bytes_from_cell(in_cell)
713
+ e_bytes = hg._bytes_from_cell(tgt_cell)
714
+ o_img = hg.Image.open(io.BytesIO(o_bytes)).convert("RGBA")
715
+ e_img = hg.Image.open(io.BytesIO(e_bytes)).convert("RGBA")
716
+ except Exception as e:
717
+ logger.error(f"[{sid}] 图像加载失败: {e}")
718
+ return
719
+
720
+ w0, h0 = o_img.size
721
+ du_o, du_e, (wc, hc) = hg.make_adaptive_payload(
722
+ o_img,
723
+ e_img,
724
+ max_side_start=max_side_start,
725
+ with_grid=(grid_mode != "off"),
726
+ grid_cell=grid_cell,
727
+ )
728
+
729
+ o_small = o_img.resize((wc, hc), hg.Image.LANCZOS)
730
+ e_small = e_img.resize((wc, hc), hg.Image.LANCZOS)
731
+ mask_u8, _diff_img, e_aligned = hg._make_diff_precise(o_small, e_small, (wc, hc))
732
+ edges_img = hg._make_edges(e_aligned, (wc, hc))
733
+ ref_regions = _gemma_extract_reference_regions(mask_u8, topk=max(1, min(roi_topk, 3)))
734
+ ref_overlay = _gemma_render_reference_overlay(o_small, ref_regions, (wc, hc))
735
+ ref_crop = _gemma_build_reference_crop(o_small, e_small, ref_regions, (wc, hc))
736
+
737
+ du_edges = hg._to_data_url(hg._encode_jpeg(edges_img, 65))
738
+ du_ref_overlay = hg._to_data_url(hg._encode_jpeg(ref_overlay, 80))
739
+ du_ref_crop = hg._to_data_url(hg._encode_jpeg(ref_crop, 82))
740
+
741
+ instr = getattr(row, "edit_instruction", "") or ""
742
+ msgs = build_gemma_messages(du_o, du_e, du_edges, du_ref_overlay, du_ref_crop, wc, hc, instr, ref_regions)
743
+
744
+ out = client.chat_force_svg_html(msgs, max_tokens=model_max_tokens)
745
+ raw_resp = (out.get("raw") or "").strip()
746
+ mode = out.get("mode", "unknown")
747
+
748
+ if not raw_resp:
749
+ logger.error(f"[{sid}] 模型返回为空,跳过该任务。")
750
+ return
751
+
752
+ svg_raw, _ = hg._extract_svg_or_html_from_raw(raw_resp)
753
+ if not svg_raw and hg._looks_like_svg_payload(raw_resp):
754
+ svg_raw = raw_resp
755
+
756
+ if not svg_raw:
757
+ logger.error(f"[{sid}] 未找到有效的 SVG 负载 (mode={mode})。")
758
+ hg._save_raw_fail(out_dir, sid, raw_resp, f"nopayload_{mode}")
759
+ return
760
+
761
+ current_svg = svg_raw
762
+ current_shapes_small = _gemma_parse_shapes_safe(current_svg, wc, hc)
763
+ if not current_shapes_small:
764
+ logger.warning(f"[{sid}] 解析成功但未找到任何形状。")
765
+ hg._save_raw_fail(out_dir, sid, raw_resp, f"noshapes_{mode}")
766
+ return
767
+ current_score = _gemma_score_shapes(current_shapes_small, mask_u8, wc, hc)
768
+ logger.info(f"[{sid}] 初始 hint score={current_score:.4f}")
769
+
770
+ for round_idx in range(1, int(max(0, _GEMMA_REFINE_ROUNDS)) + 1):
771
+ hint_overlay_small = hg._render_hint_preview(e_small, current_shapes_small, stroke_width, label_scale)
772
+ du_hint_overlay = hg._to_data_url(hg._encode_jpeg(hint_overlay_small.convert("RGB"), 82))
773
+ refine_msgs = build_gemma_refine_messages(
774
+ du_o=du_o,
775
+ du_e=du_e,
776
+ du_edges=du_edges,
777
+ du_ref_overlay=du_ref_overlay,
778
+ du_ref_crop=du_ref_crop,
779
+ du_hint_overlay=du_hint_overlay,
780
+ w=wc,
781
+ h=hc,
782
+ instruction=instr,
783
+ current_svg=current_svg,
784
+ round_idx=round_idx,
785
+ )
786
+ refine_out = client.chat_force_svg_html(refine_msgs, max_tokens=model_max_tokens)
787
+ refine_raw = (refine_out.get("raw") or "").strip()
788
+ if not refine_raw:
789
+ continue
790
+ refine_svg, _ = hg._extract_svg_or_html_from_raw(refine_raw)
791
+ if not refine_svg and hg._looks_like_svg_payload(refine_raw):
792
+ refine_svg = refine_raw
793
+ if not refine_svg:
794
+ logger.info(f"[{sid}] refine round {round_idx}: no valid svg payload")
795
+ continue
796
+ refine_shapes_small = _gemma_parse_shapes_safe(refine_svg, wc, hc)
797
+ if not refine_shapes_small:
798
+ logger.info(f"[{sid}] refine round {round_idx}: parse yielded no shapes")
799
+ continue
800
+ refine_score = _gemma_score_shapes(refine_shapes_small, mask_u8, wc, hc)
801
+ if refine_score > current_score:
802
+ current_svg = refine_svg
803
+ current_shapes_small = refine_shapes_small
804
+ current_score = refine_score
805
+ logger.info(f"[{sid}] refine round {round_idx}: accepted score={current_score:.4f}")
806
+ else:
807
+ logger.info(
808
+ f"[{sid}] refine round {round_idx}: rejected candidate score={refine_score:.4f} "
809
+ f"<= current={current_score:.4f}"
810
+ )
811
+
812
+ scaled_shapes = _gemma_parse_shapes_safe(current_svg, w0, h0)
813
+ if not scaled_shapes:
814
+ logger.error(f"[{sid}] 最终 refined SVG 在原图尺度下解析失败。")
815
+ hg._save_raw_fail(out_dir, sid, current_svg, f"refinefail_{mode}")
816
+ return
817
+
818
+ hint_overlay_img_mem = hg._render_hint_preview(o_img, scaled_shapes, stroke_width, label_scale)
819
+ hg._draw_shapes_on_image(
820
+ base_img=o_img,
821
+ shapes=scaled_shapes,
822
+ out_path=png_path,
823
+ stroke_width=stroke_width,
824
+ label_scale=label_scale,
825
+ )
826
+
827
+ svg_clean = hg._shapes_to_svg(scaled_shapes, w0, h0)
828
+ du_orig_full = hg._to_data_url(hg._encode_jpeg(o_img.convert("RGB"), 85))
829
+ final_html = hg._build_overlay_html(du_orig_full, svg_clean, w0, h0)
830
+ with open(html_path, "w", encoding="utf-8") as f:
831
+ f.write(final_html)
832
+
833
+ if verify:
834
+ verdict = hg.verify_hint_with_model(
835
+ client=client,
836
+ o_img=o_img,
837
+ e_img=e_img,
838
+ hint_overlay_img=hint_overlay_img_mem,
839
+ max_side=1024,
840
+ max_tokens=700,
841
+ )
842
+ ok = bool(verdict.get("ok", False))
843
+ score = float(verdict.get("score", 0.0) or 0.0)
844
+ if (not ok) or (score < float(verify_threshold)):
845
+ logger.warning(f"[{sid}] 验证未通过 (Score: {score}),移动至 reject 目录。")
846
+ target_reject_dir = reject_dir or os.path.join(out_dir, "_reject")
847
+ os.makedirs(target_reject_dir, exist_ok=True)
848
+ try:
849
+ os.rename(png_path, os.path.join(target_reject_dir, f"hints_{sid}.png"))
850
+ except Exception:
851
+ pass
852
+ try:
853
+ os.rename(html_path, os.path.join(target_reject_dir, f"hints_{sid}.html"))
854
+ except Exception:
855
+ pass
856
+
857
+ logger.info(f"[{sid}] 任务完成:{png_path} final_score={current_score:.4f}")
858
+
859
+
860
+ def build_parser() -> argparse.ArgumentParser:
861
+ parser = argparse.ArgumentParser()
862
+
863
+ parser.add_argument("--use-json", action="store_true")
864
+ parser.add_argument("--json-path", default="", help="Path to editing.json")
865
+ parser.add_argument("--image-root", default="", help="Root for json images")
866
+ parser.add_argument("--data-dir", default="", help="Dir with parquets")
867
+ parser.add_argument(
868
+ "--base-url",
869
+ default=GATEWAY_BASE_URL,
870
+ help="OpenAI-compatible API base URL for remote gateways or local /v1 servers.",
871
+ )
872
+ parser.add_argument(
873
+ "--force-api",
874
+ action="store_true",
875
+ help="Treat --model-name as an API model id even if it looks like a local path.",
876
+ )
877
+
878
+ parser.add_argument("--out-root", default="./gemma_hint_runs")
879
+ parser.add_argument("--max-side-start", type=int, default=480)
880
+ parser.add_argument("--limit-rows", type=int, default=None)
881
+ parser.add_argument("--rpm", type=int, default=1200)
882
+ parser.add_argument("--workers", type=int, default=1)
883
+ parser.add_argument("--grid-mode", default="auto", choices=["auto", "off"])
884
+ parser.add_argument("--grid-cell", type=int, default=64)
885
+
886
+ parser.add_argument("--stroke-width", type=int, default=6)
887
+ parser.add_argument("--label-scale", type=float, default=0.050)
888
+
889
+ parser.add_argument("--roi-topk", type=int, default=5)
890
+ parser.add_argument("--model-max-tokens", type=int, default=4096)
891
+ parser.add_argument("--refine-rounds", type=int, default=3)
892
+
893
+ parser.add_argument("--verify", action="store_true")
894
+ parser.add_argument("--verify-threshold", type=float, default=0.3)
895
+
896
+ parser.add_argument("--log-missing", action="store_true")
897
+
898
+ parser.add_argument(
899
+ "--model-name",
900
+ default=os.environ.get("GEMMA_HINT_MODEL", GEMMA_MODEL_PATH),
901
+ help="Gemma checkpoint path or remote model id.",
902
+ )
903
+ parser.add_argument(
904
+ "--local-model-dtype",
905
+ default=os.environ.get("LOCAL_MODEL_DTYPE", "bfloat16"),
906
+ help="Torch dtype for local HF loading: auto, bfloat16, float16, float32",
907
+ )
908
+ parser.add_argument("--local-load-in-4bit", action="store_true")
909
+ parser.add_argument("--local-load-in-8bit", action="store_true")
910
+ parser.add_argument("--local-offload-dir", default="")
911
+ parser.add_argument(
912
+ "--local-device-map",
913
+ default=os.environ.get("LOCAL_DEVICE_MAP", "auto"),
914
+ help="HF device_map for local model loading, e.g. auto, balanced, balanced_low_0, sequential.",
915
+ )
916
+ parser.add_argument(
917
+ "--local-max-memory-per-gpu-gb",
918
+ type=int,
919
+ default=None,
920
+ help="Optional per-GPU max memory budget in GiB when using multi-GPU sharding.",
921
+ )
922
+ parser.add_argument(
923
+ "--local-processor-path",
924
+ default=os.environ.get("GEMMA_HINT_PROCESSOR_PATH", ""),
925
+ help="Optional directory containing tokenizer/processor files if they are separate from model weights.",
926
+ )
927
+ parser.add_argument(
928
+ "--local-processor-class",
929
+ default=os.environ.get("GEMMA_HINT_PROCESSOR_CLASS", ""),
930
+ help="Optional explicit processor class name, e.g. Gemma3Processor or PaliGemmaProcessor.",
931
+ )
932
+ parser.add_argument("--temperature", type=float, default=0.2)
933
+ parser.add_argument("--no-stop", action="store_true")
934
+
935
+ parser.add_argument("--session", action="store_true")
936
+ parser.add_argument("--session-keep-turns", type=int, default=4)
937
+
938
+ parser.add_argument(
939
+ "--keys",
940
+ nargs="+",
941
+ default=[],
942
+ help="API keys for gateway usage. Ignored in local model mode.",
943
+ )
944
+ return parser
945
+
946
+
947
+ def build_client_pool(args) -> List[GemmaHintClient]:
948
+ model_name = resolve_model_name(args.model_name)
949
+ use_local_model = is_local_model_name(model_name) and (not args.force_api)
950
+ use_local_openai_server = (not use_local_model) and is_local_openai_base_url(args.base_url)
951
+
952
+ if args.force_api and (args.local_load_in_4bit or args.local_load_in_8bit):
953
+ raise RuntimeError("--force-api cannot be used together with --local-load-in-4bit/--local-load-in-8bit")
954
+ if args.local_load_in_4bit and args.local_load_in_8bit:
955
+ raise RuntimeError("Use at most one of --local-load-in-4bit / --local-load-in-8bit")
956
+ if use_local_model and not os.path.isdir(model_name):
957
+ raise RuntimeError(f"Local model path does not exist or is not a directory: {model_name}")
958
+ if use_local_model and (args.local_load_in_4bit or args.local_load_in_8bit):
959
+ if not args.local_offload_dir:
960
+ args.local_offload_dir = os.path.join(args.out_root, "_hf_offload")
961
+ os.makedirs(args.local_offload_dir, exist_ok=True)
962
+
963
+ keys: List[str] = []
964
+ limiter: Optional[KeyedRateLimiter] = None
965
+ if not use_local_model:
966
+ keys = args.keys or []
967
+ if not keys:
968
+ env_keys = os.environ.get("GPT_KEYS", "").strip()
969
+ if env_keys:
970
+ keys = [k.strip() for k in env_keys.split(",") if k.strip()]
971
+ if not keys and not use_local_openai_server:
972
+ raise RuntimeError("No API keys provided. Use --keys or set GPT_KEYS.")
973
+ if keys:
974
+ limiter = KeyedRateLimiter(rpm_per_key=args.rpm, keys=keys)
975
+ elif use_local_openai_server:
976
+ logger.warning(f"Using local OpenAI-compatible server without API key: base_url={args.base_url}")
977
+ assert_local_openai_server_ready(args.base_url)
978
+
979
+ num_workers = int(max(1, args.workers))
980
+ if use_local_model and num_workers != 1:
981
+ logger.warning("Local Gemma backend detected; forcing workers=1.")
982
+ num_workers = 1
983
+ args.workers = 1
984
+
985
+ clients: List[GemmaHintClient] = []
986
+ for i in range(num_workers):
987
+ api_key = keys[i % len(keys)] if keys else ""
988
+ clients.append(
989
+ GemmaHintClient(
990
+ api_key=api_key,
991
+ limiter=limiter,
992
+ base_url=args.base_url,
993
+ model=model_name,
994
+ timeout=DEFAULT_TIMEOUT,
995
+ max_retries=MAX_RETRIES_ENV,
996
+ temperature=args.temperature,
997
+ local_dtype=args.local_model_dtype,
998
+ local_load_in_4bit=args.local_load_in_4bit,
999
+ local_load_in_8bit=args.local_load_in_8bit,
1000
+ local_cpu_offload=(args.local_load_in_4bit or args.local_load_in_8bit),
1001
+ local_offload_dir=args.local_offload_dir,
1002
+ local_device_map=args.local_device_map,
1003
+ local_max_memory_per_gpu_gb=args.local_max_memory_per_gpu_gb,
1004
+ local_processor_path=args.local_processor_path,
1005
+ local_processor_class=args.local_processor_class,
1006
+ force_api=args.force_api,
1007
+ enable_stop=(not args.no_stop),
1008
+ session_mode=args.session,
1009
+ session_keep_turns=args.session_keep_turns,
1010
+ )
1011
+ )
1012
+ args.model_name = model_name
1013
+ return clients
1014
+
1015
+
1016
+ def main() -> None:
1017
+ parser = build_parser()
1018
+ args = parser.parse_args()
1019
+
1020
+ logger.remove()
1021
+ logger.add(sys.stderr, level="INFO")
1022
+ os.makedirs(args.out_root, exist_ok=True)
1023
+
1024
+ global _GEMMA_REFINE_ROUNDS
1025
+ _GEMMA_REFINE_ROUNDS = int(max(0, args.refine_rounds))
1026
+
1027
+ hg.SYSTEM_PROMPT = GEMMA_SYSTEM_PROMPT
1028
+ hg.build_messages = build_gemma_messages
1029
+ hg.process_row = _process_row_gemma
1030
+
1031
+ clients = build_client_pool(args)
1032
+ use_local_model = is_local_model_name(args.model_name) and (not args.force_api)
1033
+ backend = "local_hf" if use_local_model else "api"
1034
+
1035
+ if args.use_json or (args.json_path and os.path.isfile(args.json_path)):
1036
+ if not args.json_path or not args.image_root:
1037
+ raise RuntimeError("JSON mode requires --json-path and --image-root")
1038
+ logger.info(
1039
+ f"Running Gemma hint generation in JSON mode... "
1040
+ f"backend={backend} workers={args.workers} model={args.model_name}"
1041
+ )
1042
+ run_json_mode(args, clients)
1043
+ return
1044
+
1045
+ if not args.data_dir:
1046
+ raise RuntimeError("Parquet mode requires --data-dir")
1047
+ logger.info(
1048
+ f"Running Gemma hint generation in Parquet mode... "
1049
+ f"backend={backend} workers={args.workers} model={args.model_name}"
1050
+ )
1051
+ run_parquet_mode(args, clients)
1052
+
1053
+
1054
+ if __name__ == "__main__":
1055
+ main()