-
Notifications
You must be signed in to change notification settings - Fork 207
Expand file tree
/
Copy pathautofigure2.py
More file actions
3678 lines (3107 loc) · 131 KB
/
autofigure2.py
File metadata and controls
3678 lines (3107 loc) · 131 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Paper Method 到 SVG 图标替换完整流程 (Label 模式增强版 + Box合并 + 多Prompt支持)
支持的 API Provider:
- openrouter: OpenRouter API (https://openrouter.ai/api/v1)
- bianxie: Bianxie API (https://api.bianxie.ai/v1) - 使用 OpenAI SDK
- gemini: Google Gemini 官方 API (https://ai.google.dev/)
- openai: OpenAI Images API(仅步骤一生图 override)
- openai_response: OpenAI Responses API(文本/多模态 SVG 重建)
占位符模式 (--placeholder_mode):
- none: 无特殊样式(默认黑色边框)
- box: 传入 boxlib 坐标给 LLM
- label: 灰色填充+黑色边框+序号标签 <AF>01, <AF>02...(推荐)
SAM3 多Prompt支持 (--sam_prompt):
- 支持逗号分隔的多个text prompt
- 例如: "icon,diagram,arrow,chart"
- 对每个prompt分别检测,然后合并去重结果
- boxlib.json 会记录每个box的来源prompt
Box合并功能 (--merge_threshold):
- 对SAM3检测到的重叠box进行合并去重
- 重叠比例 = 交集面积 / 较小box面积
- 默认阈值0.9,设为0表示不合并
- 跨prompt检测结果也会自动去重
流程:
1. 输入 paper method 文本,调用图像模型生成学术风格图片 -> figure.png
2. SAM3 分割图片,用灰色填充+黑色边框+序号标记 -> samed.png + boxlib.json
2.1 支持多个text prompts分别检测
2.2 合并重叠的boxes(可选,通过 --merge_threshold 控制)
3. 裁切分割区域 + RMBG2 去背景 -> icons/icon_AF01_nobg.png, icon_AF02_nobg.png...
4. 多模态调用 LLM 生成 SVG(占位符样式与 samed.png 一致)-> template.svg
4.5. SVG 语法验证(lxml)+ LLM 修复
4.6. LLM 优化 SVG 模板(位置和样式对齐)-> optimized_template.svg
可通过 --optimize_iterations 参数控制迭代次数(0 表示跳过优化)
4.7. 坐标系对齐:比较 figure.png 与 SVG 尺寸,计算缩放因子
5. 根据序号匹配,将透明图标替换到 SVG 占位符中 -> final.svg
使用方法:
# 使用 Bianxie + label 模式(默认)
python iou_autofigure.py --method_file paper_method.txt --output_dir ./output --api_key "your-key"
# 使用 OpenRouter
python iou_autofigure.py --method_file paper_method.txt --output_dir ./output --api_key "sk-or-v1-xxx" --provider openrouter
# 仅步骤一改用 OpenAI GPT-Image,步骤四仍走原 provider
python iou_autofigure.py --method_file paper_method.txt --output_dir ./output --provider gemini --api_key "gemini-key" --image_provider openai --image_api_key "sk-openai-xxx" --image_model gpt-image-2
# 使用 box 模式(传入坐标)
python iou_autofigure.py --method_file paper_method.txt --output_dir ./output --placeholder_mode box
# 使用多个 SAM3 prompts 检测
python iou_autofigure.py --method_file paper_method.txt --output_dir ./output --sam_prompt "icon,diagram,arrow"
# 跳过步骤 4.6 优化(设置迭代次数为 0)
python iou_autofigure.py --method_file paper_method.txt --output_dir ./output --optimize_iterations 0
# 设置步骤 4.6 优化迭代 3 次
python iou_autofigure.py --method_file paper_method.txt --output_dir ./output --optimize_iterations 3
# 自定义 box 合并阈值(0.8)
python iou_autofigure.py --method_file paper_method.txt --output_dir ./output --merge_threshold 0.8
# 禁用 box 合并
python iou_autofigure.py --method_file paper_method.txt --output_dir ./output --merge_threshold 0
"""
from __future__ import annotations
import argparse
import base64
import io
import json
import os
import re
import shutil
import sys
import time
from pathlib import Path
from typing import Optional, List, Dict, Any, Literal
import requests
import numpy as np
import torch
from PIL import Image, ImageDraw, ImageFont, ImageOps
from torchvision import transforms
from transformers import AutoModelForImageSegmentation
# ============================================================================
# Provider 配置
# ============================================================================
PROVIDER_CONFIGS = {
"openrouter": {
"base_url": "https://openrouter.ai/api/v1",
"default_image_model": "google/gemini-3.1-flash-image-preview",
"default_svg_model": "google/gemini-3.1-pro-preview",
},
"custom": {
"base_url": "https://api.bianxie.ai/v1",
"default_image_model": "gemini-3.1-flash-image-preview",
"default_svg_model": "gemini-3.1-pro-preview",
},
"bianxie": {
"base_url": "https://api.bianxie.ai/v1",
"default_image_model": "gemini-3.1-flash-image-preview",
"default_svg_model": "gemini-3.1-pro-preview",
},
"gemini": {
"base_url": "https://generativelanguage.googleapis.com/v1beta",
"default_image_model": "gemini-3.1-flash-image-preview",
"default_svg_model": "gemini-3.1-pro-preview",
},
"openai_response": {
"base_url": "https://api.openai.com/v1",
"default_image_model": "gpt-image-2",
"default_svg_model": "gpt-5.5",
},
}
IMAGE_PROVIDER_CONFIGS = {
**PROVIDER_CONFIGS,
"openai": {
"base_url": "https://api.openai.com/v1",
"default_image_model": "gpt-image-2",
},
}
ProviderType = Literal["openrouter", "custom", "bianxie", "gemini", "openai_response"]
ImageProviderType = Literal["openrouter", "custom", "bianxie", "gemini", "openai"]
PlaceholderMode = Literal["none", "box", "label"]
GEMINI_DEFAULT_IMAGE_SIZE = "4K"
IMAGE_SIZE_CHOICES = ("1K", "2K", "4K")
OPENAI_DEFAULT_IMAGE_SIZE = "1536x1024"
OPENAI_IMAGE_SIZE_CHOICES = ("1024x1024", "1536x1024", "1024x1536", "auto")
UPSCALE_TARGET_LONG_EDGE = 3840
BOXLIB_NO_ICON_MODE_KEY = "no_icon_mode"
# SAM3 API config
SAM3_FAL_API_URL = "https://fal.run/fal-ai/sam-3/image"
SAM3_ROBOFLOW_API_URL = os.environ.get(
"ROBOFLOW_API_URL",
"https://serverless.roboflow.com/sam3/concept_segment",
)
SAM3_API_TIMEOUT = 300
# Step 1 reference image settings (overridden by CLI)
USE_REFERENCE_IMAGE = False
REFERENCE_IMAGE_PATH: Optional[str] = None
# ============================================================================
# 统一的 LLM 调用接口
# ============================================================================
def call_llm_text(
prompt: str,
api_key: str,
model: str,
base_url: str,
provider: ProviderType,
max_tokens: int = 16000,
temperature: float = 0.7,
) -> Optional[str]:
"""
统一的文本 LLM 调用接口
Args:
prompt: 文本提示
api_key: API Key
model: 模型名称
base_url: API base URL
provider: API 提供商
reference_image: 参考图片(可选)
max_tokens: 最大输出 token 数
temperature: 温度参数
Returns:
LLM 响应文本
"""
if provider in ("bianxie", "custom"):
return _call_bianxie_text(prompt, api_key, model, base_url, max_tokens, temperature)
if provider == "gemini":
return _call_gemini_text(prompt, api_key, model, max_tokens, temperature)
if provider == "openai_response":
return _call_openai_response_text(prompt, api_key, model, base_url, max_tokens, temperature)
return _call_openrouter_text(prompt, api_key, model, base_url, max_tokens, temperature)
def call_llm_multimodal(
contents: List[Any],
api_key: str,
model: str,
base_url: str,
provider: ProviderType,
max_tokens: int = 16000,
temperature: float = 0.7,
) -> Optional[str]:
"""
统一的多模态 LLM 调用接口
Args:
contents: 内容列表(字符串或 PIL Image)
api_key: API Key
model: 模型名称
base_url: API base URL
provider: API 提供商
max_tokens: 最大输出 token 数
temperature: 温度参数
Returns:
LLM 响应文本
"""
if provider in ("bianxie", "custom"):
return _call_bianxie_multimodal(contents, api_key, model, base_url, max_tokens, temperature)
if provider == "gemini":
return _call_gemini_multimodal(contents, api_key, model, max_tokens, temperature)
if provider == "openai_response":
return _call_openai_response_multimodal(
contents, api_key, model, base_url, max_tokens, temperature
)
return _call_openrouter_multimodal(contents, api_key, model, base_url, max_tokens, temperature)
def call_llm_image_generation(
prompt: str,
api_key: str,
model: str,
base_url: str,
provider: ImageProviderType,
reference_image: Optional[Image.Image] = None,
image_size: str = GEMINI_DEFAULT_IMAGE_SIZE,
) -> Optional[Image.Image]:
"""
统一的图像生成 LLM 调用接口
Args:
prompt: 文本提示
api_key: API Key
model: 模型名称
base_url: API base URL
provider: API 提供商
Returns:
生成的 PIL Image,失败返回 None
"""
if provider in ("bianxie", "custom"):
return _call_bianxie_image_generation(prompt, api_key, model, base_url, reference_image)
if provider == "gemini":
return _call_gemini_image_generation(
prompt=prompt,
api_key=api_key,
model=model,
reference_image=reference_image,
image_size=image_size,
)
if provider == "openai":
return _call_openai_image_generation(
prompt=prompt,
api_key=api_key,
model=model,
base_url=base_url,
reference_image=reference_image,
image_size=image_size,
)
return _call_openrouter_image_generation(prompt, api_key, model, base_url, reference_image)
# ============================================================================
# Bianxie Provider 实现 (使用 OpenAI SDK)
# ============================================================================
def _call_bianxie_text(
prompt: str,
api_key: str,
model: str,
base_url: str,
max_tokens: int = 16000,
temperature: float = 0.7,
) -> Optional[str]:
"""使用 OpenAI SDK 调用 Bianxie 文本接口"""
try:
from openai import OpenAI
client = OpenAI(base_url=base_url, api_key=api_key)
completion = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
max_tokens=max_tokens,
temperature=temperature,
)
return completion.choices[0].message.content if completion and completion.choices else None
except Exception as e:
print(f"[Bianxie] API 调用失败: {e}")
raise
def _call_bianxie_multimodal(
contents: List[Any],
api_key: str,
model: str,
base_url: str,
max_tokens: int = 16000,
temperature: float = 0.7,
) -> Optional[str]:
"""使用 OpenAI SDK 调用 Bianxie 多模态接口"""
try:
from openai import OpenAI
client = OpenAI(base_url=base_url, api_key=api_key)
message_content: List[Dict[str, Any]] = []
for part in contents:
if isinstance(part, str):
message_content.append({"type": "text", "text": part})
elif isinstance(part, Image.Image):
buf = io.BytesIO()
part.save(buf, format='PNG')
image_b64 = base64.b64encode(buf.getvalue()).decode('utf-8')
message_content.append({
"type": "image_url",
"image_url": {"url": f"data:image/png;base64,{image_b64}"}
})
completion = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": message_content}],
max_tokens=max_tokens,
temperature=temperature,
)
return completion.choices[0].message.content if completion and completion.choices else None
except Exception as e:
print(f"[Bianxie] 多模态 API 调用失败: {e}")
raise
def _call_bianxie_image_generation(
prompt: str,
api_key: str,
model: str,
base_url: str,
reference_image: Optional[Image.Image] = None,
) -> Optional[Image.Image]:
"""使用 OpenAI SDK 调用 Bianxie 图像生成接口"""
try:
from openai import OpenAI
client = OpenAI(base_url=base_url, api_key=api_key)
if reference_image is None:
messages = [{"role": "user", "content": prompt}]
else:
buf = io.BytesIO()
reference_image.save(buf, format='PNG')
image_b64 = base64.b64encode(buf.getvalue()).decode('utf-8')
message_content = [
{"type": "text", "text": prompt},
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image_b64}"}},
]
messages = [{"role": "user", "content": message_content}]
completion = client.chat.completions.create(
model=model,
messages=messages,
)
content = completion.choices[0].message.content if completion and completion.choices else None
if not content:
return None
# Bianxie 返回 Markdown 格式的图片: 
pattern = r'data:image/(png|jpeg|jpg|webp);base64,([A-Za-z0-9+/=]+)'
match = re.search(pattern, content)
if match:
image_base64 = match.group(2)
image_data = base64.b64decode(image_base64)
return Image.open(io.BytesIO(image_data))
return None
except Exception as e:
print(f"[Bianxie] 图像生成 API 调用失败: {e}")
raise
def _pil_image_to_data_uri(image: Image.Image) -> str:
"""Convert a PIL image to a PNG data URI."""
buf = io.BytesIO()
image.save(buf, format="PNG")
image_b64 = base64.b64encode(buf.getvalue()).decode("utf-8")
return f"data:image/png;base64,{image_b64}"
def _extract_openai_response_text(response: Any) -> Optional[str]:
"""Extract plain text from a Responses API response."""
text = getattr(response, "output_text", None)
if isinstance(text, str) and text.strip():
return text
extracted: list[str] = []
for item in getattr(response, "output", None) or []:
if getattr(item, "type", None) != "message":
continue
for content in getattr(item, "content", None) or []:
if getattr(content, "type", None) != "output_text":
continue
content_text = getattr(content, "text", None)
if isinstance(content_text, str) and content_text.strip():
extracted.append(content_text)
if extracted:
return "".join(extracted)
return None
def _build_openai_response_input(contents: List[Any]) -> List[Dict[str, Any]]:
"""Build a Responses API input payload from text and PIL images."""
message_content: List[Dict[str, Any]] = []
for part in contents:
if isinstance(part, str):
message_content.append({"type": "input_text", "text": part})
elif isinstance(part, Image.Image):
message_content.append(
{
"type": "input_image",
"image_url": _pil_image_to_data_uri(part),
"detail": "high",
}
)
return [{"role": "user", "content": message_content}]
def _call_openai_response_text(
prompt: str,
api_key: str,
model: str,
base_url: str,
max_tokens: int = 16000,
temperature: float = 0.7,
) -> Optional[str]:
"""Use the OpenAI Responses API for text generation."""
try:
from openai import OpenAI
client = OpenAI(base_url=base_url, api_key=api_key, timeout=300)
response = client.responses.create(
model=model,
input=[{"role": "user", "content": [{"type": "input_text", "text": prompt}]}],
max_output_tokens=max_tokens,
temperature=temperature,
)
return _extract_openai_response_text(response)
except Exception as e:
print(f"[OpenAI Responses] 文本 API 调用失败: {e}")
raise
def _call_openai_response_multimodal(
contents: List[Any],
api_key: str,
model: str,
base_url: str,
max_tokens: int = 16000,
temperature: float = 0.7,
) -> Optional[str]:
"""Use the OpenAI Responses API for multimodal generation."""
try:
from openai import OpenAI
client = OpenAI(base_url=base_url, api_key=api_key, timeout=300)
response = client.responses.create(
model=model,
input=_build_openai_response_input(contents),
max_output_tokens=max_tokens,
temperature=temperature,
)
return _extract_openai_response_text(response)
except Exception as e:
print(f"[OpenAI Responses] 多模态 API 调用失败: {e}")
raise
def _resolve_openai_image_size(
image_size: Optional[str],
reference_image: Optional[Image.Image] = None,
) -> str:
"""将项目现有的生图尺寸提示映射到 OpenAI Images API 的 size 参数。"""
if image_size in OPENAI_IMAGE_SIZE_CHOICES:
return image_size
if image_size == "1K":
return "1024x1024"
if image_size == "2K":
return "1536x1024"
if reference_image is not None:
width, height = reference_image.size
if width >= height * 1.15:
return "1536x1024"
if height >= width * 1.15:
return "1024x1536"
return "1024x1024"
return OPENAI_DEFAULT_IMAGE_SIZE
def _extract_openai_image_response(response: Any) -> Optional[Image.Image]:
"""从 OpenAI Images API 响应中提取图片。"""
data = getattr(response, "data", None) or []
for item in data:
image_b64 = getattr(item, "b64_json", None)
if isinstance(image_b64, str) and image_b64.strip():
image_data = base64.b64decode(image_b64)
image = Image.open(io.BytesIO(image_data))
image.load()
return image
image_url = getattr(item, "url", None)
if isinstance(image_url, str) and image_url.strip():
resp = requests.get(image_url, timeout=120)
resp.raise_for_status()
image = Image.open(io.BytesIO(resp.content))
image.load()
return image
return None
def _call_openai_image_generation(
prompt: str,
api_key: str,
model: str,
base_url: str,
reference_image: Optional[Image.Image] = None,
image_size: str = GEMINI_DEFAULT_IMAGE_SIZE,
) -> Optional[Image.Image]:
"""使用 OpenAI Images API 调用 GPT-Image 生图 / 参考图编辑。"""
try:
from openai import OpenAI
client = OpenAI(base_url=base_url, api_key=api_key, timeout=300)
resolved_size = _resolve_openai_image_size(image_size, reference_image)
if reference_image is None:
response = client.images.generate(
model=model,
prompt=prompt,
size=resolved_size,
quality="high",
output_format="png",
)
else:
buf = io.BytesIO()
reference_image.convert("RGBA").save(buf, format="PNG")
image_file = ("reference.png", buf.getvalue(), "image/png")
response = client.images.edit(
model=model,
image=image_file,
prompt=prompt,
size=resolved_size,
quality="high",
output_format="png",
)
return _extract_openai_image_response(response)
except Exception as e:
print(f"[OpenAI] 图像生成 API 调用失败: {e}")
raise
# ============================================================================
# OpenRouter Provider 实现 (使用 requests)
# ============================================================================
def _get_openrouter_headers(api_key: str) -> dict:
"""获取 OpenRouter 请求头"""
return {
'Content-Type': 'application/json',
'Authorization': f'Bearer {api_key}',
'HTTP-Referer': 'https://localhost',
'X-Title': 'MethodToSVG'
}
def _get_openrouter_api_url(base_url: str) -> str:
"""获取 OpenRouter API URL"""
if not base_url.endswith('/chat/completions'):
if base_url.endswith('/'):
return base_url + 'chat/completions'
else:
return base_url + '/chat/completions'
return base_url
def _extract_openrouter_message_text(message: Any) -> Optional[str]:
"""尽可能从 OpenRouter message 中提取文本,兼容 string/list/object 多种 content 形态"""
if not isinstance(message, dict):
return None
def _collect_from_part(part: Any, out: list[str]) -> None:
if isinstance(part, str):
text = part.strip()
if text:
out.append(text)
return
if not isinstance(part, dict):
return
for key in ("text", "content", "value"):
value = part.get(key)
if isinstance(value, str) and value.strip():
out.append(value.strip())
nested = part.get("content")
if isinstance(nested, list):
for item in nested:
_collect_from_part(item, out)
content = message.get("content")
if isinstance(content, str) and content.strip():
return content.strip()
if isinstance(content, dict):
chunks: list[str] = []
_collect_from_part(content, chunks)
if chunks:
return "\n".join(chunks)
if isinstance(content, list):
chunks: list[str] = []
for part in content:
_collect_from_part(part, chunks)
if chunks:
return "\n".join(chunks)
for key in ("output_text", "text"):
value = message.get(key)
if isinstance(value, str) and value.strip():
return value.strip()
return None
def _summarize_openrouter_choice(choice: Any) -> str:
"""构造可读的 OpenRouter choice 摘要,便于定位空响应问题"""
if not isinstance(choice, dict):
return f"invalid choice type={type(choice).__name__}"
message = choice.get("message")
if not isinstance(message, dict):
return (
f"finish_reason={choice.get('finish_reason')}, "
f"message_type={type(message).__name__}"
)
content = message.get("content")
content_type = type(content).__name__
if isinstance(content, str):
content_size = len(content)
elif isinstance(content, list):
content_size = len(content)
elif isinstance(content, dict):
content_size = len(content.keys())
else:
content_size = 0
refusal = message.get("refusal")
refusal_preview = repr(refusal)
if len(refusal_preview) > 220:
refusal_preview = refusal_preview[:220] + "..."
return (
f"finish_reason={choice.get('finish_reason')}, "
f"message_keys={sorted(message.keys())}, "
f"content_type={content_type}, "
f"content_size={content_size}, "
f"refusal={refusal_preview}"
)
def _call_openrouter_text(
prompt: str,
api_key: str,
model: str,
base_url: str,
max_tokens: int = 16000,
temperature: float = 0.7,
) -> Optional[str]:
"""使用 requests 调用 OpenRouter 文本接口"""
api_url = _get_openrouter_api_url(base_url)
headers = _get_openrouter_headers(api_key)
payload = {
'model': model,
'messages': [{'role': 'user', 'content': prompt}],
'max_tokens': max_tokens,
'temperature': temperature,
'stream': False
}
response = requests.post(api_url, headers=headers, json=payload, timeout=300)
if response.status_code != 200:
raise Exception(f'OpenRouter API 错误: {response.status_code} - {response.text[:500]}')
result = response.json()
if 'error' in result:
error_msg = result.get('error', {})
if isinstance(error_msg, dict):
error_msg = error_msg.get('message', str(error_msg))
raise Exception(f'OpenRouter API 错误: {error_msg}')
choices = result.get('choices', [])
if not choices:
return None
message = choices[0].get('message', {})
text = _extract_openrouter_message_text(message)
if text:
return text
return None
def _call_openrouter_multimodal(
contents: List[Any],
api_key: str,
model: str,
base_url: str,
max_tokens: int = 16000,
temperature: float = 0.7,
) -> Optional[str]:
"""使用 requests 调用 OpenRouter 多模态接口"""
api_url = _get_openrouter_api_url(base_url)
headers = _get_openrouter_headers(api_key)
message_content: List[Dict[str, Any]] = []
for part in contents:
if isinstance(part, str):
message_content.append({"type": "text", "text": part})
elif isinstance(part, Image.Image):
buf = io.BytesIO()
part.save(buf, format='PNG')
image_b64 = base64.b64encode(buf.getvalue()).decode('utf-8')
message_content.append({
"type": "image_url",
"image_url": {"url": f"data:image/png;base64,{image_b64}"}
})
payload = {
'model': model,
'messages': [{'role': 'user', 'content': message_content}],
'max_tokens': max_tokens,
'temperature': temperature,
'stream': False
}
retry_env = os.environ.get("OPENROUTER_MULTIMODAL_RETRIES", "3")
delay_env = os.environ.get("OPENROUTER_MULTIMODAL_RETRY_DELAY", "1.5")
try:
retry_count = max(1, int(retry_env))
except ValueError:
retry_count = 3
try:
retry_delay = max(0.0, float(delay_env))
except ValueError:
retry_delay = 1.5
last_error: Optional[Exception] = None
for attempt in range(1, retry_count + 1):
try:
response = requests.post(api_url, headers=headers, json=payload, timeout=300)
if response.status_code != 200:
raise Exception(f'OpenRouter API 错误: {response.status_code} - {response.text[:500]}')
result = response.json()
if 'error' in result:
error_msg = result.get('error', {})
if isinstance(error_msg, dict):
error_msg = error_msg.get('message', str(error_msg))
raise Exception(f'OpenRouter API 错误: {error_msg}')
choices = result.get('choices', [])
if not choices:
raise RuntimeError("OpenRouter 返回 choices 为空")
message = choices[0].get('message', {})
text = _extract_openrouter_message_text(message)
if text:
return text
choice_summary = _summarize_openrouter_choice(choices[0])
raise RuntimeError(
"OpenRouter 多模态响应没有可解析文本内容。"
f" model={model}, summary={choice_summary}"
)
except Exception as e:
last_error = e
if attempt < retry_count:
sleep_s = retry_delay * (2 ** (attempt - 1))
print(
f"OpenRouter 多模态请求失败(尝试 {attempt}/{retry_count}):{e},"
f"{sleep_s:.1f}s 后重试..."
)
time.sleep(sleep_s)
continue
break
if last_error is not None:
raise last_error
return None
def _call_openrouter_image_generation(
prompt: str,
api_key: str,
model: str,
base_url: str,
reference_image: Optional[Image.Image] = None,
) -> Optional[Image.Image]:
"""使用 requests 调用 OpenRouter 图像生成接口"""
api_url = _get_openrouter_api_url(base_url)
headers = _get_openrouter_headers(api_key)
if reference_image is None:
messages = [{'role': 'user', 'content': prompt}]
else:
buf = io.BytesIO()
reference_image.save(buf, format='PNG')
image_b64 = base64.b64encode(buf.getvalue()).decode('utf-8')
message_content: List[Dict[str, Any]] = [
{"type": "text", "text": prompt},
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image_b64}"}},
]
messages = [{'role': 'user', 'content': message_content}]
payload = {
'model': model,
'messages': messages,
# 对 OpenRouter 的 Gemini 图像模型,强制 image-only 可显著降低“返回纯文本无图片”的概率
'modalities': ['image'],
'stream': False
}
response = requests.post(api_url, headers=headers, json=payload, timeout=300)
if response.status_code != 200:
raise Exception(f'OpenRouter API 错误: {response.status_code} - {response.text[:500]}')
result = response.json()
if 'error' in result:
error_msg = result.get('error', {})
if isinstance(error_msg, dict):
error_msg = error_msg.get('message', str(error_msg))
raise Exception(f'OpenRouter API 错误: {error_msg}')
def _extract_data_url_payload(data_url: str) -> Optional[str]:
match = re.match(r"^data:image/[^;]+;base64,(.+)$", data_url, flags=re.IGNORECASE | re.DOTALL)
if not match:
return None
return re.sub(r"\s+", "", match.group(1))
def _decode_base64_image(image_b64: str) -> Optional[Image.Image]:
if not image_b64:
return None
try:
b64 = re.sub(r"\s+", "", image_b64)
padding = len(b64) % 4
if padding:
b64 += "=" * (4 - padding)
image_data = base64.b64decode(b64)
image = Image.open(io.BytesIO(image_data))
image.load()
return image
except Exception:
return None
def _load_remote_image(image_url: str) -> Optional[Image.Image]:
try:
resp = requests.get(image_url, timeout=120)
if resp.status_code != 200 or not resp.content:
return None
image = Image.open(io.BytesIO(resp.content))
image.load()
return image
except Exception:
return None
def _extract_image_url(value: Any) -> Optional[str]:
if isinstance(value, str):
return value
if isinstance(value, dict):
if isinstance(value.get("url"), str):
return value["url"]
if "image_url" in value:
return _extract_image_url(value.get("image_url"))
return None
def _try_parse_image_candidate(candidate: Any) -> Optional[Image.Image]:
if isinstance(candidate, dict):
# OpenAI/OpenRouter 常见图片字段
for key in ("b64_json", "base64", "data"):
raw = candidate.get(key)
if isinstance(raw, str):
parsed = _decode_base64_image(raw)
if parsed is not None:
return parsed
if "image_url" in candidate:
parsed = _try_parse_image_candidate(candidate.get("image_url"))
if parsed is not None:
return parsed
if "url" in candidate:
parsed = _try_parse_image_candidate(candidate.get("url"))
if parsed is not None:
return parsed
return None
if not isinstance(candidate, str):
return None
candidate = candidate.strip()
if not candidate:
return None
if candidate.startswith("data:image/"):
b64_payload = _extract_data_url_payload(candidate)
if b64_payload:
return _decode_base64_image(b64_payload)
return None
if candidate.startswith("http://") or candidate.startswith("https://"):
return _load_remote_image(candidate)
# 极少数场景服务会直接返回纯 base64
return _decode_base64_image(candidate)
def _extract_markdown_image_urls(text: str) -> list[str]:
urls: list[str] = []
for match in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", text):
urls.append(match.group(1).strip())
for match in re.finditer(r"data:image/[^;]+;base64,[A-Za-z0-9+/=\s]+", text, flags=re.IGNORECASE):
urls.append(match.group(0).strip())
return urls
choices = result.get('choices', [])
if not choices:
raise RuntimeError("OpenRouter 返回中没有 choices,无法解析生图结果。")
message = choices[0].get('message', {})
candidates: list[Any] = []
images = message.get("images")
if isinstance(images, list):
candidates.extend(images)
elif images is not None:
candidates.append(images)
content = message.get("content")
if isinstance(content, list):
candidates.extend(content)
elif isinstance(content, str):
candidates.extend(_extract_markdown_image_urls(content))
# 某些中间层会把图片放到顶层字段
top_images = result.get("images")
if isinstance(top_images, list):
candidates.extend(top_images)
for item in candidates:
# 先尝试直接解析对象
parsed = _try_parse_image_candidate(item)
if parsed is not None:
return parsed
# 再尝试从对象中抽取 URL 字符串
image_url = _extract_image_url(item)
if image_url:
parsed = _try_parse_image_candidate(image_url)
if parsed is not None:
return parsed
content_preview = ""
if isinstance(content, str):
content_preview = content[:240].replace("\n", " ")
refusal = message.get("refusal")
message_keys = sorted(message.keys()) if isinstance(message, dict) else []
images_count = len(images) if isinstance(images, list) else 0