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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import glob
|
| 4 |
+
import json
|
| 5 |
+
import random
|
| 6 |
+
import argparse
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from collections import defaultdict
|
| 10 |
+
|
| 11 |
+
def parse_ground_truth(name):
|
| 12 |
+
"""Extract ground truth rotation axis and angle from filename or folder name"""
|
| 13 |
+
# Remove file extension if present
|
| 14 |
+
basename = name.split(".")[0] if "." in name else name
|
| 15 |
+
|
| 16 |
+
parts = basename.split("_")
|
| 17 |
+
if len(parts) >= 4: # figXXXX_XXX_axis_angle
|
| 18 |
+
rotation_axis = parts[-2] # Second to last element is axis
|
| 19 |
+
rotation_angle = int(parts[-1]) # Last element is angle
|
| 20 |
+
|
| 21 |
+
# Convert negative angles to 0-360 range
|
| 22 |
+
if rotation_angle < 0:
|
| 23 |
+
rotation_angle += 360
|
| 24 |
+
|
| 25 |
+
return rotation_axis, rotation_angle
|
| 26 |
+
|
| 27 |
+
print(f"Warning: Could not parse name: {basename}")
|
| 28 |
+
return None, None
|
| 29 |
+
|
| 30 |
+
def load_examples(example_dir, generation_mode):
|
| 31 |
+
"""Load example images from the example directory"""
|
| 32 |
+
if generation_mode == "combined":
|
| 33 |
+
# Load all single PNG files from the example directory
|
| 34 |
+
files = glob.glob(os.path.join(example_dir, "*.png"))
|
| 35 |
+
print(f"Found {len(files)} combined example images in {example_dir}")
|
| 36 |
+
return files
|
| 37 |
+
else: # separate mode
|
| 38 |
+
# Find all folders in the example directory
|
| 39 |
+
folders = [f for f in glob.glob(os.path.join(example_dir, "*")) if os.path.isdir(f)]
|
| 40 |
+
# Filter folders that contain both _ini.png and _rot.png files
|
| 41 |
+
valid_folders = []
|
| 42 |
+
for folder in folders:
|
| 43 |
+
folder_name = os.path.basename(folder)
|
| 44 |
+
ini_file = os.path.join(folder, f"{folder_name}_ini.png")
|
| 45 |
+
rot_file = os.path.join(folder, f"{folder_name}_rot.png")
|
| 46 |
+
if os.path.exists(ini_file) and os.path.exists(rot_file):
|
| 47 |
+
valid_folders.append(folder)
|
| 48 |
+
|
| 49 |
+
print(f"Found {len(valid_folders)} example folder pairs in {example_dir}")
|
| 50 |
+
return valid_folders
|
| 51 |
+
|
| 52 |
+
def organize_examples(examples, generation_mode):
|
| 53 |
+
"""Organize examples by rotation axis and angle"""
|
| 54 |
+
organized = defaultdict(list)
|
| 55 |
+
for example in examples:
|
| 56 |
+
basename = os.path.basename(example)
|
| 57 |
+
if generation_mode == "combined":
|
| 58 |
+
basename = basename.split(".")[0]
|
| 59 |
+
|
| 60 |
+
axis, angle = parse_ground_truth(basename)
|
| 61 |
+
if axis is None or angle is None:
|
| 62 |
+
continue
|
| 63 |
+
|
| 64 |
+
key = (axis, angle)
|
| 65 |
+
organized[key].append(example)
|
| 66 |
+
|
| 67 |
+
# Print statistics
|
| 68 |
+
print("\nDistribution of examples by axis-angle:")
|
| 69 |
+
for key, examples_list in organized.items():
|
| 70 |
+
print(f" {key[0]}-axis, {key[1]} degrees: {len(examples_list)} examples")
|
| 71 |
+
|
| 72 |
+
return dict(organized)
|
| 73 |
+
|
| 74 |
+
def select_examples(organized_examples, test_axis, possible_angles, max_examples=1):
|
| 75 |
+
"""Select a single random example for the test case"""
|
| 76 |
+
# Collect all examples for this axis regardless of angle
|
| 77 |
+
all_examples_for_axis = []
|
| 78 |
+
for (axis, angle), example_list in organized_examples.items():
|
| 79 |
+
if axis == test_axis:
|
| 80 |
+
for example in example_list:
|
| 81 |
+
all_examples_for_axis.append((example, angle))
|
| 82 |
+
|
| 83 |
+
# If we have any examples for this axis, select one randomly
|
| 84 |
+
examples = []
|
| 85 |
+
if all_examples_for_axis:
|
| 86 |
+
selected_example = random.choice(all_examples_for_axis)
|
| 87 |
+
examples.append(selected_example)
|
| 88 |
+
else:
|
| 89 |
+
print(f"Warning: No examples found for rotation around {test_axis}-axis")
|
| 90 |
+
|
| 91 |
+
return examples
|
| 92 |
+
|
| 93 |
+
def construct_icl_prompt(axis, possible_angles, icl_examples, difficulty="easy", generation_mode="combined"):
|
| 94 |
+
"""Create prompt with in-context learning examples for the VLM"""
|
| 95 |
+
# Generate list of all possible rotation angles based on angle increment
|
| 96 |
+
'''possible_angles = []
|
| 97 |
+
current_angle = 0 + angle_increment
|
| 98 |
+
while current_angle < 360:
|
| 99 |
+
possible_angles.append(current_angle)
|
| 100 |
+
current_angle += angle_increment'''
|
| 101 |
+
|
| 102 |
+
# Common instructions for both modes
|
| 103 |
+
coordinate_system = (
|
| 104 |
+
f"The 3D Cartesian coordinate system is defined as follows: "
|
| 105 |
+
f"\n- x-axis: points horizontally from left to right (positive direction is right)"
|
| 106 |
+
f"\n- y-axis: points vertically from bottom to top (positive direction is up)"
|
| 107 |
+
f"\n- z-axis: points from inside the image toward the viewer (positive direction is out of the screen)"
|
| 108 |
+
f"\n- The origin (0,0,0) is located at the geometric center of the 3D object mesh"
|
| 109 |
+
f"\n\nWhen discussing rotations around an axis, imagine looking along the positive direction of that axis (as if looking from the origin toward the positive end)."
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
angle_constraints = (
|
| 113 |
+
f"The rotation angle is one of these specific values: {possible_angles} degrees. "
|
| 114 |
+
f"A positive angle means rotation in the CLOCKWISE direction when looking along the positive direction of the axis. "
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
# Create example section of the prompt (singular!)
|
| 118 |
+
examples_text = "\n### EXAMPLE OF ROTATION ###\n"
|
| 119 |
+
for idx, (_, angle) in enumerate(icl_examples):
|
| 120 |
+
if generation_mode == "combined":
|
| 121 |
+
img_num = idx + 1
|
| 122 |
+
examples_text += f"\nExample: Image {img_num} shows a 3D object with its left half showing the initial view and right half showing a {angle} degree rotation around the {axis}-axis.\n"
|
| 123 |
+
else: # separate mode
|
| 124 |
+
img_num_start = idx * 2 + 1
|
| 125 |
+
img_num_end = idx * 2 + 2
|
| 126 |
+
examples_text += f"\nExample: Image {img_num_start} shows the initial view and Image {img_num_end} shows the object after a {angle} degree rotation around the {axis}-axis.\n"
|
| 127 |
+
|
| 128 |
+
# Different instructions based on difficulty
|
| 129 |
+
if difficulty == "easy":
|
| 130 |
+
# For easy mode - axis is provided
|
| 131 |
+
thinking_instructions = (
|
| 132 |
+
f"IMPORTANT: Please follow this systematic approach to determine the rotation angle:"
|
| 133 |
+
f"\n\n1. First, analyze the object's features in both views to understand its structure."
|
| 134 |
+
f"\n\n2. For the {axis}-axis rotation, you must evaluate ONLY these possible rotation angles: {possible_angles}"
|
| 135 |
+
f"\n - For each angle in the list, describe what the object would look like after rotating around the {axis}-axis by that amount"
|
| 136 |
+
f"\n - Compare these descriptions with the actual second view"
|
| 137 |
+
f"\n - DO NOT make a decision until you have evaluated all possible angles in the list"
|
| 138 |
+
f"\n\n3. After evaluating all angles, choose the one that best matches the observed changes"
|
| 139 |
+
f"\n\n4. Verify your answer by mentally applying the rotation to confirm it matches the second view"
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
response_format = (
|
| 143 |
+
f"Place your detailed reasoning process in <think></think> tags. Your reasoning should include:"
|
| 144 |
+
f"\n- Systematic evaluation of possible rotation angles from the provided list"
|
| 145 |
+
f"\n- Specific visual features you used to determine your answer"
|
| 146 |
+
f"\n\nThen provide your final answer in <rotation_angle></rotation_angle> tags (use only a number from the list for angle)."
|
| 147 |
+
f"\ni.e., <think> your reasoning process here </think><rotation_angle> your predicted degrees here </rotation_angle>"
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
task_description = (
|
| 151 |
+
f"Your task is to determine the angle of rotation around the {axis}-axis in degrees."
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
else: # hard mode - axis is not provided
|
| 155 |
+
thinking_instructions = (
|
| 156 |
+
f"IMPORTANT: Please follow this systematic approach to determine the rotation:"
|
| 157 |
+
f"\n\n1. First, analyze the object's features in both views to understand its structure."
|
| 158 |
+
f"\n\n2. Consider what would happen if rotation occurred around each of the three axes (x, y, and z):"
|
| 159 |
+
f"\n - For x-axis rotation: What specific features would change and how?"
|
| 160 |
+
f"\n - For y-axis rotation: What specific features would change and how?"
|
| 161 |
+
f"\n - For z-axis rotation: What specific features would change and how?"
|
| 162 |
+
f"\n - Based on the observed changes, explain which axis makes the most sense and why."
|
| 163 |
+
f"\n\n3. Once you've determined the most likely axis, evaluate ALL of these possible rotation angles: {possible_angles}"
|
| 164 |
+
f"\n - For each angle in the list, describe what the object would look like after rotating around your chosen axis by that amount"
|
| 165 |
+
f"\n - Compare these descriptions with the actual second view"
|
| 166 |
+
f"\n - DO NOT make a decision until you have evaluated all angles in the list"
|
| 167 |
+
f"\n\n4. After evaluating all angles, choose the one that best matches the observed changes"
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
response_format = (
|
| 171 |
+
f"Place your detailed reasoning process in <think></think> tags. Your reasoning should include:"
|
| 172 |
+
f"\n- Analysis of how rotation around each axis would affect the object"
|
| 173 |
+
f"\n- Systematic evaluation of possible rotation angles from the provided list"
|
| 174 |
+
f"\n- Specific visual features you used to determine your answer"
|
| 175 |
+
f"\n\nThen provide your final answer in <rotation_axis></rotation_axis> and <rotation_angle></rotation_angle> tags respectively (use only x, y, or z for axis and only a number from the list for angle)."
|
| 176 |
+
f"\ni.e., <think> your reasoning process here </think><rotation_axis> your predicted axis here </rotation_axis><rotation_angle> your predicted degrees here </rotation_angle>"
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
task_description = (
|
| 180 |
+
f"Your task is to determine which axis the object was rotated around and by what angle."
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
# Generate the prompt based on generation mode
|
| 184 |
+
if generation_mode == "combined":
|
| 185 |
+
test_img_num = len(icl_examples) + 1
|
| 186 |
+
prompt = (
|
| 187 |
+
f"IMPORTANT: I'm showing you multiple images of 3D objects. "
|
| 188 |
+
f"The test case (final image) contains TWO separate 3D renderings side-by-side. "
|
| 189 |
+
f"\n\nThe LEFT HALF shows a 3D object in its initial orientation. "
|
| 190 |
+
f"The RIGHT HALF shows the SAME 3D object after being rotated. "
|
| 191 |
+
f"\n\nYour task is to determine the angle of rotation around the {axis}-axis in degrees."
|
| 192 |
+
f"\n\n{coordinate_system}"
|
| 193 |
+
f"\n\n{angle_constraints}"
|
| 194 |
+
f"\n\n{examples_text}"
|
| 195 |
+
f"\n\n### YOUR TASK ###"
|
| 196 |
+
f"\nNow, for Image {test_img_num}, determine the angle of rotation around the {axis}-axis."
|
| 197 |
+
f"\nBased on the examples provided, analyze Image {test_img_num} carefully."
|
| 198 |
+
f"\n\n{thinking_instructions}"
|
| 199 |
+
f"\n\n{response_format}"
|
| 200 |
+
)
|
| 201 |
+
else: # separate mode
|
| 202 |
+
test_img_start = len(icl_examples) * 2 + 1
|
| 203 |
+
test_img_end = len(icl_examples) * 2 + 2
|
| 204 |
+
prompt = (
|
| 205 |
+
f"I'm showing you multiple images of 3D objects. "
|
| 206 |
+
f"For each example or test case, two images represent the same object before and after rotation."
|
| 207 |
+
f"\n\nYour task is to determine the angle of rotation around the {axis}-axis in degrees."
|
| 208 |
+
f"\n\n{coordinate_system}"
|
| 209 |
+
f"\n\n{angle_constraints}"
|
| 210 |
+
f"\n\n{examples_text}"
|
| 211 |
+
f"\n\n### YOUR TASK ###"
|
| 212 |
+
f"\nNow, determine the angle of rotation around the {axis}-axis from Image {test_img_start} to Image {test_img_end}."
|
| 213 |
+
f"\nBased on the examples provided, analyze the rotation carefully."
|
| 214 |
+
f"\n\n{thinking_instructions}"
|
| 215 |
+
f"\n\n{response_format}"
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
return prompt
|
| 219 |
+
|
| 220 |
+
def create_metadata_jsonl_combined_icl(input_dir, example_dir, output_file, possible_angles=[45, 315], difficulty="easy", max_examples=3):
|
| 221 |
+
"""Create metadata JSONL file for all images in input_dir with in-context learning examples (combined mode)"""
|
| 222 |
+
# Get all PNG files in the input directory
|
| 223 |
+
png_files = glob.glob(os.path.join(input_dir, "*.png"))
|
| 224 |
+
|
| 225 |
+
# Sort files to ensure consistent order
|
| 226 |
+
png_files = sorted(png_files)
|
| 227 |
+
|
| 228 |
+
if not png_files:
|
| 229 |
+
print(f"No PNG files found in {input_dir}")
|
| 230 |
+
return
|
| 231 |
+
|
| 232 |
+
print(f"Found {len(png_files)} PNG files in {input_dir}")
|
| 233 |
+
|
| 234 |
+
# Load example images
|
| 235 |
+
examples = load_examples(example_dir, "combined")
|
| 236 |
+
|
| 237 |
+
# Organize examples by axis and angle
|
| 238 |
+
organized_examples = organize_examples(examples, "combined")
|
| 239 |
+
|
| 240 |
+
# Create output directory if it doesn't exist
|
| 241 |
+
output_dir = os.path.dirname(output_file)
|
| 242 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 243 |
+
|
| 244 |
+
# Get the last folder name from the input directory
|
| 245 |
+
last_folder = os.path.basename(os.path.normpath(input_dir))
|
| 246 |
+
|
| 247 |
+
# Define the target base directory
|
| 248 |
+
target_base_dir = f"/lustre/fsw/portfolios/av/users/shiyil/yunfei/MM-EUREKA/data/{last_folder}"
|
| 249 |
+
|
| 250 |
+
# Example directory - assume it's the "examples" subdirectory of input_dir
|
| 251 |
+
target_example_dir = f"{target_base_dir}/examples"
|
| 252 |
+
|
| 253 |
+
# Generate list of all possible rotation angles
|
| 254 |
+
'''possible_angles = []
|
| 255 |
+
current_angle = 0 + angle_increment
|
| 256 |
+
while current_angle < 360:
|
| 257 |
+
possible_angles.append(current_angle)
|
| 258 |
+
current_angle += angle_increment'''
|
| 259 |
+
|
| 260 |
+
# Process each file and create metadata entries
|
| 261 |
+
entries = []
|
| 262 |
+
|
| 263 |
+
for png_file in tqdm(png_files, desc="Creating metadata for combined mode with ICL"):
|
| 264 |
+
# Parse ground truth from filename
|
| 265 |
+
axis, angle = parse_ground_truth(os.path.basename(png_file))
|
| 266 |
+
|
| 267 |
+
if axis is None or angle is None:
|
| 268 |
+
print(f"Skipping {png_file} - could not parse ground truth")
|
| 269 |
+
continue
|
| 270 |
+
|
| 271 |
+
# Get the basename
|
| 272 |
+
basename = os.path.basename(png_file)
|
| 273 |
+
|
| 274 |
+
# Create the new image path for the target system
|
| 275 |
+
target_image_path = f"{target_base_dir}/{basename}"
|
| 276 |
+
|
| 277 |
+
# Select in-context examples for this test case
|
| 278 |
+
icl_examples = select_examples(organized_examples, axis, possible_angles, max_examples)
|
| 279 |
+
|
| 280 |
+
# Skip if no examples found
|
| 281 |
+
if not icl_examples:
|
| 282 |
+
print(f"Skipping {png_file} - no suitable examples found")
|
| 283 |
+
continue
|
| 284 |
+
|
| 285 |
+
# Construct prompt with in-context examples
|
| 286 |
+
prompt = construct_icl_prompt(axis, possible_angles, icl_examples, difficulty, generation_mode="combined")
|
| 287 |
+
|
| 288 |
+
# Create answer format based on difficulty WITH image path
|
| 289 |
+
if difficulty == "easy":
|
| 290 |
+
# For easy mode, only include angle in the answer (axis is provided in the prompt)
|
| 291 |
+
answer = f"<angle>{angle}</angle><image_path>{target_image_path}</image_path>"
|
| 292 |
+
else:
|
| 293 |
+
# For hard mode, include both axis and angle
|
| 294 |
+
answer = f"<axis>{axis}</axis><angle>{angle}</angle><image_path>{target_image_path}</image_path>"
|
| 295 |
+
|
| 296 |
+
# Create content array with example images and test image
|
| 297 |
+
content = []
|
| 298 |
+
|
| 299 |
+
# Add example images
|
| 300 |
+
for example_path, _ in icl_examples:
|
| 301 |
+
example_basename = os.path.basename(example_path)
|
| 302 |
+
target_example_path = f"{target_example_dir}/{example_basename}"
|
| 303 |
+
content.append({"type": "image", "image": target_example_path})
|
| 304 |
+
|
| 305 |
+
# Add test image
|
| 306 |
+
content.append({"type": "image", "image": target_image_path})
|
| 307 |
+
|
| 308 |
+
# Add prompt text
|
| 309 |
+
content.append({"type": "text", "text": prompt})
|
| 310 |
+
|
| 311 |
+
# Create entry with the content array
|
| 312 |
+
entry = {
|
| 313 |
+
"message": json.dumps([{
|
| 314 |
+
"role": "user",
|
| 315 |
+
"content": content
|
| 316 |
+
}]),
|
| 317 |
+
"answer": answer
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
entries.append(entry)
|
| 321 |
+
|
| 322 |
+
# Write entries to JSONL file
|
| 323 |
+
with open(output_file, 'w') as f:
|
| 324 |
+
for entry in entries:
|
| 325 |
+
f.write(json.dumps(entry) + '\n')
|
| 326 |
+
|
| 327 |
+
print(f"\nSummary for combined mode with ICL:")
|
| 328 |
+
print(f" Found {len(png_files)} PNG files")
|
| 329 |
+
print(f" Created metadata for {len(entries)} entries")
|
| 330 |
+
print(f" Output file: {output_file}")
|
| 331 |
+
print(f" Image paths are set to: {target_base_dir}/[filename].png")
|
| 332 |
+
print(f" Example paths are set to: {target_example_dir}/[filename].png")
|
| 333 |
+
|
| 334 |
+
def create_metadata_jsonl_separate_icl(input_dir, example_dir, output_file, possible_angles=[45, 315], difficulty="easy", max_examples=3):
|
| 335 |
+
"""Create metadata JSONL file for folders in input_dir with in-context learning examples (separate mode)"""
|
| 336 |
+
# Get all directories in the input directory (excluding the examples directory)
|
| 337 |
+
folders = [f for f in glob.glob(os.path.join(input_dir, "*"))
|
| 338 |
+
if os.path.isdir(f) and os.path.basename(f) != "examples"]
|
| 339 |
+
|
| 340 |
+
# Sort folders to ensure consistent order
|
| 341 |
+
folders = sorted(folders)
|
| 342 |
+
|
| 343 |
+
if not folders:
|
| 344 |
+
print(f"No folders found in {input_dir}")
|
| 345 |
+
return
|
| 346 |
+
|
| 347 |
+
print(f"Found {len(folders)} folders in {input_dir}")
|
| 348 |
+
|
| 349 |
+
# Load example folders
|
| 350 |
+
examples = load_examples(example_dir, "separate")
|
| 351 |
+
|
| 352 |
+
# Organize examples by axis and angle
|
| 353 |
+
organized_examples = organize_examples(examples, "separate")
|
| 354 |
+
|
| 355 |
+
# Create output directory if it doesn't exist
|
| 356 |
+
output_dir = os.path.dirname(output_file)
|
| 357 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 358 |
+
|
| 359 |
+
# Get the last folder name from the input directory
|
| 360 |
+
last_folder = os.path.basename(os.path.normpath(input_dir))
|
| 361 |
+
|
| 362 |
+
# Define the target base directory
|
| 363 |
+
target_base_dir = f"/lustre/fsw/portfolios/av/users/shiyil/yunfei/MM-EUREKA/data/{last_folder}"
|
| 364 |
+
|
| 365 |
+
# Example directory is always a subdirectory called 'examples'
|
| 366 |
+
target_example_dir = f"{target_base_dir}/examples"
|
| 367 |
+
|
| 368 |
+
# Generate list of all possible rotation angles
|
| 369 |
+
'''possible_angles = []
|
| 370 |
+
current_angle = 0 + angle_increment
|
| 371 |
+
while current_angle < 360:
|
| 372 |
+
possible_angles.append(current_angle)
|
| 373 |
+
current_angle += angle_increment'''
|
| 374 |
+
|
| 375 |
+
# Process each folder and create metadata entries
|
| 376 |
+
entries = []
|
| 377 |
+
valid_folders = 0
|
| 378 |
+
|
| 379 |
+
for folder in tqdm(folders, desc="Creating metadata for separate mode with ICL"):
|
| 380 |
+
folder_name = os.path.basename(folder)
|
| 381 |
+
|
| 382 |
+
# Parse ground truth from folder name
|
| 383 |
+
axis, angle = parse_ground_truth(folder_name)
|
| 384 |
+
|
| 385 |
+
if axis is None or angle is None:
|
| 386 |
+
print(f"Skipping {folder} - could not parse ground truth")
|
| 387 |
+
continue
|
| 388 |
+
|
| 389 |
+
# Check for the two required images in the folder
|
| 390 |
+
ini_path = os.path.join(folder, f"{folder_name}_ini.png")
|
| 391 |
+
rot_path = os.path.join(folder, f"{folder_name}_rot.png")
|
| 392 |
+
|
| 393 |
+
if not os.path.exists(ini_path):
|
| 394 |
+
print(f"Skipping {folder} - missing initial view image")
|
| 395 |
+
continue
|
| 396 |
+
|
| 397 |
+
if not os.path.exists(rot_path):
|
| 398 |
+
print(f"Skipping {folder} - missing rotated view image")
|
| 399 |
+
continue
|
| 400 |
+
|
| 401 |
+
# Create target paths for remote system
|
| 402 |
+
target_folder_path = f"{target_base_dir}/{folder_name}"
|
| 403 |
+
target_ini_path = f"{target_folder_path}/{folder_name}_ini.png"
|
| 404 |
+
target_rot_path = f"{target_folder_path}/{folder_name}_rot.png"
|
| 405 |
+
|
| 406 |
+
# Select in-context examples for this test case
|
| 407 |
+
icl_examples = select_examples(organized_examples, axis, possible_angles, max_examples)
|
| 408 |
+
|
| 409 |
+
# Skip if no examples found
|
| 410 |
+
if not icl_examples:
|
| 411 |
+
print(f"Skipping {folder} - no suitable examples found")
|
| 412 |
+
continue
|
| 413 |
+
|
| 414 |
+
# Construct prompt with in-context examples
|
| 415 |
+
prompt = construct_icl_prompt(axis, possible_angles, icl_examples, difficulty, generation_mode="separate")
|
| 416 |
+
|
| 417 |
+
# Create answer format based on difficulty WITH folder path
|
| 418 |
+
if difficulty == "easy":
|
| 419 |
+
# For easy mode, only include angle in the answer (axis is provided in the prompt)
|
| 420 |
+
answer = f"<angle>{angle}</angle><image_path>{target_folder_path}</image_path>"
|
| 421 |
+
else:
|
| 422 |
+
# For hard mode, include both axis and angle
|
| 423 |
+
answer = f"<axis>{axis}</axis><angle>{angle}</angle><image_path>{target_folder_path}</image_path>"
|
| 424 |
+
|
| 425 |
+
# Create content array with example images and test images
|
| 426 |
+
content = []
|
| 427 |
+
|
| 428 |
+
# Add example image pairs
|
| 429 |
+
for example_folder, _ in icl_examples:
|
| 430 |
+
example_name = os.path.basename(example_folder)
|
| 431 |
+
target_example_ini = f"{target_example_dir}/{example_name}/{example_name}_ini.png"
|
| 432 |
+
target_example_rot = f"{target_example_dir}/{example_name}/{example_name}_rot.png"
|
| 433 |
+
|
| 434 |
+
content.append({"type": "image", "image": target_example_ini})
|
| 435 |
+
content.append({"type": "image", "image": target_example_rot})
|
| 436 |
+
|
| 437 |
+
# Add test image pair
|
| 438 |
+
content.append({"type": "image", "image": target_ini_path})
|
| 439 |
+
content.append({"type": "image", "image": target_rot_path})
|
| 440 |
+
|
| 441 |
+
# Add prompt text
|
| 442 |
+
content.append({"type": "text", "text": prompt})
|
| 443 |
+
|
| 444 |
+
# Create entry with both image paths
|
| 445 |
+
entry = {
|
| 446 |
+
"message": json.dumps([{
|
| 447 |
+
"role": "user",
|
| 448 |
+
"content": content
|
| 449 |
+
}]),
|
| 450 |
+
"answer": answer
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
entries.append(entry)
|
| 454 |
+
valid_folders += 1
|
| 455 |
+
|
| 456 |
+
# Write entries to JSONL file
|
| 457 |
+
with open(output_file, 'w') as f:
|
| 458 |
+
for entry in entries:
|
| 459 |
+
f.write(json.dumps(entry) + '\n')
|
| 460 |
+
|
| 461 |
+
print(f"\nSummary for separate mode with ICL:")
|
| 462 |
+
print(f" Found {len(folders)} folders")
|
| 463 |
+
print(f" Created metadata for {valid_folders} valid folders")
|
| 464 |
+
print(f" Output file: {output_file}")
|
| 465 |
+
print(f" Image paths format: {target_base_dir}/[folder_name]/[folder_name]_[ini/rot].png")
|
| 466 |
+
print(f" Example paths format: {target_example_dir}/[folder_name]/[folder_name]_[ini/rot].png")
|
| 467 |
+
|
| 468 |
+
def main():
|
| 469 |
+
parser = argparse.ArgumentParser(description="Create metadata JSONL for rotation dataset with in-context learning")
|
| 470 |
+
parser.add_argument('--input-dir', type=str, required=True,
|
| 471 |
+
help="Directory containing rotation dataset images or folders")
|
| 472 |
+
parser.add_argument('--example-dir', type=str, required=True,
|
| 473 |
+
help="Directory containing example images or folders for in-context learning")
|
| 474 |
+
parser.add_argument('--output-file', type=str, default="rotation_metadata_icl.jsonl",
|
| 475 |
+
help="Output JSONL file path")
|
| 476 |
+
parser.add_argument('--possible-angles', type=int, nargs='+', default=[45, 315],
|
| 477 |
+
help="List of possible rotation angles in degrees (e.g., 45 315)")
|
| 478 |
+
parser.add_argument('--difficulty', type=str, choices=["easy", "hard"], default="easy",
|
| 479 |
+
help="Difficulty mode: easy (axis provided) or hard (axis not provided)")
|
| 480 |
+
parser.add_argument('--generation-mode', type=str, choices=["combined", "separate"], default="combined",
|
| 481 |
+
help="Mode for dataset generation (combined = one image with both views, separate = folder with two images)")
|
| 482 |
+
parser.add_argument('--max-examples', type=int, default=1,
|
| 483 |
+
help="Maximum number of examples to include for each test case (default: 1)")
|
| 484 |
+
parser.add_argument('--random-seed', type=int, default=None,
|
| 485 |
+
help="Random seed for example selection (None for true randomness)")
|
| 486 |
+
|
| 487 |
+
args = parser.parse_args()
|
| 488 |
+
|
| 489 |
+
# Set random seed for reproducibility (or use None for true randomness)
|
| 490 |
+
random.seed(args.random_seed)
|
| 491 |
+
|
| 492 |
+
print(f"Creating metadata JSONL for rotation dataset with in-context learning:")
|
| 493 |
+
print(f"Input directory: {args.input_dir}")
|
| 494 |
+
print(f"Example directory: {args.example_dir}")
|
| 495 |
+
print(f"Output file: {args.output_file}")
|
| 496 |
+
print(f"Possible angles: {args.possible_angles}")
|
| 497 |
+
print(f"Difficulty mode: {args.difficulty}")
|
| 498 |
+
print(f"Generation mode: {args.generation_mode}")
|
| 499 |
+
print(f"Max examples per test case: {args.max_examples}")
|
| 500 |
+
|
| 501 |
+
if args.random_seed is not None:
|
| 502 |
+
print(f"Using fixed random seed: {args.random_seed}")
|
| 503 |
+
else:
|
| 504 |
+
print("Using true randomness (different examples selection each run)")
|
| 505 |
+
|
| 506 |
+
# Fix the indentation error here:
|
| 507 |
+
if args.example_dir is None and os.path.exists(os.path.join(args.input_dir, "examples")):
|
| 508 |
+
args.example_dir = os.path.join(args.input_dir, "examples")
|
| 509 |
+
print(f"Using examples directory: {args.example_dir}")
|
| 510 |
+
|
| 511 |
+
if args.generation_mode == "combined":
|
| 512 |
+
create_metadata_jsonl_combined_icl(
|
| 513 |
+
input_dir=args.input_dir,
|
| 514 |
+
example_dir=args.example_dir,
|
| 515 |
+
output_file=args.output_file,
|
| 516 |
+
possible_angles=args.possible_angles, # Updated from angle_increment
|
| 517 |
+
difficulty=args.difficulty,
|
| 518 |
+
max_examples=args.max_examples
|
| 519 |
+
)
|
| 520 |
+
else: # separate mode
|
| 521 |
+
create_metadata_jsonl_separate_icl(
|
| 522 |
+
input_dir=args.input_dir,
|
| 523 |
+
example_dir=args.example_dir,
|
| 524 |
+
output_file=args.output_file,
|
| 525 |
+
possible_angles=args.possible_angles, # Updated from angle_increment
|
| 526 |
+
difficulty=args.difficulty,
|
| 527 |
+
max_examples=args.max_examples
|
| 528 |
+
)
|
| 529 |
+
if __name__ == "__main__":
|
| 530 |
+
main()
|