ZoneMaestro_code / eval /respace /tools /layout_objects_grouping.py
kkkkiiii's picture
Add files using upload-large-folder tool
7cb2bdf verified
Raw
History Blame Contribute Delete
8 kB
import json
import os
from openai import AzureOpenAI
from azure.identity import ChainedTokenCredential, AzureCliCredential, ManagedIdentityCredential, get_bearer_token_provider
import base64
import uuid
import re
from prompts import grouping_prompt_template, grouping_prompt_template_v2
from render_view import render_scene_example
def encode_image_to_base64(image_path):
"""将图片文件编码为base64字符串"""
if not os.path.exists(image_path):
print(f"Warning: Image file not found at {image_path}")
return None
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
def extract_json_from_response(content):
"""
从消息内容中提取JSON,支持代码块格式和纯JSON格式
"""
try:
# 方法1: 提取 ```json 代码块中的内容
json_pattern = r'```json\s*\n?(.*?)\n?```'
match = re.search(json_pattern, content, re.DOTALL)
if match:
json_str = match.group(1).strip()
else:
# 方法2: 如果没有代码块,查找第一个完整的JSON对象
json_pattern_fallback = r'\{.*\}'
match = re.search(json_pattern_fallback, content, re.DOTALL)
if match:
json_str = match.group(0).strip()
else:
raise ValueError("No valid JSON found in the message")
# 尝试直接解析
try:
return json.loads(json_str)
except json.JSONDecodeError:
# 如果失败,尝试修复单引号问题
# 将单引号替换为双引号(但要小心处理字符串内部的引号)
fixed_json_str = json_str.replace("'", '"')
try:
return json.loads(fixed_json_str)
except json.JSONDecodeError:
# 如果还是失败,使用eval(仅作为最后手段,存在安全风险)
# 但在这个受控环境中可以接受
try:
import ast
# 使用ast.literal_eval更安全
return ast.literal_eval(json_str)
except (ValueError, SyntaxError):
raise ValueError(f"Unable to parse JSON: {json_str}")
except Exception as e:
if "JSON parsing error" in str(e):
raise e
else:
raise ValueError(f"JSON parsing error: {e}")
#Authenticate by trying az login first, then a managed identity, if one exists on the system)
scope = "api://trapi/.default"
credential = get_bearer_token_provider(ChainedTokenCredential(
AzureCliCredential(),
ManagedIdentityCredential(),
), scope)
api_version = '2024-12-01-preview'
deployment_name = 'gpt-4o_2024-11-20'
instance = 'msra/shared'
endpoint = f'https://trapi.research.microsoft.com/{instance}'
#Create an AzureOpenAI Client
client = AzureOpenAI(
azure_endpoint=endpoint,
azure_ad_token_provider=credential,
api_version=api_version,
)
layout_path = "/home/v-meiszhang/amlt-project/respace/dataset-ssr3dfront/scenes"
render_img_path = "/home/v-meiszhang/amlt-project/respace/eval/viz/misc"
output_path = "/home/v-meiszhang/amlt-project/respace/grouped_layouts"
def process_layout_files():
"""
Processes layout files in the specified directory, generating grouping prompts and JSON outputs.
"""
os.makedirs(output_path, exist_ok=True)
for root, dirs, files in os.walk(layout_path):
for file in files:
if file.endswith('.json'):
try:
output_file_path = os.path.join(output_path, file)
if os.path.exists(output_file_path):
continue
layout_file_path = os.path.join(root, file)
print(f"Processing: {layout_file_path}")
with open(layout_file_path, 'r') as f:
layout_json = json.load(f)
# 转字符串
layout_json_str = json.dumps(layout_json, indent=4)
# 获取图片路径并编码
json_filename_without_ext = os.path.splitext(file)[0]
diag_view_image = os.path.join(render_img_path, json_filename_without_ext, "diag", 'frame.jpg')
top_view_image = os.path.join(render_img_path, json_filename_without_ext, "top", 'frame.jpg')
diag_base64 = encode_image_to_base64(diag_view_image)
top_base64 = encode_image_to_base64(top_view_image)
# 如果图片不存在,渲染场景
if not diag_base64 or not top_base64:
print(f"Images not found, rendering scene for {json_filename_without_ext}...")
render_scene_example(layout_file_path)
# 重新获取图片的base64编码
diag_base64 = encode_image_to_base64(diag_view_image)
top_base64 = encode_image_to_base64(top_view_image)
# 如果重新渲染后仍然无法获取图片,跳过该文件
if not diag_base64 or not top_base64:
print(f"Failed to generate or encode images for {json_filename_without_ext}, skipping...")
continue
# 生成提示词文本
prompt_text = grouping_prompt_template.replace(
"<<LAYOUT_JSON>>",
layout_json_str
)
# 正确的API调用格式
response = client.chat.completions.create(
model=deployment_name, # 使用model而不是deployment_name
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": prompt_text},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{diag_base64}",
"detail": "high"
}
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{top_base64}",
"detail": "high"
}
}
]
}
],
max_tokens=4096,
temperature=0.7, # 添加逗号
)
# 处理响应
grouped_layout_str = response.choices[0].message.content
grouped_layout_str = extract_json_from_response(grouped_layout_str)
# 保存结果
with open(output_file_path, 'w') as out_f:
json.dump(grouped_layout_str, out_f, indent=4)
print(f"Successfully generated and saved grouped layout to {output_file_path}")
except Exception as e:
print(f"An error occurred while processing {file}: {e}")
if __name__ == "__main__":
process_layout_files()