File size: 6,701 Bytes
754ac61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import requests
import json
import base64
import os
import time
import pandas as pd
from tqdm import tqdm
from concurrent.futures import ThreadPoolExecutor

DEBUG = True

SK_LIST = [
    "sk-V8HaW6l4a6qkTRlR07423f3c8c67431c8a9d9c365c0b7d9b",
    "sk-MZQXlv5tEG5hDX3yoK6sKRB4P9JBuw8PWtbeix1JITHWzIxW",
    "sk-NgALyBkzs6LPt5kbvLS8WBILov33pL2rB6J5bLTI4FBk7O2p",
    "sk-MEuJz0u5CyFyVgEP9CvUPhybfkP9eQg8iak82OU9pN6GC0xH",
]

COCO_ROOT = '/root/autodl-tmp/data/location_bench1/coco_resize/'  # 根据需要修改路径

# 将图片转base64格式
def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode('utf-8')

def gemini_label(question, img,idx, sk, attempt=0):
    if attempt > 5:
        return None

    # 构建图片路径并编码为base64
    # image_path = os.path.join(COCO_ROOT, 'val{0:06}.jpg'.format(idx))  # 根据需要修改路径
    # image_path = f'/home/aiops/wangzh/data/RGBD-benchmark/out_doors/pic_all/{img}'
    image_path = img
    # image_path = '/home/aiops/wangzh/data/RGBD-benchmark/out_doors/pic_all/1_gpt4o.png'
    base64_image = encode_image(image_path)
    # import pdb;pdb.set_trace()
    url = "https://open.xiaojingai.com/v1/chat/completions"  # 替换为新API的URL
 #     "text": f'''You will see an image along with four corresponding descriptions (captions). Please carefully observe the image and select the description that best matches the content of the image. Choose one option from (A), (B), (C), or (D).
                    # Options: (A){question[0]}\n(B){question[1]}\n(C){question[2]}\n(D){question[3]}\nPlease provide your answer with only one of the options and nothing else.'''
    try:
        # 构建请求体
        # payload = json.dumps({
        #     "image": f"data:image/jpeg;base64,{base64_image}",
        #     "question": question
        # })
        payload = json.dumps({
        "model": "gemini-1.5-pro",
        # "model": "gpt-4o",
        "stream": False,
        "messages": [
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": f'''You will see an image along with four corresponding descriptions (captions). Please carefully observe the image and select the description that best matches the content of the image. Choose one option from (A), (B), (C), or (D).
                        Options: (A){question[0]}\n(B){question[1]}\n(C){question[2]}\n(D){question[3]}\nPlease provide your answer with only one of the options and nothing else.'''
  
                    },
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": f"data:image/jpeg;base64,{base64_image}"
                        }
                    }
                ]
            }
        ],
        "max_tokens": 1000
    })
        headers = {
            'Authorization': sk,
            'Content-Type': 'application/json'
        }

        # 发送POST请求
        response = requests.post(url, headers=headers, data=payload)
        print(response)
        print("Response Status Code:", response.status_code)  # 打印状态码
        print("Response Text:", response.text)  # 打印响应内容
        output = response.json()  # 获取回答
        print("output",output)
        return {"id": idx, "answer": output}

    except Exception as ex:
        print(idx, ex)
        time.sleep(2)  # 等待后重试
        return gemini_label(question, idx, sk, attempt + 1)  # 重试

def process_sample(i, img,questions, sk):
    uid = uids[i]
    question = questions[i]
    img = img[i]
    # import pdb;pdb.set_trace()
    ans = gemini_label(question, img,uid, sk=sk)
    return ans if ans is not None else 'None'

if __name__ == '__main__':
    save_path = './'
    os.makedirs(os.path.join(save_path), exist_ok=True)

    # meta_path = '/home/aiops/wangzh/data/RGBD-benchmark/out_doors/all.json'
    meta_path = '/home/aiops/wangzh/data/scanner/indoor-new/all.json'
    # meta = pd.read_csv(meta_path)
    with open(meta_path, 'r', encoding='utf-8') as json_file:
        meta = json.load(json_file)
    import pdb;pdb.set_trace()
    lens=len(meta)
    uids = [meta[i]['id'] for i in range(lens)]
    questions =[meta[i]['captions'] for i in range(lens)]
    img = [meta[i]['image'] for i in range(lens)]
    # print('get samples:', len(uids))
    # print(uids[:5])
    # img = [f'/home/aiops/wangzh/data/scanner/scannet_2d_HR3/{meta[i]['scene_id']}/color/{meta[i]['image']}' for i in range(lens)]
    img = [f'/home/aiops/wangzh/data/scanner/scannet_2d_HR3/{meta[i]["scene_id"]}/color/{meta[i]["image"]}' for i in range(lens)]

    answer_list = []

    with ThreadPoolExecutor(max_workers=4) as executor:
        answer_list = list(tqdm(executor.map(lambda i: process_sample(i, img,questions, SK_LIST[i % 4]), range(len(uids))), total=len(uids)))

    print('gemini label sample:', len(answer_list))
    answer_list = pd.DataFrame(answer_list)
    answer_list.to_csv(os.path.join(save_path, 'answers.csv'), index=False)



# import requests
# import json
# import base64
# import os

# def encode_image(image_path):
#     with open(image_path, "rb") as image_file:
#         return base64.b64encode(image_file.read()).decode('utf-8')

# def ask_question(image_path, caption, sk):
#     base64_image = encode_image(image_path)
#     url = "https://open.xiaojingai.com/v1/chat/completions"
    
#     payload = json.dumps({
#         "model": "gemini-1.5-pro",
#         "stream": False,
#         "messages": [
#             {
#                 "role": "user",
#                 "content": [
#                    {
#                         "type": "text",
#                         "text":"describe what is love"
#                     },
#                     {
#                         "type": "image_url",
#                         "image_url": {
#                             "url": f"data:image/jpeg;base64,{base64_image}"
#                         }
#                     }
#                 ]
#             }
#         ],
#         "max_tokens": 1000
#     })
    
#     headers = {
#         'Authorization': sk,
#         'Content-Type': 'application/json'
#     }
    
#     response = requests.post(url, headers=headers, data=payload)
#     return response.json()

# # Example usage
# image_path = '/home/aiops/wangzh/data/RGBD-benchmark/out_doors/pic_all/1_gpt4o.png'
# caption = "Describe the content of the image."
# sk = "sk-V8HaW6l4a6qkTRlR07423f3c8c67431c8a9d9c365c0b7d9b"
# response = ask_question(image_path, caption, sk)
# print(response)