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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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
import json
from copy import deepcopy
import os
from pathlib import Path
import re
from multiprocessing import Pool
from PIL import Image
from tqdm import tqdm
import multiprocessing

def resize_image(image, scale=0.75):
    """
    Resize image to have its shorter edge equal to 720 pixels while maintaining aspect ratio.
    
    Args:
    image: PIL Image object
    
    Returns:
    Resized PIL Image
    """
    # Get current dimensions
    width, height = image.size
    
    # Calculate new dimensions
    new_width = int(width * scale)
    new_height = int(height * scale)
    
    # Resize image
    resized_image = image.resize((new_width, new_height), Image.LANCZOS)
    return resized_image

def merge_convs(conversations):
    """
    Merge all successive 'human' conversations comprehensively.
    
    Args:
        conversations (list): List of conversation dictionaries
    
    Returns:
        list: Processed conversations with all successive human messages merged
    
    Raises:
        ValueError: If input is not a list or contains invalid conversation dictionaries
    """
    # Validate input
    if not isinstance(conversations, list):
        raise ValueError("Input must be a list of conversation dictionaries")
    
    # Validate each conversation dictionary structure
    for conv in conversations:
        if not isinstance(conv, dict):
            raise ValueError("Each conversation must be a dictionary")
        if 'from' not in conv or 'value' not in conv:
            raise ValueError("Each conversation must have 'from' and 'value' keys")
    
    processed_conversations = []
    i = 0
    while i < len(conversations):
        current_conv = conversations[i]
        
        # If current conversation is 'human', start merging
        if current_conv['from'] == 'human':
            # Collect all successive human conversations
            merged_value = current_conv['value']
            j = i + 1
            while j < len(conversations) and conversations[j]['from'] == 'human':
                merged_value += '\n\n' + conversations[j]['value']
                j += 1
            
            # Update current conversation with merged value
            current_conv['value'] = merged_value
            
            # Move index to last non-human conversation
            i = j
        else:
            # For non-human conversations, just add to processed list
            i += 1
        
        processed_conversations.append(current_conv)
    
    return processed_conversations

def parse_reasoning(input_string):
    input_string = input_string.strip()
    if not input_string.endswith("```"):
        input_string += "```"
    # Regex pattern to match texts between ```A```, ```B```, and ```C```
    pattern = r'```([ABC])\n(.*?)```'
    
    # Find all matches
    matches = re.findall(pattern, input_string, re.DOTALL)
    
    # Create a dictionary to store parsed texts
    parsed_texts = []
    
    # Populate the dictionary
    for _, text in matches:
        parsed_texts.append(text.strip())

    if len(parsed_texts) != 3:
        # print(input_string)
        return None, None, None

    caption, instruction, reasoning = parsed_texts
    
    return caption, instruction.replace("Task: ", ""), reasoning

def encode_action(action_json):
    """
    Encode different types of actions into human-readable descriptions.
    
    Args:
        action_json (dict): A dictionary containing action details
    
    Returns:
        str: A human-readable description of the action
    """
    action_type = action_json.get("action", "")
    
    if action_type == "SWIPE":
        # Check scroll direction by comparing y-values
        if len(action_json.get("info", [])) >= 2:
            start_y = action_json["touch_coord"][1]
            end_y = action_json["lift_coord"][1]
            
            # Determine scroll direction
            if start_y > end_y:
                return "SCROLL UP"
            elif start_y < end_y:
                return "SCROLL DOWN"
    
    elif action_type == "TYPE":
        text_to_type = action_json.get("type_text", "")
        return f'TYPE "{text_to_type}"'
    
    elif action_type == "CLICK":
        # Check for home key action
        if action_json.get("info") == "KEY_HOME":
            return "go to the home screen"
        elif action_json.get("info") == "KEY_BACK":
            return "go to the previous screen"
        elif action_json.get("info") == "KEY_RECENT":
            return "go to the previous App"
    
    # Default case for unrecognized actions
    return f"Perform {action_type} action"

grounding_step_prompt = "<|img|>Step {step_idx}. Given a GUI image, what are the relative (0-1000) pixel point coordinates for the element corresponding to the following instruction or description: {instruction}"
grounding_step_ans = "```\n{point_str}\n```"
act_step_prompt = "<|img|>Step {step_idx}. Instruction: {prev_instruction}"
act_step_ans = "The agent's action: {prev_action}"
user_start_prompt = "The agent is performing the ultimate task: {ultimate_task}."
user_history_instr_prompt = "History of the agent's steps:\n{history_list}."

resize_ratios_per_window_size = {
    1: 0.25,
    2: 0.25,
    3: 0.25,
}

def process_android_episodes(data, window_size=2, img_dir="./AMEX/screenshot"):
    """
    Process Android episodes and extract steps with click or long_press actions.
    
    Args:
    data (list): List of episode dictionaries
    window_size (int, optional): Number of recent image-included conversations to include. 
                                 Defaults to 3 (current image + 2 previous image-included steps).
    
    Returns:
    dict: Dictionary with episode_id as key and list of filtered steps as value
    """
    instructions = []
    for episode in data:
        episode_id = episode["episode_id"]
        
        for i, step in enumerate(episode["steps"]):
            is_grounding = step["is_grounding"]
            
            if not is_grounding:
                continue

            if window_size > 0 and i == 0: # skip the first step if window_size > 0
                continue

            convs = [
                {
                    "from": "human",
                    "value": user_start_prompt.format(
                        ultimate_task=episode["instruction"]
                    ),
                },
            ]

            cur_img_list = [Path(img_dir) / Path(step["image_path"]).name]

            if window_size > 0:
                window_steps = episode["steps"][i-window_size:i] if i >= window_size else episode["steps"][:i]

                if i > window_size: # has more history steps larger than window_size
                    convs.append(
                        {
                            "from": "human",
                            "value": user_history_instr_prompt.format(
                                history_list="\n".join(
                                    [
                                        f"\t{j+1}. " + prev_step["step_instruction"]
                                        for j, prev_step in enumerate(episode["steps"][:i-window_size])
                                    ]
                                )
                            ),
                        },
                    )

                convs.append(
                    {
                        "from": "human",
                        "value": "The recent steps with the GUI images are as follows:\n",
                    }
                )
                
                for j, win_step_i in enumerate(window_steps):
                    if win_step_i["is_grounding"]:
                        convs.append(
                            {
                                "from": "human",
                                "value": grounding_step_prompt.format(
                                    instruction=win_step_i["step_instruction"], step_idx=i+1-(len(window_steps)-j)
                                ),
                            }
                        )
                        convs.append(
                            {
                                "from": "gpt",
                                "value": grounding_step_ans.format(point_str=f"({win_step_i['coord_norm'][0]}, {win_step_i['coord_norm'][1]})"),
                            }
                        )
                    else:
                        convs.append(
                            {
                                "from": "human",
                                "value": act_step_prompt.format(
                                    prev_instruction=encode_action(win_step_i), step_idx=i+1-(len(window_steps)-j)
                                ),
                            }
                        )
                        convs.append(
                            {
                                "from": "human",
                                "value": act_step_ans.format(
                                    prev_action=encode_action(win_step_i)
                                ),
                            }
                        )
                
                win_img_list = [
                    (Path(img_dir) / Path(win_step["image_path"]).name) for win_step in window_steps
                ]

                if not all([img_path.exists() for img_path in win_img_list+cur_img_list]):
                    print(f"Image not found for episode {episode_id}, step {i+1}. Skipping...")
                    continue

                has_img_broken = False
                for img_path in win_img_list+cur_img_list:
                    try:
                        Image.open(str(img_path))
                    except Exception as e:
                        print(f"Error opening image {img_path}: {e}")
                        has_img_broken = True
                        break
                if has_img_broken:
                    print(f"Image broken for episode {episode_id}, step {i+1}. Skipping...")
                    continue

                resize_scale = resize_ratios_per_window_size[window_size]
                win_img_list_resized = []
                for img_path in win_img_list:
                    new_save_name = img_path.stem + f"_{resize_scale}x" + img_path.suffix
                    new_save_dir = img_path.parent.parent / f"images_resized"
                    new_save_dir.mkdir(parents=True, exist_ok=True)
                    new_save_path = new_save_dir / new_save_name
                    if new_save_path.exists():
                        try:
                            Image.open(str(new_save_path))
                        except Exception as e:
                            print(f"Error opening image {new_save_path}: {e}")
                            os.remove(new_save_path)
                        else:
                            win_img_list_resized.append(new_save_path)
                            continue
                    win_img = Image.open(str(img_path))
                    win_img = resize_image(win_img, scale=resize_scale)
                    win_img.save(str(new_save_path))
                    win_img_list_resized.append(new_save_path)
            else:
                convs.append(
                        {
                            "from": "human",
                            "value": user_history_instr_prompt.format(
                                history_list="\n".join(
                                    [
                                        f"\t{j+1}. " + prev_step["step_instruction"]
                                        for j, prev_step in enumerate(episode["steps"][:i-window_size])
                                    ]
                                )
                            ),
                        },
                    )

            cur_img_list_resized = []
            for img_path in cur_img_list:
                new_save_name = img_path.stem + f"_{0.5}x" + img_path.suffix
                new_save_dir = img_path.parent.parent / f"images_resized"
                new_save_dir.mkdir(parents=True, exist_ok=True)
                new_save_path = new_save_dir / new_save_name
                if new_save_path.exists():
                    try:
                        Image.open(str(new_save_path))
                    except Exception as e:
                        print(f"Error opening image {new_save_path}: {e}")
                        os.remove(new_save_path)
                    else:
                        cur_img_list_resized.append(new_save_path)
                        continue
                cur_img = Image.open(str(img_path))
                cur_img = resize_image(cur_img, scale=0.5)
                cur_img.save(str(new_save_path))
                cur_img_list_resized.append(new_save_path)
            
            if window_size > 0:
                img_list = win_img_list_resized + cur_img_list_resized
            else:
                img_list = cur_img_list_resized

            convs.append(
                {
                    "from": "human",
                    "value": grounding_step_prompt.format(instruction=step["step_instruction"], step_idx=i+1),
                }
            )
            convs.append(
                {
                    "from": "gpt",
                    "value": grounding_step_ans.format(point_str=f"({step['coord_norm'][0]}, {step['coord_norm'][1]})"),
                }
            )

            convs = merge_convs(convs)

            instructions.append(
                {
                    "image": [str(img_path) for img_path in img_list],
                    "conversations": convs,
                }
            )
    
    return instructions

# Example usage
if __name__ == "__main__":
    # Sample data loading (replace with your actual file path)
    data = []

    episode_files = list(Path("./episodes_grounding_inner_reasoning_v3").glob("*.json"))
    for episode_file in episode_files:
        with open(episode_file, "r", encoding="utf-8") as file:
            episode_data = json.load(file)
            for i, step_i in enumerate(episode_data["steps"]):
                if not step_i.get("grounding_reasoning"):
                    step_i["step_instruction"] = encode_action(step_i)
                    step_i["is_grounding"] = False
                    continue
                _, step_instruction, _ = parse_reasoning(step_i["grounding_reasoning"])
                step_i["step_instruction"] = step_instruction
                step_i["is_grounding"] = bool(step_instruction) and step_i["action"] == "TAP"
            data.append(episode_data)
    
    def preprocess_coord_norm(episode):
        for step in episode["steps"]:
            image_path = Path("./AMEX/screenshot") / step["image_path"]
            if not image_path.exists():
                print(f"Image not found: {image_path}")
            if step["action"] == "TAP":
                image = Image.open(image_path)
                image_width, image_height = image.size
                step["coord_norm"] = [int(step["touch_coord"][0]/image_width*1000), int(step["touch_coord"][1]/image_height*1000)]
        return episode

    with Pool() as pool:
        data = pool.map(preprocess_coord_norm, data)

    # Process the episodes with default window_size=3
    # window_size_list = [1, 2, 3]
    window_size_list = [0,1,2,3]

    def process_episode(args):
        episode, window_size = args
        return process_android_episodes([episode], window_size)

    instructions = []
    for window_size in window_size_list:
        tasks = [(episode, window_size) for episode in data]
        with multiprocessing.Pool(processes=multiprocessing.cpu_count()) as pool:
            results = list(tqdm(pool.imap(process_episode, tasks), total=len(tasks), desc=f"Window Size {window_size}"))
        for result in results:
            instructions.extend(result)

    print(f"Number of context aware train instructions: {len(instructions)}")
    
    with open(f"amex_train_window_{'-'.join([str(e) for e in window_size_list])}_{len(instructions)//1000}k.json", "w", encoding="utf-8") as file:
        json.dump(instructions, file, ensure_ascii=False, indent=4)