BruceFeng98 commited on
Commit
a8d6356
·
verified ·
1 Parent(s): a661d53

Upload gpt_judge.py

Browse files
Files changed (1) hide show
  1. metric/gpt_judge.py +163 -0
metric/gpt_judge.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import openai
3
+ from openai import OpenAI
4
+ import base64
5
+ from tqdm import tqdm
6
+ import json
7
+ import os
8
+ from typing import Any
9
+ from threading import Lock
10
+ from pathlib import Path
11
+ import time
12
+
13
+ import json
14
+ import os
15
+ from pathlib import Path
16
+ from threading import Lock
17
+ from typing import Any
18
+ import re
19
+
20
+ _json_write_lock = Lock()
21
+
22
+ def save_json_file(
23
+ data: Any,
24
+ file_path: str,
25
+ indent: int = 4,
26
+ temp_suffix: str = ".tmp"
27
+ ) -> None:
28
+
29
+ path = Path(file_path)
30
+ path.parent.mkdir(parents=True, exist_ok=True)
31
+
32
+ temp_path = f"{file_path}{temp_suffix}"
33
+
34
+ with _json_write_lock:
35
+ try:
36
+
37
+ with open(temp_path, "w", encoding="utf-8") as f:
38
+ json.dump(data, f, ensure_ascii=False, indent=indent)
39
+
40
+ f.flush()
41
+ os.fsync(f.fileno())
42
+
43
+ os.replace(temp_path, file_path)
44
+
45
+ except Exception as e:
46
+ try:
47
+ if os.path.exists(temp_path):
48
+ os.remove(temp_path)
49
+ except OSError:
50
+ pass
51
+ raise RuntimeError(f"save json failed: {e}") from e
52
+
53
+ def read_json_file(file_path):
54
+ """
55
+ Reads a JSON file and returns the parsed data as a Python object.
56
+
57
+ :param file_path: The path to the JSON file
58
+ :return: The data parsed from the JSON file
59
+ """
60
+ with open(file_path, 'r', encoding='utf-8') as f:
61
+ data = json.load(f)
62
+ return data
63
+
64
+ def openai_api( prompt = None):
65
+ if prompt == None:
66
+ prompt = "What's in this image?"
67
+
68
+ client = OpenAI(
69
+ base_url='your_url',
70
+
71
+ api_key='your_key'
72
+ )
73
+ response = client.chat.completions.create(
74
+ model="gpt-4o",
75
+ messages=[
76
+ {
77
+ "role": "user",
78
+ "content": [
79
+ {"type": "text", "text": prompt}
80
+ ],
81
+ }
82
+ ],
83
+ max_tokens=5000,
84
+ )
85
+
86
+ return response
87
+
88
+
89
+ def extract_last_bracket_list(s: str) -> list:
90
+ """
91
+ """
92
+ last_open = s.rfind('[')
93
+ last_close = s.rfind(']')
94
+ content = s[last_open:last_close+1]
95
+
96
+ try:
97
+
98
+ result = json.loads(content)
99
+ except:
100
+ content = re.sub(r'[\n\t\r]', '', content)
101
+ content = ' '.join(content.split())
102
+ result = []
103
+ content = content.split("\",")
104
+ for item in content:
105
+ for item2 in item.split("\',"):
106
+ result.append(item2)
107
+ return result
108
+
109
+
110
+ def ads_task_llm_judge(jsonlist):
111
+ for json_file in jsonlist:
112
+ print(json_file)
113
+ max_retries = 4
114
+ retry_wait = 10
115
+ tasks = read_json_file(json_file)
116
+ for item in tqdm(tasks):
117
+ if "judge" in item: continue
118
+
119
+ prompt_templet = 'Please help me determine if the content in the Description contains Key Information. If it does, answer directly with "Yes"; if it does not, answer directly with "No". Please respond only with "Yes" or "No", without any additional output.'
120
+
121
+ judge_list = []
122
+ for keypoint in item["gt"]:
123
+ response = item["response"]
124
+ if isinstance(response, list):
125
+ content = ""
126
+ for text in response:
127
+ content += text
128
+ if isinstance(response, str):
129
+ content = response
130
+ prompt = prompt_templet +"\n"+ "Description: " + content +"\n"+ "Key Information: " + keypoint
131
+
132
+ for attempt in range(max_retries):
133
+ try:
134
+ response = openai_api(prompt)
135
+ current_judge = response.choices[0].message.content
136
+ judge_list.append(current_judge)
137
+ break
138
+ except Exception as e:
139
+ print(f"[Warning] Request failed: {e}")
140
+ if attempt < max_retries - 1:
141
+ print(f"Retrying in {retry_wait} seconds... (attempt {attempt + 1})")
142
+ time.sleep(retry_wait)
143
+ else:
144
+ print("[Error] Reached max retries. Skipping this item.")
145
+ item["error"] = str(e)
146
+ item["judge"] = judge_list
147
+ print(item["judge"])
148
+ for attempt in range(max_retries):
149
+ try:
150
+ save_json_file(tasks, json_file)
151
+ break
152
+ except Exception as e:
153
+ if attempt < max_retries - 1:
154
+ print(f"save error)")
155
+ time.sleep(2)
156
+ else:
157
+ print("[Error] Reached SAVE max retries. Skipping this item.")
158
+
159
+ if __name__ == "__main__":
160
+ jsonlist = [
161
+ r"your_path/gpt4o_bench.json",
162
+ ]
163
+ ads_task_llm_judge(jsonlist)