CADBench-Extended-Multimodal-Dataset / tools /apply_visual_semantics.py
LianeMarilin's picture
Add files using upload-large-folder tool
b6f0739 verified
Raw History Blame Contribute Delete
5.92 kB
#!/usr/bin/env python3
"""Merge manually reviewed four-view semantics into the public metadata indexes."""
from __future__ import annotations
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
ANN = ROOT / "annotations"
def read_jsonl(path: Path) -> list[dict]:
with path.open(encoding="utf-8") as handle:
return [json.loads(line) for line in handle if line.strip()]
def write_jsonl(path: Path, rows: list[dict]) -> None:
with path.open("w", encoding="utf-8") as handle:
for row in rows:
handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
def summarize_features(annotation: dict) -> str:
vf = annotation["visual_features"]
terms: list[str] = []
if vf["openings"]:
terms.append("openings: " + "; ".join(
item if isinstance(item, str) else f"{item.get('count')} × {item.get('type')} ({item.get('location')})"
for item in vf["openings"]
))
if vf["recesses"]:
terms.append("recesses: " + "; ".join(vf["recesses"]))
if vf["protrusions"]:
terms.append("protrusions: " + "; ".join(vf["protrusions"]))
if vf["repeated_structures"]:
terms.append("repetition: " + "; ".join(vf["repeated_structures"]))
terms.append("symmetry: " + vf["symmetry"])
return " | ".join(terms)
def build_prompts(sample_id: str, label: str, annotation: dict) -> dict:
primary = annotation["primary_form"]
caption_en = annotation["visual_caption_en"]
caption_zh = annotation["visual_caption_zh"]
feature_plan = ", ".join(annotation["feature_tree_hint"])
feature_summary = summarize_features(annotation)
return {
"image_to_cad_en": (
f"Reconstruct {sample_id}, a {primary}, from its four standardized isometric grayscale views "
f"as an executable CadQuery Python program. Visually verified target: {caption_en} "
f"Use this feature-order hint where suitable: {feature_plan}. Preserve the verified topology, "
"counts, symmetry, and relative placement. Include all imports, assign the final valid model "
"to result, and return Python code only."
),
"image_to_cad_zh": (
f"根据四张标准等距灰度视图,将 {sample_id} 重建为可执行 CadQuery Python 程序。"
f"人工视觉核验结果:{caption_zh} 建议特征顺序:{feature_plan}。请保持已核验的拓扑、数量、"
"对称关系与相对位置;包含全部导入,将最终有效模型赋值给 result,只返回 Python 代码。"
),
"mesh_to_cad_en": (
f"Convert the normalized clean mesh of {sample_id} into an editable CadQuery model. The object "
f"is visually identified as a {primary}. Match these reviewed observations: {feature_summary}. "
f"A useful construction sequence is: {feature_plan}. Include all imports, assign the final valid "
"model to result, and return Python code only."
),
"caption_en": (
f"Write a precise geometric caption for {sample_id}. Use the manually reviewed observation as "
f"ground truth: {caption_en} Report only visible geometry and topology."
),
"caption_zh": (
f"为 {sample_id} 撰写精确几何描述。以人工逐视图核验结果为真值:{caption_zh} "
"仅描述可见几何与拓扑。"
),
"pbr_generation_en": (
f"Create an uncropped photorealistic product render of {sample_id}, preserving its identity as a "
f"{primary}. The render must retain these reviewed geometric cues: {feature_summary}. Use the "
"recorded material, ground texture, three-point lighting, and camera parameters."
),
"negative_prompt_en": (
f"cropped {primary}, incorrect feature count, lost symmetry, omitted reviewed openings or recesses, "
"extra parts, floating fragments, extreme perspective, text, watermark, logo, low contrast, "
"overexposure, underexposure"
),
}
def main() -> None:
annotations = {row["sample_id"]: row for row in read_jsonl(ANN / "visual_semantics.jsonl")}
metadata = read_jsonl(ANN / "metadata_extended.jsonl")
if len(metadata) != 100 or set(annotations) != {row["sample_id"] for row in metadata}:
raise SystemExit("Visual semantics and metadata sample IDs do not match exactly.")
prompt_rows: list[dict] = []
for row in metadata:
sample_id = row["sample_id"]
visual = annotations[sample_id]
old_descriptions = row["descriptions"]
row["descriptions"] = {
"en": visual["visual_caption_en"],
"zh": visual["visual_caption_zh"],
"technical_en": old_descriptions.get("technical_en", old_descriptions["en"]),
"technical_zh": old_descriptions.get("technical_zh", old_descriptions["zh"]),
"annotation_method": visual["annotation_method"],
}
row["visual_semantics"] = {
"primary_form": visual["primary_form"],
"features": visual["visual_features"],
"feature_tree_hint": visual["feature_tree_hint"],
"confidence": visual["confidence"],
}
row["prompts"] = build_prompts(sample_id, row["label"], visual)
prompt_rows.append({
"sample_id": sample_id,
"label": row["label"],
"split": row["split"],
"descriptions": row["descriptions"],
"visual_semantics": row["visual_semantics"],
"prompts": row["prompts"],
})
write_jsonl(ANN / "metadata_extended.jsonl", metadata)
write_jsonl(ANN / "prompts.jsonl", prompt_rows)
print("Applied 100 manually reviewed visual-semantic records.")
if __name__ == "__main__":
main()