import json import os import time from concurrent.futures import ThreadPoolExecutor, as_completed from typing import List, Tuple from openai import AzureOpenAI from azure.identity import ChainedTokenCredential, AzureCliCredential, ManagedIdentityCredential, get_bearer_token_provider import base64 import uuid import re from prompts import cot_gen_prompt_template_loop_v2 # from prompts import cot_gen_prompt_template_noloop_v2 import random 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: 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}") def get_azure_client(instance_type='gcr'): """创建Azure OpenAI客户端""" 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' # 支持两个实例轮换使用 if instance_type == 'gcr': instance = 'gcr/shared' else: 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, ) return client, deployment_name, instance def get_pending_files(group_layout_path: str, output_path: str, user_input_path: str, render_img_path: str) -> List[Tuple[str, str, str, str, str]]: """获取待处理的文件列表""" pending_files = [] for root, dirs, files in os.walk(group_layout_path): for file in files: if file.endswith('.json'): file_wo_json = file.replace('.json', '') output_file_path = os.path.join(output_path, file_wo_json + ".txt") # 检查是否已处理 if os.path.exists(output_file_path): continue layout_file_path = os.path.join(root, file) user_input_txt_path = os.path.join(user_input_path, file_wo_json + '.txt') # 检查用户输入文件是否存在 if not os.path.exists(user_input_txt_path): print(f"User input file not found for {file_wo_json + '.txt'}, skipping...") continue # 检查图片是否存在 diag_view_image = os.path.join(render_img_path, file_wo_json, "diag", 'frame.jpg') top_view_image = os.path.join(render_img_path, file_wo_json, "top", 'frame.jpg') if not os.path.exists(diag_view_image) or not os.path.exists(top_view_image): print(f"Images not found for {file_wo_json}, skipping...") continue pending_files.append(( layout_file_path, user_input_txt_path, diag_view_image, top_view_image, output_file_path )) return pending_files def check_cot_quality(cot_content: str) -> bool: """检查CoT内容质量,确保至少有6个段落""" if not cot_content or not cot_content.strip(): return False # 按段落分割(双换行或单换行) paragraphs = [p.strip() for p in cot_content.split('\n') if p.strip()] # 检查段落数量 if len(paragraphs) < 6: return False # 检查总长度(至少应该有一定的内容) if len(cot_content.strip()) < 500: return False return True def process_single_file(args: Tuple[Tuple[str, str, str, str, str], int]) -> Tuple[str, bool, str]: """处理单个文件""" file_data, worker_id = args layout_file_path, user_input_txt_path, diag_view_image, top_view_image, output_file_path = file_data filename = os.path.basename(layout_file_path) try: print(f"Worker {worker_id}: Processing {filename}") # 获取客户端(轮换使用两个实例) instance_type = 'gcr' if worker_id % 2 == 1 else 'msra' client, deployment_name, instance = get_azure_client(instance_type) print(f"Worker {worker_id}: Using {instance}") # 读取layout JSON with open(layout_file_path, 'r') as f: layout_json = json.load(f) layout_json_str = json.dumps(layout_json, indent=4) # 读取用户输入 with open(user_input_txt_path, 'r') as f: user_input = f.read().strip() # 编码图片 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: return filename, False, "Failed to encode images" # 生成提示词文本 # cot_prompt = random.choice([cot_gen_prompt_template_loop_v2, cot_gen_prompt_template_noloop_v2]) cot_prompt = cot_gen_prompt_template_loop_v2 prompt_text = cot_prompt.replace( "<<>>", layout_json_str ).replace( "<<>>", user_input ) # API调用,增加重试机制和质量检查 max_retries = 100 max_quality_retries = 100 # 质量重试次数 for quality_attempt in range(max_quality_retries + 1): cot_str = None # API调用重试 for attempt in range(max_retries): try: 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=1.0, ) # 处理响应 cot_str = response.choices[0].message.content.replace('\n\n', '\n').strip() break # 成功则跳出重试循环 except Exception as e: if attempt == max_retries - 1: raise e print(f"Worker {worker_id}: API retry {attempt + 1} for {filename}") time.sleep(2 ** attempt) # 指数退避 # 检查CoT质量 if cot_str and check_cot_quality(cot_str): break # 质量合格,跳出质量重试循环 else: if quality_attempt < max_quality_retries: print(f"Worker {worker_id}: CoT quality insufficient for {filename}, retrying... (attempt {quality_attempt + 1})") time.sleep(1) # 短暂等待后重试 else: print(f"Worker {worker_id}: Warning - CoT quality still insufficient for {filename} after {max_quality_retries} retries, proceeding anyway") # 保存结果 with open(output_file_path, 'w') as output_file: output_file.write(cot_str) # 最终质量检查报告 quality_passed = check_cot_quality(cot_str) quality_status = "✅" if quality_passed else "⚠️" print(f"Worker {worker_id}: {quality_status} Successfully processed {filename} (Quality: {'Pass' if quality_passed else 'Warning'})") return filename, True, "" except Exception as e: error_msg = f"Worker {worker_id}: ❌ Error processing {filename}: {str(e)}" print(error_msg) return filename, False, str(e) def process_layout_files_parallel(num_workers: int = 10): """并行处理layout files""" group_layout_path = "/home/v-meiszhang/amlt-project/respace/grouped_layouts_v2" render_img_path = "/home/v-meiszhang/amlt-project/respace/eval/viz/misc" user_input_path = "/home/v-meiszhang/amlt-project/respace/user_design_layouts_v3" output_path = "/home/v-meiszhang/amlt-project/respace/layout_design_cot_loop_v3.1" # 确保输出目录存在 os.makedirs(output_path, exist_ok=True) # 获取待处理的文件 pending_files = get_pending_files(group_layout_path, output_path, user_input_path, render_img_path) print(f"Found {len(pending_files)} files to process") if not pending_files: print("No files to process!") return # 准备任务参数 task_args = [ (file_data, i % num_workers + 1) for i, file_data in enumerate(pending_files) ] # 统计变量 successful_count = 0 failed_count = 0 failed_files = [] print(f"🚀 Starting parallel processing with {num_workers} workers...") # 使用ThreadPoolExecutor进行并行处理 with ThreadPoolExecutor(max_workers=num_workers) as executor: # 提交所有任务 future_to_file = { executor.submit(process_single_file, args): args[0][0] for args in task_args } # 收集结果 for future in as_completed(future_to_file): file_path = future_to_file[future] try: filename, success, error_msg = future.result() if success: successful_count += 1 else: failed_count += 1 failed_files.append(filename) except Exception as exc: failed_count += 1 filename = os.path.basename(file_path) failed_files.append(filename) print(f"Task for {filename} generated exception: {exc}") # 打印最终统计 print("\n" + "="*60) print("🎉 Processing completed!") print(f"✅ Successfully processed: {successful_count} files") print(f"❌ Failed to process: {failed_count} files") print(f"📊 Total files: {len(pending_files)}") if len(pending_files) > 0: print(f"📈 Success rate: {successful_count/len(pending_files)*100:.1f}%") # 打印失败的文件 if failed_files: print(f"\n❌ Failed files:") for filename in failed_files[:10]: # 只显示前10个 print(f" - {filename}") if len(failed_files) > 10: print(f" ... and {len(failed_files) - 10} more") def process_layout_files_batch(batch_size: int = 50, num_workers: int = 10): """分批并行处理,避免一次性处理太多文件导致内存问题""" group_layout_path = "/home/v-meiszhang/amlt-project/respace/grouped_layouts_v2" render_img_path = "/home/v-meiszhang/amlt-project/respace/eval/viz/misc" user_input_path = "/home/v-meiszhang/amlt-project/respace/user_design_layouts_v3" output_path = "/home/v-meiszhang/amlt-project/respace/layout_design_cot_loop_v3.1" os.makedirs(output_path, exist_ok=True) # 获取待处理的文件 pending_files = get_pending_files(group_layout_path, output_path, user_input_path, render_img_path) print(f"Found {len(pending_files)} files to process") if not pending_files: print("No files to process!") return # 分批处理 total_successful = 0 total_failed = 0 batch_count = (len(pending_files) + batch_size - 1) // batch_size for batch_idx in range(0, len(pending_files), batch_size): batch_files = pending_files[batch_idx:batch_idx + batch_size] current_batch = batch_idx // batch_size + 1 print(f"\n🔄 Processing batch {current_batch}/{batch_count} ({len(batch_files)} files)") # 准备当前批次的任务参数 task_args = [ (file_data, i % num_workers + 1) for i, file_data in enumerate(batch_files) ] batch_successful = 0 batch_failed = 0 # 处理当前批次 with ThreadPoolExecutor(max_workers=num_workers) as executor: future_to_file = { executor.submit(process_single_file, args): args[0][0] for args in task_args } for future in as_completed(future_to_file): try: filename, success, error_msg = future.result() if success: batch_successful += 1 else: batch_failed += 1 except Exception as exc: batch_failed += 1 print(f"Task exception: {exc}") total_successful += batch_successful total_failed += batch_failed print(f"Batch {current_batch} completed: ✅ {batch_successful} success, ❌ {batch_failed} failed") # 批次间短暂休息,避免API限流 if current_batch < batch_count: print("Resting 2 seconds between batches...") time.sleep(2) # 最终统计 print("\n" + "="*60) print("🎉 All batches completed!") print(f"✅ Total successful: {total_successful} files") print(f"❌ Total failed: {total_failed} files") print(f"📊 Total files: {len(pending_files)}") if len(pending_files) > 0: print(f"📈 Overall success rate: {total_successful/len(pending_files)*100:.1f}%") def main(): """主函数""" import argparse parser = argparse.ArgumentParser(description="Parallel CoT generation") parser.add_argument("--workers", "-w", type=int, default=20, help="Number of parallel workers (default: 10)") parser.add_argument("--batch-size", "-b", type=int, default=0, help="Batch size for processing (0 = process all at once)") args = parser.parse_args() if args.batch_size > 0: print(f"🚀 Starting batch processing with {args.workers} workers, batch size: {args.batch_size}") process_layout_files_batch(args.batch_size, args.workers) else: print(f"🚀 Starting parallel processing with {args.workers} workers") process_layout_files_parallel(args.workers) if __name__ == "__main__": main()