| import os |
| import re |
| import glob |
| import json |
| import random |
| import argparse |
| from tqdm import tqdm |
| from pathlib import Path |
| from collections import defaultdict |
|
|
| def parse_ground_truth(name): |
| """Extract ground truth rotation axis and angle from filename or folder name""" |
| |
| basename = name.split(".")[0] if "." in name else name |
| |
| parts = basename.split("_") |
| if len(parts) >= 4: |
| rotation_axis = parts[-2] |
| rotation_angle = int(parts[-1]) |
| |
| |
| if rotation_angle < 0: |
| rotation_angle += 360 |
| |
| return rotation_axis, rotation_angle |
| |
| print(f"Warning: Could not parse name: {basename}") |
| return None, None |
|
|
| def load_examples(example_dir, generation_mode): |
| """Load example images from the example directory""" |
| if generation_mode == "combined": |
| |
| files = glob.glob(os.path.join(example_dir, "*.png")) |
| print(f"Found {len(files)} combined example images in {example_dir}") |
| return files |
| else: |
| |
| folders = [f for f in glob.glob(os.path.join(example_dir, "*")) if os.path.isdir(f)] |
| |
| valid_folders = [] |
| for folder in folders: |
| folder_name = os.path.basename(folder) |
| ini_file = os.path.join(folder, f"{folder_name}_ini.png") |
| rot_file = os.path.join(folder, f"{folder_name}_rot.png") |
| if os.path.exists(ini_file) and os.path.exists(rot_file): |
| valid_folders.append(folder) |
| |
| print(f"Found {len(valid_folders)} example folder pairs in {example_dir}") |
| return valid_folders |
|
|
| def organize_examples(examples, generation_mode): |
| """Organize examples by rotation axis and angle""" |
| organized = defaultdict(list) |
| for example in examples: |
| basename = os.path.basename(example) |
| if generation_mode == "combined": |
| basename = basename.split(".")[0] |
| |
| axis, angle = parse_ground_truth(basename) |
| if axis is None or angle is None: |
| continue |
| |
| key = (axis, angle) |
| organized[key].append(example) |
| |
| |
| print("\nDistribution of examples by axis-angle:") |
| for key, examples_list in organized.items(): |
| print(f" {key[0]}-axis, {key[1]} degrees: {len(examples_list)} examples") |
| |
| return dict(organized) |
|
|
| def select_examples(organized_examples, test_axis, possible_angles, max_examples=1): |
| """Select a single random example for the test case""" |
| |
| all_examples_for_axis = [] |
| for (axis, angle), example_list in organized_examples.items(): |
| if axis == test_axis: |
| for example in example_list: |
| all_examples_for_axis.append((example, angle)) |
| |
| |
| examples = [] |
| if all_examples_for_axis: |
| selected_example = random.choice(all_examples_for_axis) |
| examples.append(selected_example) |
| else: |
| print(f"Warning: No examples found for rotation around {test_axis}-axis") |
| |
| return examples |
|
|
| def construct_icl_prompt(axis, possible_angles, icl_examples, difficulty="easy", generation_mode="combined"): |
| """Create prompt with in-context learning examples for the VLM""" |
| |
| '''possible_angles = [] |
| current_angle = 0 + angle_increment |
| while current_angle < 360: |
| possible_angles.append(current_angle) |
| current_angle += angle_increment''' |
| |
| |
| coordinate_system = ( |
| f"The 3D Cartesian coordinate system is defined as follows: " |
| f"\n- x-axis: points horizontally from left to right (positive direction is right)" |
| f"\n- y-axis: points vertically from bottom to top (positive direction is up)" |
| f"\n- z-axis: points from inside the image toward the viewer (positive direction is out of the screen)" |
| f"\n- The origin (0,0,0) is located at the geometric center of the 3D object mesh" |
| 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)." |
| ) |
| |
| angle_constraints = ( |
| f"The rotation angle is one of these specific values: {possible_angles} degrees. " |
| f"A positive angle means rotation in the CLOCKWISE direction when looking along the positive direction of the axis. " |
| ) |
| |
| |
| examples_text = "\n### EXAMPLE OF ROTATION ###\n" |
| for idx, (_, angle) in enumerate(icl_examples): |
| if generation_mode == "combined": |
| img_num = idx + 1 |
| 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" |
| else: |
| img_num_start = idx * 2 + 1 |
| img_num_end = idx * 2 + 2 |
| 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" |
| |
| |
| if difficulty == "easy": |
| |
| thinking_instructions = ( |
| f"IMPORTANT: Please follow this systematic approach to determine the rotation angle:" |
| f"\n\n1. First, analyze the object's features in both views to understand its structure." |
| f"\n\n2. For the {axis}-axis rotation, you must evaluate ONLY these possible rotation angles: {possible_angles}" |
| f"\n - For each angle in the list, describe what the object would look like after rotating around the {axis}-axis by that amount" |
| f"\n - Compare these descriptions with the actual second view" |
| f"\n - DO NOT make a decision until you have evaluated all possible angles in the list" |
| f"\n\n3. After evaluating all angles, choose the one that best matches the observed changes" |
| f"\n\n4. Verify your answer by mentally applying the rotation to confirm it matches the second view" |
| ) |
| |
| response_format = ( |
| f"Place your detailed reasoning process in <think></think> tags. Your reasoning should include:" |
| f"\n- Systematic evaluation of possible rotation angles from the provided list" |
| f"\n- Specific visual features you used to determine your answer" |
| f"\n\nThen provide your final answer in <rotation_angle></rotation_angle> tags (use only a number from the list for angle)." |
| f"\ni.e., <think> your reasoning process here </think><rotation_angle> your predicted degrees here </rotation_angle>" |
| ) |
| |
| task_description = ( |
| f"Your task is to determine the angle of rotation around the {axis}-axis in degrees." |
| ) |
| |
| else: |
| thinking_instructions = ( |
| f"IMPORTANT: Please follow this systematic approach to determine the rotation:" |
| f"\n\n1. First, analyze the object's features in both views to understand its structure." |
| f"\n\n2. Consider what would happen if rotation occurred around each of the three axes (x, y, and z):" |
| f"\n - For x-axis rotation: What specific features would change and how?" |
| f"\n - For y-axis rotation: What specific features would change and how?" |
| f"\n - For z-axis rotation: What specific features would change and how?" |
| f"\n - Based on the observed changes, explain which axis makes the most sense and why." |
| f"\n\n3. Once you've determined the most likely axis, evaluate ALL of these possible rotation angles: {possible_angles}" |
| f"\n - For each angle in the list, describe what the object would look like after rotating around your chosen axis by that amount" |
| f"\n - Compare these descriptions with the actual second view" |
| f"\n - DO NOT make a decision until you have evaluated all angles in the list" |
| f"\n\n4. After evaluating all angles, choose the one that best matches the observed changes" |
| ) |
| |
| response_format = ( |
| f"Place your detailed reasoning process in <think></think> tags. Your reasoning should include:" |
| f"\n- Analysis of how rotation around each axis would affect the object" |
| f"\n- Systematic evaluation of possible rotation angles from the provided list" |
| f"\n- Specific visual features you used to determine your answer" |
| 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)." |
| 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>" |
| ) |
| |
| task_description = ( |
| f"Your task is to determine which axis the object was rotated around and by what angle." |
| ) |
| |
| |
| if generation_mode == "combined": |
| test_img_num = len(icl_examples) + 1 |
| prompt = ( |
| f"IMPORTANT: I'm showing you multiple images of 3D objects. " |
| f"The test case (final image) contains TWO separate 3D renderings side-by-side. " |
| f"\n\nThe LEFT HALF shows a 3D object in its initial orientation. " |
| f"The RIGHT HALF shows the SAME 3D object after being rotated. " |
| f"\n\nYour task is to determine the angle of rotation around the {axis}-axis in degrees." |
| f"\n\n{coordinate_system}" |
| f"\n\n{angle_constraints}" |
| f"\n\n{examples_text}" |
| f"\n\n### YOUR TASK ###" |
| f"\nNow, for Image {test_img_num}, determine the angle of rotation around the {axis}-axis." |
| f"\nBased on the examples provided, analyze Image {test_img_num} carefully." |
| f"\n\n{thinking_instructions}" |
| f"\n\n{response_format}" |
| ) |
| else: |
| test_img_start = len(icl_examples) * 2 + 1 |
| test_img_end = len(icl_examples) * 2 + 2 |
| prompt = ( |
| f"I'm showing you multiple images of 3D objects. " |
| f"For each example or test case, two images represent the same object before and after rotation." |
| f"\n\nYour task is to determine the angle of rotation around the {axis}-axis in degrees." |
| f"\n\n{coordinate_system}" |
| f"\n\n{angle_constraints}" |
| f"\n\n{examples_text}" |
| f"\n\n### YOUR TASK ###" |
| f"\nNow, determine the angle of rotation around the {axis}-axis from Image {test_img_start} to Image {test_img_end}." |
| f"\nBased on the examples provided, analyze the rotation carefully." |
| f"\n\n{thinking_instructions}" |
| f"\n\n{response_format}" |
| ) |
| |
| return prompt |
|
|
| def create_metadata_jsonl_combined_icl(input_dir, example_dir, output_file, possible_angles=[45, 315], difficulty="easy", max_examples=3): |
| """Create metadata JSONL file for all images in input_dir with in-context learning examples (combined mode)""" |
| |
| png_files = glob.glob(os.path.join(input_dir, "*.png")) |
| |
| |
| png_files = sorted(png_files) |
| |
| if not png_files: |
| print(f"No PNG files found in {input_dir}") |
| return |
| |
| print(f"Found {len(png_files)} PNG files in {input_dir}") |
| |
| |
| examples = load_examples(example_dir, "combined") |
| |
| |
| organized_examples = organize_examples(examples, "combined") |
| |
| |
| output_dir = os.path.dirname(output_file) |
| os.makedirs(output_dir, exist_ok=True) |
| |
| |
| last_folder = os.path.basename(os.path.normpath(input_dir)) |
| |
| |
| target_base_dir = f"/lustre/fsw/portfolios/av/users/shiyil/yunfei/MM-EUREKA/data/{last_folder}" |
| |
| |
| target_example_dir = f"{target_base_dir}/examples" |
| |
| |
| '''possible_angles = [] |
| current_angle = 0 + angle_increment |
| while current_angle < 360: |
| possible_angles.append(current_angle) |
| current_angle += angle_increment''' |
| |
| |
| entries = [] |
| |
| for png_file in tqdm(png_files, desc="Creating metadata for combined mode with ICL"): |
| |
| axis, angle = parse_ground_truth(os.path.basename(png_file)) |
| |
| if axis is None or angle is None: |
| print(f"Skipping {png_file} - could not parse ground truth") |
| continue |
| |
| |
| basename = os.path.basename(png_file) |
| |
| |
| target_image_path = f"{target_base_dir}/{basename}" |
| |
| |
| icl_examples = select_examples(organized_examples, axis, possible_angles, max_examples) |
| |
| |
| if not icl_examples: |
| print(f"Skipping {png_file} - no suitable examples found") |
| continue |
| |
| |
| prompt = construct_icl_prompt(axis, possible_angles, icl_examples, difficulty, generation_mode="combined") |
| |
| |
| if difficulty == "easy": |
| |
| answer = f"<angle>{angle}</angle><image_path>{target_image_path}</image_path>" |
| else: |
| |
| answer = f"<axis>{axis}</axis><angle>{angle}</angle><image_path>{target_image_path}</image_path>" |
| |
| |
| content = [] |
| |
| |
| for example_path, _ in icl_examples: |
| example_basename = os.path.basename(example_path) |
| target_example_path = f"{target_example_dir}/{example_basename}" |
| content.append({"type": "image", "image": target_example_path}) |
| |
| |
| content.append({"type": "image", "image": target_image_path}) |
| |
| |
| content.append({"type": "text", "text": prompt}) |
| |
| |
| entry = { |
| "message": json.dumps([{ |
| "role": "user", |
| "content": content |
| }]), |
| "answer": answer |
| } |
| |
| entries.append(entry) |
| |
| |
| with open(output_file, 'w') as f: |
| for entry in entries: |
| f.write(json.dumps(entry) + '\n') |
| |
| print(f"\nSummary for combined mode with ICL:") |
| print(f" Found {len(png_files)} PNG files") |
| print(f" Created metadata for {len(entries)} entries") |
| print(f" Output file: {output_file}") |
| print(f" Image paths are set to: {target_base_dir}/[filename].png") |
| print(f" Example paths are set to: {target_example_dir}/[filename].png") |
|
|
| def create_metadata_jsonl_separate_icl(input_dir, example_dir, output_file, possible_angles=[45, 315], difficulty="easy", max_examples=3): |
| """Create metadata JSONL file for folders in input_dir with in-context learning examples (separate mode)""" |
| |
| folders = [f for f in glob.glob(os.path.join(input_dir, "*")) |
| if os.path.isdir(f) and os.path.basename(f) != "examples"] |
| |
| |
| folders = sorted(folders) |
| |
| if not folders: |
| print(f"No folders found in {input_dir}") |
| return |
| |
| print(f"Found {len(folders)} folders in {input_dir}") |
| |
| |
| examples = load_examples(example_dir, "separate") |
| |
| |
| organized_examples = organize_examples(examples, "separate") |
| |
| |
| output_dir = os.path.dirname(output_file) |
| os.makedirs(output_dir, exist_ok=True) |
| |
| |
| last_folder = os.path.basename(os.path.normpath(input_dir)) |
| |
| |
| target_base_dir = f"/lustre/fsw/portfolios/av/users/shiyil/yunfei/MM-EUREKA/data/{last_folder}" |
| |
| |
| target_example_dir = f"{target_base_dir}/examples" |
| |
| |
| '''possible_angles = [] |
| current_angle = 0 + angle_increment |
| while current_angle < 360: |
| possible_angles.append(current_angle) |
| current_angle += angle_increment''' |
| |
| |
| entries = [] |
| valid_folders = 0 |
| |
| for folder in tqdm(folders, desc="Creating metadata for separate mode with ICL"): |
| folder_name = os.path.basename(folder) |
| |
| |
| axis, angle = parse_ground_truth(folder_name) |
| |
| if axis is None or angle is None: |
| print(f"Skipping {folder} - could not parse ground truth") |
| continue |
| |
| |
| ini_path = os.path.join(folder, f"{folder_name}_ini.png") |
| rot_path = os.path.join(folder, f"{folder_name}_rot.png") |
| |
| if not os.path.exists(ini_path): |
| print(f"Skipping {folder} - missing initial view image") |
| continue |
| |
| if not os.path.exists(rot_path): |
| print(f"Skipping {folder} - missing rotated view image") |
| continue |
| |
| |
| target_folder_path = f"{target_base_dir}/{folder_name}" |
| target_ini_path = f"{target_folder_path}/{folder_name}_ini.png" |
| target_rot_path = f"{target_folder_path}/{folder_name}_rot.png" |
| |
| |
| icl_examples = select_examples(organized_examples, axis, possible_angles, max_examples) |
| |
| |
| if not icl_examples: |
| print(f"Skipping {folder} - no suitable examples found") |
| continue |
| |
| |
| prompt = construct_icl_prompt(axis, possible_angles, icl_examples, difficulty, generation_mode="separate") |
| |
| |
| if difficulty == "easy": |
| |
| answer = f"<angle>{angle}</angle><image_path>{target_folder_path}</image_path>" |
| else: |
| |
| answer = f"<axis>{axis}</axis><angle>{angle}</angle><image_path>{target_folder_path}</image_path>" |
| |
| |
| content = [] |
| |
| |
| for example_folder, _ in icl_examples: |
| example_name = os.path.basename(example_folder) |
| target_example_ini = f"{target_example_dir}/{example_name}/{example_name}_ini.png" |
| target_example_rot = f"{target_example_dir}/{example_name}/{example_name}_rot.png" |
| |
| content.append({"type": "image", "image": target_example_ini}) |
| content.append({"type": "image", "image": target_example_rot}) |
| |
| |
| content.append({"type": "image", "image": target_ini_path}) |
| content.append({"type": "image", "image": target_rot_path}) |
| |
| |
| content.append({"type": "text", "text": prompt}) |
| |
| |
| entry = { |
| "message": json.dumps([{ |
| "role": "user", |
| "content": content |
| }]), |
| "answer": answer |
| } |
| |
| entries.append(entry) |
| valid_folders += 1 |
| |
| |
| with open(output_file, 'w') as f: |
| for entry in entries: |
| f.write(json.dumps(entry) + '\n') |
| |
| print(f"\nSummary for separate mode with ICL:") |
| print(f" Found {len(folders)} folders") |
| print(f" Created metadata for {valid_folders} valid folders") |
| print(f" Output file: {output_file}") |
| print(f" Image paths format: {target_base_dir}/[folder_name]/[folder_name]_[ini/rot].png") |
| print(f" Example paths format: {target_example_dir}/[folder_name]/[folder_name]_[ini/rot].png") |
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Create metadata JSONL for rotation dataset with in-context learning") |
| parser.add_argument('--input-dir', type=str, required=True, |
| help="Directory containing rotation dataset images or folders") |
| parser.add_argument('--example-dir', type=str, required=True, |
| help="Directory containing example images or folders for in-context learning") |
| parser.add_argument('--output-file', type=str, default="rotation_metadata_icl.jsonl", |
| help="Output JSONL file path") |
| parser.add_argument('--possible-angles', type=int, nargs='+', default=[45, 315], |
| help="List of possible rotation angles in degrees (e.g., 45 315)") |
| parser.add_argument('--difficulty', type=str, choices=["easy", "hard"], default="easy", |
| help="Difficulty mode: easy (axis provided) or hard (axis not provided)") |
| parser.add_argument('--generation-mode', type=str, choices=["combined", "separate"], default="combined", |
| help="Mode for dataset generation (combined = one image with both views, separate = folder with two images)") |
| parser.add_argument('--max-examples', type=int, default=1, |
| help="Maximum number of examples to include for each test case (default: 1)") |
| parser.add_argument('--random-seed', type=int, default=None, |
| help="Random seed for example selection (None for true randomness)") |
| |
| args = parser.parse_args() |
| |
| |
| random.seed(args.random_seed) |
| |
| print(f"Creating metadata JSONL for rotation dataset with in-context learning:") |
| print(f"Input directory: {args.input_dir}") |
| print(f"Example directory: {args.example_dir}") |
| print(f"Output file: {args.output_file}") |
| print(f"Possible angles: {args.possible_angles}") |
| print(f"Difficulty mode: {args.difficulty}") |
| print(f"Generation mode: {args.generation_mode}") |
| print(f"Max examples per test case: {args.max_examples}") |
| |
| if args.random_seed is not None: |
| print(f"Using fixed random seed: {args.random_seed}") |
| else: |
| print("Using true randomness (different examples selection each run)") |
|
|
| |
| if args.example_dir is None and os.path.exists(os.path.join(args.input_dir, "examples")): |
| args.example_dir = os.path.join(args.input_dir, "examples") |
| print(f"Using examples directory: {args.example_dir}") |
| |
| if args.generation_mode == "combined": |
| create_metadata_jsonl_combined_icl( |
| input_dir=args.input_dir, |
| example_dir=args.example_dir, |
| output_file=args.output_file, |
| possible_angles=args.possible_angles, |
| difficulty=args.difficulty, |
| max_examples=args.max_examples |
| ) |
| else: |
| create_metadata_jsonl_separate_icl( |
| input_dir=args.input_dir, |
| example_dir=args.example_dir, |
| output_file=args.output_file, |
| possible_angles=args.possible_angles, |
| difficulty=args.difficulty, |
| max_examples=args.max_examples |
| ) |
| if __name__ == "__main__": |
| main() |