File size: 16,236 Bytes
86b0043
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
import os
import re
import glob
import json
import argparse
from tqdm import tqdm
from pathlib import Path

def parse_ground_truth(name):
    """Extract ground truth rotation axis and angle from filename or folder name"""
    # Remove file extension if present
    basename = name.split(".")[0] if "." in name else name
    
    parts = basename.split("_")
    if len(parts) >= 4:  # figXXXX_XXX_axis_angle
        rotation_axis = parts[-2]  # Second to last element is axis
        rotation_angle = int(parts[-1])  # Last element is angle
        
        # Convert negative angles to 0-360 range
        if rotation_angle < 0:
            rotation_angle += 360
            
        return rotation_axis, rotation_angle
    
    print(f"Warning: Could not parse name: {basename}")
    return None, None

def construct_prompt(axis, angle_increment, difficulty="easy", generation_mode="combined"):
    """Create prompt for the VLM based on difficulty mode and generation mode"""
    # Generate list of all possible rotation angles based on angle increment
    possible_angles = []
    current_angle = 0 + angle_increment
    while current_angle < 360:
        possible_angles.append(current_angle)
        current_angle += angle_increment
    
    # Common instructions for both modes
    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\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 always a multiple of {angle_increment} degrees between 0 and 360 degrees inclusive. "
        f"A positive angle means rotation in the CLOCKWISE direction when looking along the positive direction of the axis. "
    )
    
    # Different instructions based on difficulty
    if difficulty == "easy":
        # For easy mode - axis is provided
        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 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 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:  # hard mode - axis is not provided
        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 <thinking></thinking> 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., <thinking> your reasoning process here </thinking><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."
        )
    
    # Generate the prompt based on generation mode
    if generation_mode == "combined":
        prompt = (
            f"IMPORTANT: The image I'm showing you contains TWO separate 3D renderings side-by-side. "
            f"This is a single image file with two distinct rendered views placed next to each other. "
            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\n{task_description}"
            f"\n\n{coordinate_system}"
            f"\n\n{angle_constraints}"
            f"\n\n{thinking_instructions}"
            f"\n\n{response_format}"
        )
    else:  # separate mode
        prompt = (
            f"I'm showing you TWO images of the same 3D object. "
            f"The FIRST image shows the object in its initial orientation. "
            f"The SECOND image shows the object after being rotated. "
            f"\n\n{task_description}"
            f"\n\n{coordinate_system}"
            f"\n\n{angle_constraints}"
            f"\n\n{thinking_instructions}"
            f"\n\n{response_format}"
        )
            
    return prompt

def create_metadata_jsonl_combined(input_dir, output_file, angle_increment=30, difficulty="easy"):
    """Create metadata JSONL file for all images in input_dir (combined mode)"""
    # Get all PNG files in the input directory
    png_files = glob.glob(os.path.join(input_dir, "*.png"))
    
    # Sort files to ensure consistent order
    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}")
    
    # Create output directory if it doesn't exist
    output_dir = os.path.dirname(output_file)
    os.makedirs(output_dir, exist_ok=True)
    
    # Get the last folder name from the input directory
    last_folder = os.path.basename(os.path.normpath(input_dir))
    
    # Define the target base directory
    target_base_dir = f"/lustre/fsw/portfolios/av/users/shiyil/yunfei/MM-EUREKA/data/{last_folder}"
    
    # Process each file and create metadata entries
    entries = []
    
    for png_file in tqdm(png_files, desc="Creating metadata for combined mode"):
        # Parse ground truth from filename
        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
        
        # Get the basename
        basename = os.path.basename(png_file)
        
        # Create the new image path for the target system
        target_image_path = f"{target_base_dir}/{basename}"
        
        # Construct prompt for combined mode
        prompt = construct_prompt(axis, angle_increment, difficulty, generation_mode="combined")
        
        # Create answer format based on difficulty WITH image path
        if difficulty == "easy":
            # For easy mode, only include angle in the answer (axis is provided in the prompt)
            answer = f"<angle>{angle}</angle><image_path>{target_image_path}</image_path>"
        else:
            # For hard mode, include both axis and angle
            answer = f"<axis>{axis}</axis><angle>{angle}</angle><image_path>{target_image_path}</image_path>"
        
        # Create entry with the modified image path
        entry = {
            "message": json.dumps([{
                "role": "user",
                "content": [
                    {
                        "type": "image",
                        "image": target_image_path
                    },
                    {
                        "type": "text",
                        "text": prompt
                    }
                ]
            }]),
            "answer": answer
        }
        
        entries.append(entry)
    
    # Write entries to JSONL file
    with open(output_file, 'w') as f:
        for entry in entries:
            f.write(json.dumps(entry) + '\n')
    
    print(f"\nSummary for combined mode:")
    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")

def create_metadata_jsonl_separate(input_dir, output_file, angle_increment=30, difficulty="easy"):
    """Create metadata JSONL file for folders in input_dir (separate mode)"""
    # Get all directories in the input directory
    folders = [f for f in glob.glob(os.path.join(input_dir, "*")) if os.path.isdir(f)]
    
    # Sort folders to ensure consistent order
    folders = sorted(folders)
    
    if not folders:
        print(f"No folders found in {input_dir}")
        return
    
    print(f"Found {len(folders)} folders in {input_dir}")
    
    # Create output directory if it doesn't exist
    output_dir = os.path.dirname(output_file)
    os.makedirs(output_dir, exist_ok=True)
    
    # Get the last folder name from the input directory
    last_folder = os.path.basename(os.path.normpath(input_dir))
    
    # Define the target base directory
    target_base_dir = f"/lustre/fsw/portfolios/av/users/shiyil/yunfei/MM-EUREKA/data/{last_folder}"
    
    # Process each folder and create metadata entries
    entries = []
    valid_folders = 0
    
    for folder in tqdm(folders, desc="Creating metadata for separate mode"):
        folder_name = os.path.basename(folder)
        
        # Parse ground truth from folder name
        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
        
        # Check for the two required images in the folder
        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
        
        # Create target paths for remote system
        target_folder_path = f"{target_base_dir}/{folder_name}"
        target_ini_path = f"{target_base_dir}/{folder_name}/{folder_name}_ini.png"
        target_rot_path = f"{target_base_dir}/{folder_name}/{folder_name}_rot.png"
        
        # Construct prompt for separate mode
        prompt = construct_prompt(axis, angle_increment, difficulty, generation_mode="separate")
        
        # Create answer format based on difficulty WITH folder path
        if difficulty == "easy":
            # For easy mode, only include angle in the answer (axis is provided in the prompt)
            answer = f"<angle>{angle}</angle><image_path>{target_folder_path}</image_path>"
        else:
            # For hard mode, include both axis and angle
            answer = f"<axis>{axis}</axis><angle>{angle}</angle><image_path>{target_folder_path}</image_path>"
        
        # Create entry with both image paths
        entry = {
            "message": json.dumps([{
                "role": "user",
                "content": [
                    {"type": "image", "image": target_ini_path},
                    {"type": "image", "image": target_rot_path},
                    {"type": "text", "text": prompt}
                ]
            }]),
            "answer": answer
        }
        
        entries.append(entry)
        valid_folders += 1
    
    # Write entries to JSONL file
    with open(output_file, 'w') as f:
        for entry in entries:
            f.write(json.dumps(entry) + '\n')
    
    print(f"\nSummary for separate mode:")
    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")

def main():
    parser = argparse.ArgumentParser(description="Create metadata JSONL for rotation dataset")
    parser.add_argument('--input-dir', type=str, required=True,
                      help="Directory containing rotation dataset images or folders")
    parser.add_argument('--output-file', type=str, default="rotation_metadata.jsonl",
                      help="Output JSONL file path")
    parser.add_argument('--angle-increment', type=int, default=30,
                      help="Angle increment used in the dataset (e.g., 30, 45, 90)")
    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)")
    
    args = parser.parse_args()
    
    print(f"Creating metadata JSONL for rotation dataset:")
    print(f"Input directory: {args.input_dir}")
    print(f"Output file: {args.output_file}")
    print(f"Angle increment: {args.angle_increment} degrees")
    print(f"Difficulty mode: {args.difficulty}")
    print(f"Generation mode: {args.generation_mode}")
    
    if args.generation_mode == "combined":
        create_metadata_jsonl_combined(
            input_dir=args.input_dir,
            output_file=args.output_file,
            angle_increment=args.angle_increment,
            difficulty=args.difficulty
        )
    else:  # separate mode
        create_metadata_jsonl_separate(
            input_dir=args.input_dir,
            output_file=args.output_file,
            angle_increment=args.angle_increment,
            difficulty=args.difficulty
        )

if __name__ == "__main__":
    main()