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|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import openai
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
import base64
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
import time
|
| 7 |
+
import json
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from threading import Lock
|
| 10 |
+
from typing import Any
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
_json_write_lock = Lock()
|
| 14 |
+
|
| 15 |
+
def save_json_file(
|
| 16 |
+
data: Any,
|
| 17 |
+
file_path: str,
|
| 18 |
+
indent: int = 4,
|
| 19 |
+
temp_suffix: str = ".tmp"
|
| 20 |
+
) -> None:
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
path = Path(file_path)
|
| 25 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 26 |
+
|
| 27 |
+
temp_path = f"{file_path}{temp_suffix}"
|
| 28 |
+
|
| 29 |
+
with _json_write_lock:
|
| 30 |
+
try:
|
| 31 |
+
|
| 32 |
+
with open(temp_path, "w", encoding="utf-8") as f:
|
| 33 |
+
json.dump(data, f, ensure_ascii=False, indent=indent)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
f.flush()
|
| 37 |
+
os.fsync(f.fileno())
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
os.replace(temp_path, file_path)
|
| 41 |
+
|
| 42 |
+
except Exception as e:
|
| 43 |
+
# 出错则删除临时文件
|
| 44 |
+
try:
|
| 45 |
+
if os.path.exists(temp_path):
|
| 46 |
+
os.remove(temp_path)
|
| 47 |
+
except OSError:
|
| 48 |
+
pass
|
| 49 |
+
raise RuntimeError(f"save json failed: {e}") from e
|
| 50 |
+
|
| 51 |
+
def read_json_file(file_path):
|
| 52 |
+
"""
|
| 53 |
+
Reads a JSON file and returns the parsed data as a Python object.
|
| 54 |
+
|
| 55 |
+
:param file_path: The path to the JSON file
|
| 56 |
+
:return: The data parsed from the JSON file
|
| 57 |
+
"""
|
| 58 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 59 |
+
data = json.load(f)
|
| 60 |
+
return data
|
| 61 |
+
|
| 62 |
+
def encode_image(image_path):
|
| 63 |
+
with open(image_path, "rb") as image_file:
|
| 64 |
+
return base64.standard_b64encode(image_file.read()).decode("utf-8")
|
| 65 |
+
|
| 66 |
+
def merge_json_lists(folder_path):
|
| 67 |
+
"""
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
json_list = [
|
| 71 |
+
os.path.join(folder_path, f)
|
| 72 |
+
for f in os.listdir(folder_path)
|
| 73 |
+
if f.lower().endswith('.json') and os.path.isfile(os.path.join(folder_path, f))
|
| 74 |
+
]
|
| 75 |
+
|
| 76 |
+
merged_list = []
|
| 77 |
+
|
| 78 |
+
for file_path in json_list:
|
| 79 |
+
try:
|
| 80 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 81 |
+
data = json.load(f)
|
| 82 |
+
if isinstance(data, list):
|
| 83 |
+
merged_list.extend(data)
|
| 84 |
+
else:
|
| 85 |
+
print(f"waring: {file_path} is not list. skipped")
|
| 86 |
+
except Exception as e:
|
| 87 |
+
print(f"processing {file_path} error: {str(e)}")
|
| 88 |
+
|
| 89 |
+
return merged_list
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def openai_api(image_path, prompt = None):
|
| 93 |
+
if prompt == None:
|
| 94 |
+
prompt = "What's in this image?"
|
| 95 |
+
|
| 96 |
+
base64_image = encode_image(image_path)
|
| 97 |
+
client = OpenAI(
|
| 98 |
+
base_url='your_url',
|
| 99 |
+
api_key='your_key'
|
| 100 |
+
)
|
| 101 |
+
response = client.chat.completions.create(
|
| 102 |
+
model="claude-3-7-sonnet-20250219",
|
| 103 |
+
messages=[
|
| 104 |
+
{
|
| 105 |
+
"role": "user",
|
| 106 |
+
"content": [
|
| 107 |
+
{"type": "text", "text": prompt},
|
| 108 |
+
{
|
| 109 |
+
"type": "image_url",
|
| 110 |
+
"image_url": {
|
| 111 |
+
"url": f"data:image/jpeg;base64,{base64_image}"
|
| 112 |
+
}
|
| 113 |
+
},
|
| 114 |
+
],
|
| 115 |
+
}
|
| 116 |
+
],
|
| 117 |
+
max_tokens=5000,
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
return response
|
| 121 |
+
|
| 122 |
+
if __name__ == "__main__":
|
| 123 |
+
folder_path = r"your_path/poster/data"
|
| 124 |
+
save_dir = r"your_path/poster/result"
|
| 125 |
+
|
| 126 |
+
saved_josn = os.path.join(save_dir,"result.json")
|
| 127 |
+
if not os.path.exists(saved_josn):
|
| 128 |
+
tasks = merge_json_lists(folder_path)
|
| 129 |
+
save_json_file(tasks, saved_josn)
|
| 130 |
+
|
| 131 |
+
tasks = read_json_file(saved_josn)
|
| 132 |
+
max_retries = 4
|
| 133 |
+
retry_wait = 10
|
| 134 |
+
for item in tqdm(tasks):
|
| 135 |
+
if "response" in item: continue
|
| 136 |
+
|
| 137 |
+
prompt = item["prompt"]
|
| 138 |
+
image_path = os.path.join(folder_path, item["path"])
|
| 139 |
+
for attempt in range(max_retries):
|
| 140 |
+
try:
|
| 141 |
+
response = openai_api(image_path, prompt)
|
| 142 |
+
item["response"] = response.choices[0].message.content
|
| 143 |
+
print(item["response"])
|
| 144 |
+
save_json_file(tasks, saved_josn)
|
| 145 |
+
break
|
| 146 |
+
except Exception as e:
|
| 147 |
+
print(f"[Warning] Request failed: {e}")
|
| 148 |
+
if attempt < max_retries - 1:
|
| 149 |
+
print(f"Retrying in {retry_wait} seconds... (attempt {attempt + 1})")
|
| 150 |
+
time.sleep(retry_wait)
|
| 151 |
+
else:
|
| 152 |
+
print("[Error] Reached max retries. Skipping this item.")
|
| 153 |
+
item["error"] = str(e)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
|
run/qwen_32b.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from threading import Lock
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
_json_write_lock = Lock()
|
| 14 |
+
|
| 15 |
+
def save_json_file(
|
| 16 |
+
data: Any,
|
| 17 |
+
file_path: str,
|
| 18 |
+
indent: int = 4,
|
| 19 |
+
temp_suffix: str = ".tmp"
|
| 20 |
+
) -> None:
|
| 21 |
+
"""
|
| 22 |
+
"""
|
| 23 |
+
path = Path(file_path)
|
| 24 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 25 |
+
|
| 26 |
+
temp_path = f"{file_path}{temp_suffix}"
|
| 27 |
+
|
| 28 |
+
with _json_write_lock:
|
| 29 |
+
try:
|
| 30 |
+
|
| 31 |
+
with open(temp_path, "w", encoding="utf-8") as f:
|
| 32 |
+
json.dump(data, f, ensure_ascii=False, indent=indent)
|
| 33 |
+
|
| 34 |
+
f.flush()
|
| 35 |
+
os.fsync(f.fileno())
|
| 36 |
+
|
| 37 |
+
os.replace(temp_path, file_path)
|
| 38 |
+
|
| 39 |
+
except Exception as e:
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
if os.path.exists(temp_path):
|
| 43 |
+
os.remove(temp_path)
|
| 44 |
+
except OSError:
|
| 45 |
+
pass
|
| 46 |
+
raise RuntimeError(f"save json failed: {e}") from e
|
| 47 |
+
|
| 48 |
+
def read_json_file(file_path):
|
| 49 |
+
"""
|
| 50 |
+
Reads a JSON file and returns the parsed data as a Python object.
|
| 51 |
+
|
| 52 |
+
:param file_path: The path to the JSON file
|
| 53 |
+
:return: The data parsed from the JSON file
|
| 54 |
+
"""
|
| 55 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 56 |
+
data = json.load(f)
|
| 57 |
+
return data
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def merge_json_lists(folder_path):
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
json_list = [
|
| 64 |
+
os.path.join(folder_path, f)
|
| 65 |
+
for f in os.listdir(folder_path)
|
| 66 |
+
if f.lower().endswith('.json') and os.path.isfile(os.path.join(folder_path, f))
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
merged_list = []
|
| 70 |
+
|
| 71 |
+
for file_path in json_list:
|
| 72 |
+
try:
|
| 73 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 74 |
+
data = json.load(f)
|
| 75 |
+
if isinstance(data, list):
|
| 76 |
+
merged_list.extend(data)
|
| 77 |
+
else:
|
| 78 |
+
print(f"警告: {file_path} 的内容不是列表,已跳过")
|
| 79 |
+
except Exception as e:
|
| 80 |
+
print(f"处理文件 {file_path} 时出错: {str(e)}")
|
| 81 |
+
|
| 82 |
+
return merged_list
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def build():
|
| 86 |
+
#cache_dir="/workspace/huggingface"
|
| 87 |
+
# default: Load the model on the available device(s)
|
| 88 |
+
model = Qwen2_5_VLForConditionalGeneration.from_pretrained( "Qwen/Qwen2.5-VL-32B-Instruct", torch_dtype="auto", device_map="auto")
|
| 89 |
+
|
| 90 |
+
# default processer
|
| 91 |
+
processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-32B-Instruct")
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
return model,processor
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def conversation(model, processor, image_path, prompt):
|
| 98 |
+
messages = [
|
| 99 |
+
{
|
| 100 |
+
"role": "user",
|
| 101 |
+
"content": [
|
| 102 |
+
{
|
| 103 |
+
"type": "image",
|
| 104 |
+
"image": image_path,
|
| 105 |
+
},
|
| 106 |
+
{"type": "text", "text": prompt},
|
| 107 |
+
],
|
| 108 |
+
}
|
| 109 |
+
]
|
| 110 |
+
|
| 111 |
+
# Preparation for inference
|
| 112 |
+
text = processor.apply_chat_template(
|
| 113 |
+
messages, tokenize=False, add_generation_prompt=True
|
| 114 |
+
)
|
| 115 |
+
image_inputs, video_inputs = process_vision_info(messages)
|
| 116 |
+
inputs = processor(
|
| 117 |
+
text=[text],
|
| 118 |
+
images=image_inputs,
|
| 119 |
+
videos=video_inputs,
|
| 120 |
+
padding=True,
|
| 121 |
+
return_tensors="pt",
|
| 122 |
+
)
|
| 123 |
+
inputs = inputs.to("cuda")
|
| 124 |
+
|
| 125 |
+
# Inference: Generation of the output
|
| 126 |
+
generated_ids = model.generate(**inputs, max_new_tokens=128)
|
| 127 |
+
generated_ids_trimmed = [
|
| 128 |
+
out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
| 129 |
+
]
|
| 130 |
+
output_text = processor.batch_decode(
|
| 131 |
+
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
| 132 |
+
)
|
| 133 |
+
print(output_text)
|
| 134 |
+
return output_text
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
if __name__ == "__main__":
|
| 138 |
+
folder_path = r"your_path/poster/data"
|
| 139 |
+
save_dir = r"your_path/poster/result"
|
| 140 |
+
|
| 141 |
+
saved_josn = os.path.join(save_dir,"qwen_32b_bench.json")
|
| 142 |
+
if not os.path.exists(saved_josn):
|
| 143 |
+
tasks = merge_json_lists(folder_path)
|
| 144 |
+
save_json_file(tasks, saved_josn)
|
| 145 |
+
|
| 146 |
+
tasks = read_json_file(saved_josn)
|
| 147 |
+
model,processor = build()
|
| 148 |
+
print("build model successful")
|
| 149 |
+
for item in tqdm(tasks):
|
| 150 |
+
if "response" in item: continue
|
| 151 |
+
|
| 152 |
+
prompt = item["prompt"]
|
| 153 |
+
image_path = os.path.join(folder_path, item["path"])
|
| 154 |
+
try:
|
| 155 |
+
item["response"] = conversation(model, processor, image_path, prompt)
|
| 156 |
+
print(item["response"])
|
| 157 |
+
save_json_file(tasks, saved_josn)
|
| 158 |
+
break
|
| 159 |
+
except Exception as e:
|
| 160 |
+
print(f"[Warning] failed: {e}")
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
|