File size: 7,259 Bytes
0d4e49d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import anthropic
import base64
import httpx
import os
import time
from mimetypes import guess_type

import random
# import numpy as np
def seed_everything(seed):
    random.seed(seed)
    # np.random.seed(seed)
    os.environ['PYTHONHASHSEED'] = str(seed)
    # torch.manual_seed(seed)
    # torch.cuda.manual_seed(seed)
    # torch.backends.cudnn.deterministic = True
    # env.seed(seed)
seed_everything(1)

def local_image_to_data_url(image_path):
    mime_type, _ = guess_type(image_path)
    if mime_type is None:
        mime_type = 'application/octet-stream'
    with open(image_path, "rb") as image_file:
        base64_encoded_data = base64.b64encode(image_file.read()).decode('utf-8')
    return base64_encoded_data

client = anthropic.Anthropic(
    api_key="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",
)


# Start test
levels = [3,4,5,6,7,8]
in_context_example_num = 0 # 0, 1, 2, 4, 8

if in_context_example_num > 0:
    output_path = "output/output_img_%d/"%(in_context_example_num)
    input_backup_path = "input/input_backup_img_%d/"%(in_context_example_num)
else:
    output_path = "output/output_img/"
    input_backup_path = "input/input_backup_img/"

os.makedirs(output_path, exist_ok=True)
os.makedirs(input_backup_path, exist_ok=True)

EXAMPLE_DICT = {
    3: [],
    4: [],
    5: [],
    6: [],
    7: [],
    8: [],
}
# for level in levels:
#     for example_id in range(8):
#         curr_example_pack = {}
#         curr_example_pack["image_path"] = "../example/level%d/img/%d.png"%(level, example_id)
#         with open("../example/level%d/answer/%d.txt"%(level, example_id), "r") as f:
#             curr_example_pack["answer"] = f.read()
        
        # curr_example_pack["pure_text"] = "../example/level%d/pure_text/%d.txt"%(level, example_id)
        # curr_example_pack["table"] = "../example/level%d/table/%d.txt"%(level, example_id)

        # curr_example_pack["start_image_path"] = "../example/level%d/begin/%d.jpg"%(level, example_id)
        # curr_example_pack["end_image_path"] = "../example/level%d/end/%d.jpg"%(level, example_id)
        # example_path = "../example/level%d/"%(level)
        # curr_example_pack["question1"] = "\n\nPlease generate the moving plan. The beginning state is:"
        # curr_example_pack["question2"] = "\nThe end state is:"
        # with open(example_path + "sol_%d.txt"%(example_id), "r") as f:
        #     curr_example_pack["answer"] = f.read()
        # EXAMPLE_DICT[level].append(curr_example_pack)


import ipdb; ipdb.set_trace()
for level in levels:
    os.makedirs(output_path + "level%d"%(level), exist_ok=True)
    os.makedirs(input_backup_path + "level%d"%(level), exist_ok=True)
    start_idx = 0
    end_idx = 100
    runned_term = 0
    map_path = "../maps/level%d/img/"%(level)
    while True:
        try:
            curr_id = start_idx + runned_term
            if curr_id >= end_idx:
                break
            
            prompt_input_1 = '''            
In this task, you will analyze a maze to determine if there is a hole in a specific position.
The following figure illustrates the appearances of the player, holes, lands, and the goal within the maze. You will need to focus on the appearance of the hole.
'''
            prompt_input_2 = '''
Here is an example to illustrate how to analyze and answer the question:
'''
            prompt_input_3 = '''
Example question: Is there a hole in row 3, column 3?

In this example:
- We check the position in row 3, column 3.
- According to the image, it is a land square. It does not contain a hole.
- Therefore, you will output "<Output> No".

Your output should be: "<Output> No" or "<Output> Yes", depending on whether there is a hole at the specified position.
'''
            # prompt_examples = []
            # image_examples = []
            # if in_context_example_num > 0:
            #     prompt_examples.append("## Example:\n")
            #     example_indices = random.sample(range(8), in_context_example_num)
            #     for example_index in example_indices:
            #         this_example = EXAMPLE_DICT[level][example_index]
            #         image_examples.append(local_image_to_data_url(this_example["image_path"]))
            #         prompt_examples.append(this_example["answer"])
            prompt_input_4 = "\n\nNow you will analyze the following maze and answer the question: "
            with open("../maps/level%d/question/%d.txt"%(level, curr_id), "r") as f:
                prompt_input_5 = f.read()

            # construct 
            content_input_seq = []
            content_input_seq.append({ 
                            "type": "text", 
                            "text": prompt_input_1,
                        })
            content_input_seq.append({ 
                            "type": "image",
                            "source": {
                                "type": "base64",
                                "media_type": "image/png",
                                "data": local_image_to_data_url("../prompt-visual-images/system-figure-1.png"),
                            }
                        })
            content_input_seq.append({ 
                            "type": "text", 
                            "text": prompt_input_2,
                        })
            content_input_seq.append({ 
                            "type": "image",
                            "source": {
                                "type": "base64",
                                "media_type": "image/png",
                                "data": local_image_to_data_url("../prompt-visual-images/system-figure-2.png"),
                            }
                        })
            content_input_seq.append({ 
                            "type": "text", 
                            "text": prompt_input_3,
                        })
            content_input_seq.append({
                "type": "text",
                "text": prompt_input_4,
            })
            content_input_seq.append({ 
                "type": "image",
                "source": {
                    "type": "base64",
                    "media_type": "image/png",
                    "data": local_image_to_data_url(map_path + "%d.png"%(curr_id)),
                }
            })
            content_input_seq.append({
                "type": "text",
                "text": prompt_input_5,
            })
            response = client.messages.create(
                model="claude-3-sonnet-20240229",
                max_tokens=1024,
                system="You are a maze-solving agent playing a pixelated maze videogame.\nMazes are presented on grid maps, where each tile can be empty land, or contain a player, hole, or goal.",
                messages=[
                    { 
                        "role": "user", 
                        "content": content_input_seq
                    },
                ],
            )
            with open(output_path + "level%d/%d.txt"%(level, curr_id), "w") as f:
                f.write(response.content[0].text)
            time.sleep(2)
            runned_term += 1
        except:
            time.sleep(2)
            pass