CaveWorld3D / project /scripts /caption_measured_views.py
xiaojie06's picture
Archive CaveWorld3D project files 路 5
1d15e3f verified
Raw History Blame Contribute Delete
2.72 kB
"""Describe only the photographed conditioning frame for measured view training."""
import argparse
import json
from pathlib import Path
import time
from PIL import Image
import torch
from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration
def main():
p = argparse.ArgumentParser(description=__doc__)
for key in ("model", "data", "output"):
p.add_argument("--" + key, type=Path, required=True)
a = p.parse_args()
model = (
Qwen2_5_VLForConditionalGeneration.from_pretrained(
str(a.model / "text_encoder"),
torch_dtype=torch.bfloat16,
local_files_only=True,
attn_implementation="sdpa",
)
.to("cuda")
.eval()
)
proc = AutoProcessor.from_pretrained(
str(a.model / "processor"), local_files_only=True
)
while not a.data.is_file():
time.sleep(2)
data = json.loads(a.data.read_text())
paths = sorted({r["condition"] for k in ("train", "development") for r in data[k]})
prompt = "Describe this photograph in one short English sentence, using only visible surfaces, structures, light and ground texture. Be literal. Omit guesses about unseen surroundings."
messages = [
{
"role": "user",
"content": [{"type": "image"}, {"type": "text", "text": prompt}],
}
]
template = proc.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True
)
log = a.output.with_suffix(".jsonl")
captions = (
{
v["condition"]: v["text"]
for v in (json.loads(line) for line in log.read_text().splitlines())
}
if log.exists()
else {}
)
a.output.parent.mkdir(parents=True, exist_ok=True)
for path in paths:
if path in captions:
continue
with Image.open(path) as im:
image = im.convert("RGB")
image.thumbnail((560, 560), Image.Resampling.LANCZOS)
batch = proc(text=[template], images=[image], return_tensors="pt").to("cuda")
with torch.inference_mode():
ids = model.generate(**batch, max_new_tokens=50, do_sample=False)
sentence = proc.batch_decode(
ids[:, batch.input_ids.shape[1] :], skip_special_tokens=True
)[0].strip()
captions[path] = sentence
with log.open("a") as handle:
handle.write(json.dumps(dict(condition=path, text=sentence)) + "\n")
print(len(captions), len(paths), Path(path).name, sentence, flush=True)
temp = a.output.with_suffix(".tmp")
temp.write_text(json.dumps(captions, indent=2) + "\n")
temp.replace(a.output)
if __name__ == "__main__":
main()