Upload 7 files
Browse files- task/generation/multimodel_svg/complex_svg_captions.json +0 -0
- task/generation/multimodel_svg/easy_svg_captions.json +0 -0
- task/generation/multimodel_svg/moderate_svg_captions.json +0 -0
- task/generation/style_trans/gen.py +275 -0
- task/generation/text_svg/complex_svg_captions.json +0 -0
- task/generation/text_svg/easy_svg_captions.json +0 -0
- task/generation/text_svg/moderate_svg_captions.json +0 -0
task/generation/multimodel_svg/complex_svg_captions.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
task/generation/multimodel_svg/easy_svg_captions.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
task/generation/multimodel_svg/moderate_svg_captions.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
task/generation/style_trans/gen.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
import json
|
| 7 |
+
import logging
|
| 8 |
+
import re
|
| 9 |
+
import time
|
| 10 |
+
import shutil
|
| 11 |
+
from typing import Dict, List, Any, Optional, Tuple
|
| 12 |
+
from datetime import datetime
|
| 13 |
+
from openai import OpenAI
|
| 14 |
+
import traceback
|
| 15 |
+
# 设置日志
|
| 16 |
+
log_dir = "./logs"
|
| 17 |
+
os.makedirs(log_dir, exist_ok=True)
|
| 18 |
+
logging.basicConfig(
|
| 19 |
+
level=logging.INFO,
|
| 20 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 21 |
+
handlers=[
|
| 22 |
+
logging.FileHandler(os.path.join(log_dir, "svg_style_transfer.log")),
|
| 23 |
+
logging.StreamHandler() # 同时输出到控制台
|
| 24 |
+
]
|
| 25 |
+
)
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
# API设置
|
| 29 |
+
API_KEY = "" # API密钥
|
| 30 |
+
BASE_URL = "" # API基础URL
|
| 31 |
+
AVAILABLE_MODELS = ["Meta-Llama-3-8B-Instruct", "Qwen2-72B-Instruct-AWQ", "gpt-4o", "gpt-4-32k", "gpt-3.5-turbo", "deepseekr1"]
|
| 32 |
+
|
| 33 |
+
# 创建OpenAI客户端
|
| 34 |
+
client = OpenAI(api_key=API_KEY, base_url=BASE_URL)
|
| 35 |
+
|
| 36 |
+
def extract_svg_from_response(response_text: str) -> Optional[str]:
|
| 37 |
+
# 尝试匹配Answer:格式的SVG
|
| 38 |
+
answer_pattern = r'Answer:\s*(<svg[\s\S]*?<\/svg>)'
|
| 39 |
+
answer_match = re.search(answer_pattern, response_text)
|
| 40 |
+
|
| 41 |
+
if answer_match:
|
| 42 |
+
return answer_match.group(1)
|
| 43 |
+
|
| 44 |
+
# 尝试匹配直接返回的SVG
|
| 45 |
+
svg_pattern = r'(<svg[\s\S]*?<\/svg>)'
|
| 46 |
+
svg_match = re.search(svg_pattern, response_text)
|
| 47 |
+
|
| 48 |
+
if svg_match:
|
| 49 |
+
return svg_match.group(1)
|
| 50 |
+
|
| 51 |
+
# 如果没有找到完整SVG,记录警告并返回None
|
| 52 |
+
logger.warning("无法从响应中提取SVG代码")
|
| 53 |
+
return None
|
| 54 |
+
|
| 55 |
+
def generate_svg_from_api(prompt: str, reference_svg: str, model: str = "deepseekr1") -> Tuple[Optional[str], float, Optional[str]]:
|
| 56 |
+
"""
|
| 57 |
+
使用API根据问题和参考SVG生成新的SVG(风格转换)
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
prompt: 描述或问题
|
| 61 |
+
reference_svg: 参考SVG代码
|
| 62 |
+
model: 要使用的模型名称
|
| 63 |
+
|
| 64 |
+
Returns:
|
| 65 |
+
生成的SVG代码、生成时间和完整响应文本
|
| 66 |
+
"""
|
| 67 |
+
start_time = time.time()
|
| 68 |
+
|
| 69 |
+
try:
|
| 70 |
+
# 构建系统提示
|
| 71 |
+
system_prompt = (
|
| 72 |
+
"""You are a professional SVG designer with extensive experience in vector graphics creation.
|
| 73 |
+
Your task is to perform a style transfer - recreate the provided reference SVG.
|
| 74 |
+
Keep the basic structure of the SVG but adapt its style based on the description.
|
| 75 |
+
Provide your answer strictly in the following format: Answer:{SVG code}, without adding any explanations, comments, or other content."""
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
# 构建用户提示
|
| 79 |
+
user_prompt = f"Reference SVG to transform:\n{reference_svg}\n\nPlease transfer to {prompt}"
|
| 80 |
+
|
| 81 |
+
# 调用API
|
| 82 |
+
response = client.chat.completions.create(
|
| 83 |
+
model=model,
|
| 84 |
+
messages=[
|
| 85 |
+
{"role": "system", "content": system_prompt},
|
| 86 |
+
{"role": "user", "content": user_prompt}
|
| 87 |
+
]
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
# 计算生成时间
|
| 91 |
+
execution_time = time.time() - start_time
|
| 92 |
+
|
| 93 |
+
# 获取完整响应
|
| 94 |
+
response_text = response.choices[0].message.content
|
| 95 |
+
|
| 96 |
+
# 提取SVG
|
| 97 |
+
svg_code = extract_svg_from_response(response_text)
|
| 98 |
+
|
| 99 |
+
return svg_code, execution_time, response_text
|
| 100 |
+
|
| 101 |
+
except Exception as e:
|
| 102 |
+
logger.error(f"error: {e}")
|
| 103 |
+
return None, time.time() - start_time, None
|
| 104 |
+
|
| 105 |
+
def process_svg_style_transfer(input_file: str, output_file: str, output_dir: str, model: str = "deepseekr1") -> Dict[str, Any]:
|
| 106 |
+
|
| 107 |
+
# 加载JSON数据
|
| 108 |
+
try:
|
| 109 |
+
with open(input_file, 'r', encoding='utf-8') as f:
|
| 110 |
+
samples_data = json.load(f)
|
| 111 |
+
|
| 112 |
+
# 确保数据是列表格式
|
| 113 |
+
if not isinstance(samples_data, list):
|
| 114 |
+
samples_data = [samples_data]
|
| 115 |
+
|
| 116 |
+
except Exception as e:
|
| 117 |
+
logger.error(f"加载JSON文件 {input_file} 失败: {e}")
|
| 118 |
+
return {"error": f"加载JSON文件失败: {e}"}
|
| 119 |
+
|
| 120 |
+
if not samples_data:
|
| 121 |
+
return {"error": "样本数据为空"}
|
| 122 |
+
|
| 123 |
+
# 确保输出目录存在
|
| 124 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 125 |
+
|
| 126 |
+
# 逐个处理样本
|
| 127 |
+
results = []
|
| 128 |
+
for i, sample in enumerate(samples_data):
|
| 129 |
+
logger.info(f"处理样本 {i+1}/{len(samples_data)}")
|
| 130 |
+
|
| 131 |
+
# 获取问题和参考SVG路径
|
| 132 |
+
question = sample.get('question', [''])[0] if isinstance(sample.get('question'), list) else sample.get('question', '')
|
| 133 |
+
gt_svg_content = sample.get('answer', '')
|
| 134 |
+
gt_svg_path = sample.get('image', '')
|
| 135 |
+
|
| 136 |
+
if not question:
|
| 137 |
+
logger.warning(f"样本 {i+1} 缺少问题描述,跳过")
|
| 138 |
+
continue
|
| 139 |
+
|
| 140 |
+
if not gt_svg_content and not gt_svg_path:
|
| 141 |
+
logger.warning(f"样本 {i+1} 既没有SVG内容也没有SVG路径,跳过")
|
| 142 |
+
continue
|
| 143 |
+
|
| 144 |
+
# 如果没有SVG内容但有路径,尝试读取
|
| 145 |
+
if not gt_svg_content and gt_svg_path:
|
| 146 |
+
try:
|
| 147 |
+
with open(gt_svg_path, 'r', encoding='utf-8') as f:
|
| 148 |
+
gt_svg_content = f.read()
|
| 149 |
+
except Exception as e:
|
| 150 |
+
logger.error(f"读取SVG文件 {gt_svg_path} 失败: {e}")
|
| 151 |
+
continue
|
| 152 |
+
|
| 153 |
+
# 获取文件名(不含路径和扩展名)
|
| 154 |
+
if gt_svg_path:
|
| 155 |
+
svg_basename = os.path.basename(gt_svg_path)
|
| 156 |
+
svg_filename = os.path.splitext(svg_basename)[0]
|
| 157 |
+
else:
|
| 158 |
+
svg_filename = f"sample_{i+1}"
|
| 159 |
+
|
| 160 |
+
# 创建样本输出目录
|
| 161 |
+
sample_output_dir = os.path.join(output_dir, svg_filename)
|
| 162 |
+
os.makedirs(sample_output_dir, exist_ok=True)
|
| 163 |
+
|
| 164 |
+
# 生成SVG
|
| 165 |
+
generated_svg, execution_time, full_response = generate_svg_from_api(question, gt_svg_content, model)
|
| 166 |
+
|
| 167 |
+
if not generated_svg:
|
| 168 |
+
result = {
|
| 169 |
+
'question': question,
|
| 170 |
+
'gt_svg_path': gt_svg_path,
|
| 171 |
+
'gt_svg': gt_svg_content,
|
| 172 |
+
'error': 'SVG生成失败',
|
| 173 |
+
'execution_time': execution_time,
|
| 174 |
+
'full_response': full_response
|
| 175 |
+
}
|
| 176 |
+
results.append(result)
|
| 177 |
+
continue
|
| 178 |
+
|
| 179 |
+
# 保存参考SVG和生成的SVG
|
| 180 |
+
gt_svg_output_path = os.path.join(sample_output_dir, svg_basename if svg_basename else f"{svg_filename}.svg")
|
| 181 |
+
gen_svg_output_path = os.path.join(sample_output_dir, f"{model}.svg")
|
| 182 |
+
|
| 183 |
+
# 保存参考SVG(如果有路径,直接复制;否则写入文件)
|
| 184 |
+
if gt_svg_path and os.path.exists(gt_svg_path):
|
| 185 |
+
shutil.copy2(gt_svg_path, gt_svg_output_path)
|
| 186 |
+
else:
|
| 187 |
+
with open(gt_svg_output_path, 'w', encoding='utf-8') as f:
|
| 188 |
+
f.write(gt_svg_content)
|
| 189 |
+
|
| 190 |
+
# 保存生成的SVG
|
| 191 |
+
with open(gen_svg_output_path, 'w', encoding='utf-8') as f:
|
| 192 |
+
f.write(generated_svg)
|
| 193 |
+
|
| 194 |
+
# 记录结果
|
| 195 |
+
result = {
|
| 196 |
+
'question': question,
|
| 197 |
+
'gt_svg_path': gt_svg_path,
|
| 198 |
+
'gt_svg': gt_svg_content,
|
| 199 |
+
'generated_svg': generated_svg,
|
| 200 |
+
'execution_time': execution_time,
|
| 201 |
+
'full_response': full_response,
|
| 202 |
+
'output_paths': {
|
| 203 |
+
'gt_svg': gt_svg_output_path,
|
| 204 |
+
'gen_svg': gen_svg_output_path
|
| 205 |
+
}
|
| 206 |
+
}
|
| 207 |
+
results.append(result)
|
| 208 |
+
|
| 209 |
+
# 显示进度
|
| 210 |
+
if (i + 1) % 5 == 0 or (i + 1) == len(samples_data):
|
| 211 |
+
logger.info(f"已处理 {i+1}/{len(samples_data)} 个样本")
|
| 212 |
+
|
| 213 |
+
# 汇总结果
|
| 214 |
+
summary = {
|
| 215 |
+
"total_samples": len(samples_data),
|
| 216 |
+
"processed_samples": len(results),
|
| 217 |
+
"successful_samples": len([r for r in results if 'error' not in r]),
|
| 218 |
+
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 219 |
+
"model": model
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
# 完整结果
|
| 223 |
+
full_result = {
|
| 224 |
+
"summary": summary,
|
| 225 |
+
"results": results
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
# 保存结果
|
| 229 |
+
try:
|
| 230 |
+
with open(output_file, 'w', encoding='utf-8') as f:
|
| 231 |
+
json.dump(full_result, f, indent=2, ensure_ascii=False)
|
| 232 |
+
logger.info(f"处理结果已保存到: {output_file}")
|
| 233 |
+
except Exception as e:
|
| 234 |
+
logger.error(f"保存结果到 {output_file} 失败: {e}")
|
| 235 |
+
|
| 236 |
+
return summary
|
| 237 |
+
|
| 238 |
+
def main():
|
| 239 |
+
"""
|
| 240 |
+
命令行入口函数
|
| 241 |
+
"""
|
| 242 |
+
import argparse
|
| 243 |
+
|
| 244 |
+
parser = argparse.ArgumentParser(description='SVG风格转换')
|
| 245 |
+
parser.add_argument('--input', type=str, required=True, help='输入JSON文件路径')
|
| 246 |
+
parser.add_argument('--output', type=str, required=True, help='输出结果的JSON文件路径')
|
| 247 |
+
parser.add_argument('--output-dir', type=str, required=True, help='输出SVG文件保存目录')
|
| 248 |
+
parser.add_argument('--model', type=str, default="Qwen2.5-72B-Instruct", choices=AVAILABLE_MODELS, help='要使用的模型名称')
|
| 249 |
+
|
| 250 |
+
args = parser.parse_args()
|
| 251 |
+
|
| 252 |
+
try:
|
| 253 |
+
# 处理样本
|
| 254 |
+
summary = process_svg_style_transfer(
|
| 255 |
+
args.input,
|
| 256 |
+
args.output,
|
| 257 |
+
args.output_dir,
|
| 258 |
+
args.model
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
# 输出简要结果
|
| 262 |
+
if "error" in summary:
|
| 263 |
+
print(f"处理失败: {summary['error']}")
|
| 264 |
+
else:
|
| 265 |
+
print(f"处理完成,共 {summary['total_samples']} 个样本,成功 {summary['successful_samples']} 个")
|
| 266 |
+
print(f"详细结果已保存到: {args.output}")
|
| 267 |
+
print(f"SVG文件已保存到: {args.output_dir}")
|
| 268 |
+
|
| 269 |
+
except Exception as e:
|
| 270 |
+
print(f"发生错误: {e}")
|
| 271 |
+
print(traceback.format_exc())
|
| 272 |
+
sys.exit(1)
|
| 273 |
+
|
| 274 |
+
if __name__ == "__main__":
|
| 275 |
+
main()
|
task/generation/text_svg/complex_svg_captions.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
task/generation/text_svg/easy_svg_captions.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
task/generation/text_svg/moderate_svg_captions.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|