| 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: |
| |
| json_pattern = r'```json\s*\n?(.*?)\n?```' |
| match = re.search(json_pattern, content, re.DOTALL) |
| |
| if match: |
| json_str = match.group(1).strip() |
| else: |
| |
| 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: |
| |
| |
| try: |
| import ast |
| |
| 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}") |
|
|
| |
| 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}' |
|
|
| |
| 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) |
| |
| |
| 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 |
| ) |
| |
| |
| response = client.chat.completions.create( |
| 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() |