-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimax_cli.py
More file actions
3727 lines (3261 loc) · 140 KB
/
minimax_cli.py
File metadata and controls
3727 lines (3261 loc) · 140 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MiniMax AI 统一命令行工具
简洁高效,无垃圾代码版本
"""
import os
import sys
import json
import time
import requests
import base64
import mimetypes
from datetime import datetime
from pathlib import Path
from typing import Optional, Dict, Any
import argparse
class MiniMaxClient:
"""精简版MiniMax客户端"""
def __init__(self):
self.group_id = os.getenv("MINIMAX_GROUP_ID")
self.api_key = os.getenv("MINIMAX_API_KEY")
self.base_url = "https://api.minimaxi.com/v1"
self.verbose = False
if not self.group_id or not self.api_key:
self._setup_credentials()
def _log(self, message: str, level: str = "INFO"):
"""日志输出"""
print(f"[{level}] {message}")
def _log_request(self, method: str, endpoint: str, data: dict = None):
"""请求日志"""
self._log(f"🚀 {method} {endpoint}")
if self.verbose and data:
self._log(f"📤 请求数据: {json.dumps(data, ensure_ascii=False, indent=2)}")
def _setup_credentials(self):
"""配置向导"""
config_file = Path.home() / ".minimax_ai" / "config.json"
config_file.parent.mkdir(exist_ok=True)
if config_file.exists():
try:
with open(config_file) as f:
config = json.load(f)
self.group_id = config.get("group_id")
self.api_key = config.get("api_key")
if self.group_id and self.api_key:
return
except Exception:
pass
print("⚠️ 需要配置API密钥")
group_id = input("请输入Group ID: ").strip()
api_key = input("请输入API Key: ").strip()
if not group_id or not api_key:
print("❌ Group ID和API Key不能为空")
sys.exit(1)
with open(config_file, "w") as f:
json.dump({"group_id": group_id, "api_key": api_key}, f, indent=2)
print(f"✅ 配置已保存到 {config_file}")
print("请重新运行程序")
sys.exit(0)
def _request(self, method: str, endpoint: str, **kwargs) -> Dict[str, Any]:
"""统一请求"""
# 检测是否是 Anthropic API 端点
if endpoint.startswith("v1/messages"):
url = f"https://api.minimaxi.com/anthropic/{endpoint}"
else:
url = f"{self.base_url}/{endpoint}"
if any(k in endpoint for k in ["t2a_v2", "voice_clone", "music_generation"]):
url += f"?GroupId={self.group_id}"
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
}
self._log_request(method, endpoint, kwargs.get("json"))
for attempt in range(3):
try:
response = requests.request(method, url, headers=headers, **kwargs)
response.raise_for_status()
result = response.json()
self._log(f"📥 响应状态: {response.status_code}")
# Anthropic API 响应格式不同,不需要检查 base_resp
if "base_resp" in result and result["base_resp"]["status_code"] != 0:
self._log(
f"⚠️ API错误: {result['base_resp']['status_msg']}", "ERROR"
)
if result["base_resp"]["status_code"] == 1002 and attempt < 2:
time.sleep(2 * (attempt + 1))
continue
raise Exception(f"API错误: {result['base_resp']['status_msg']}")
self._log(f"✅ 请求成功")
return result
except Exception as e:
if attempt == 2:
self._log(f"❌ 请求失败: {e}", "ERROR")
raise # 抛出异常而不是退出,让上层处理
self._log(f"🔄 重试第{attempt + 1}次...", "WARN")
time.sleep(1)
def chat(
self,
message: str,
model: str = "MiniMax-M2.7",
system_prompt: str = None,
# M2-her 专属参数(暂时注释,等待 API BUG 修复)
# user_system: str = None, group: str = None,
# sample_user: str = None, sample_ai: str = None,
temperature: float = 1.0,
top_p: float = 1.0,
max_tokens: int = 2048,
stream: bool = False,
use_anthropic_api: bool = False,
show_thinking: bool = False,
) -> str:
"""智能对话(支持 M2-her 和 Anthropic API 兼容接口)
Args:
message: 用户消息内容
model: 模型名称,可选值:M2-her, MiniMax-M2.7, MiniMax-M2.7-highspeed, MiniMax-M2.5, MiniMax-M2.5-highspeed, MiniMax-M2.1, MiniMax-M2.1-highspeed, MiniMax-M2
system_prompt: 系统提示词(定义 AI 的角色和行为)
# M2-her 专属参数(暂时注释)
# user_system: 用户角色设定(用于角色扮演场景定义用户身份)
# group: 对话分组名称(标识对话场景)
# sample_user: 示例用户消息(引导模型理解期望的对话风格)
# sample_ai: 示例 AI 回复(配合 sample_user 使用)
temperature: 温度参数 (0.0, 1.0],推荐 1.0
top_p: 核采样参数 (0.0, 1.0],推荐 1.0
max_tokens: 最大生成 token 数,M2-her 上限为 2048
stream: 是否使用流式响应
use_anthropic_api: 是否使用 Anthropic API 兼容接口
show_thinking: 是否显示思考过程(仅 Anthropic API 支持)
Returns:
模型响应文本,如果 show_thinking=True 则返回包含思考过程的字典
"""
# 模型映射:M2-her 为对话模型,MiniMax-M2 系列为文本生成模型
model_mapping = {
"MiniMax-M2.7": "MiniMax-M2.7",
"MiniMax-M2.7-highspeed": "MiniMax-M2.7-highspeed",
"MiniMax-M2.5": "MiniMax-M2.5",
"MiniMax-M2.5-highspeed": "MiniMax-M2.5-highspeed",
"MiniMax-M2.1": "MiniMax-M2.1",
"MiniMax-M2.1-highspeed": "MiniMax-M2.1-highspeed",
"MiniMax-M2.1-lightning": "MiniMax-M2.7-highspeed", # 兼容旧名称,映射到最新高速版
"MiniMax-M2": "MiniMax-M2",
"M2-her": "M2-her",
}
model = model_mapping.get(model, model)
# 选择 API 端点
if use_anthropic_api:
endpoint = "v1/messages"
base_url = "https://api.minimaxi.com/anthropic"
self._log(f"🤖 使用 Anthropic API 兼容接口 (模型: {model})")
else:
endpoint = "text/chatcompletion_v2"
base_url = self.base_url
self._log(f"🤖 使用标准 MiniMax API (模型: {model})")
# 构建请求数据
if use_anthropic_api:
# Anthropic API 格式
messages = [
{"role": "user", "content": [{"type": "text", "text": message}]}
]
data = {"model": model, "messages": messages, "max_tokens": max_tokens}
if system_prompt:
data["system"] = system_prompt
if temperature is not None:
if temperature <= 0 or temperature > 1:
raise ValueError(
f"temperature 必须在 (0.0, 1.0] 范围内,当前为 {temperature}"
)
data["temperature"] = temperature
if stream:
data["stream"] = True
else:
# 标准 MiniMax API 格式
messages = []
# M2-her 支持高级角色类型
if model == "M2-her":
# system: 定义 AI 角色
if system_prompt:
messages.append({"role": "system", "content": system_prompt})
# user_system, group, sample_user, sample_ai 已暂时注释,等待 API BUG 修复
# if user_system:
# messages.append({"role": "user_system", "content": user_system})
# if group:
# messages.append({"role": "group", "content": group})
# if sample_user:
# messages.append({"role": "sample_message_user", "content": sample_user})
# if sample_ai:
# messages.append({"role": "sample_message_ai", "content": sample_ai})
# user: 用户消息
messages.append({"role": "user", "content": message})
# 构建请求数据
data = {"model": model, "messages": messages}
# M2-her 参数验证
if max_tokens > 2048:
self._log(f"⚠️ max_tokens 超过 M2-her 上限 2048,已调整为 2048")
max_tokens = 2048
else:
# 原有模型格式(MiniMax-M2 系列)
messages = [{"role": "user", "content": message}]
data = {"model": model, "messages": messages, "max_tokens": max_tokens}
if system_prompt:
# 标准 API 将 system prompt 作为第一条消息
messages.insert(0, {"role": "system", "content": system_prompt})
# 通用参数
if temperature is not None:
data["temperature"] = temperature
if top_p is not None:
data["top_p"] = top_p
if stream:
data["stream"] = True
# 发送请求
if use_anthropic_api:
# 使用自定义 base_url
original_base_url = self.base_url
self.base_url = base_url
try:
response = self._request("POST", endpoint, json=data)
finally:
self.base_url = original_base_url
else:
response = self._request("POST", endpoint, json=data)
# 解析响应
if use_anthropic_api:
return self._parse_anthropic_response(response, show_thinking)
else:
# 检查响应是否包含 choices
if "choices" not in response or response["choices"] is None:
self._log(f"❌ API 响应异常: {response}")
raise ValueError(f"API 响应格式异常: {response}")
content = response["choices"][0]["message"]["content"]
self._log(f"📄 生成内容长度: {len(content)} 字符")
return content
def _parse_anthropic_response(
self, response: dict, show_thinking: bool = False
) -> str | dict:
"""解析 Anthropic API 格式的响应
Args:
response: API 响应数据
show_thinking: 是否显示思考过程
Returns:
文本内容或包含思考过程的字典
"""
# Anthropic API 格式:response.content 是一个列表
if "content" not in response:
raise ValueError("无效的 API 响应格式:缺少 content 字段")
content_blocks = response["content"]
thinking_text = ""
response_text = ""
for block in content_blocks:
if block.get("type") == "thinking":
thinking_text = block.get("thinking", "")
elif block.get("type") == "text":
response_text = block.get("text", "")
if show_thinking:
return {
"thinking": thinking_text,
"content": response_text,
"full_response": content_blocks,
}
else:
self._log(f"📄 生成内容长度: {len(response_text)} 字符")
return response_text
def chat_stream(
self,
messages: list,
model: str = "MiniMax-M2.7",
system_prompt: str = None,
temperature: float = 1.0,
max_tokens: int = 2048,
use_anthropic_api: bool = True,
show_thinking: bool = False,
):
"""流式对话生成器
Args:
messages: 消息列表
model: 模型名称
system_prompt: 系统提示词
temperature: 温度参数
max_tokens: 最大生成token数
use_anthropic_api: 是否使用Anthropic API兼容接口
show_thinking: 是否显示思考过程
Yields:
dict: {"type": "thinking"|"text", "content": str}
"""
from typing import Generator
model_mapping = {
"MiniMax-M2.7": "MiniMax-M2.7",
"MiniMax-M2.7-highspeed": "MiniMax-M2.7-highspeed",
"MiniMax-M2.5": "MiniMax-M2.5",
"MiniMax-M2.5-highspeed": "MiniMax-M2.5-highspeed",
"MiniMax-M2.1": "MiniMax-M2.1",
"MiniMax-M2.1-highspeed": "MiniMax-M2.1-highspeed",
"MiniMax-M2.1-lightning": "MiniMax-M2.7-highspeed",
"MiniMax-M2": "MiniMax-M2",
"M2-her": "M2-her",
}
model = model_mapping.get(model, model)
if use_anthropic_api:
endpoint = "v1/messages"
base_url = "https://api.minimaxi.com/anthropic"
self._log(f"🤖 流式对话 (Anthropic API, 模型: {model})")
anthropic_messages = []
for m in messages:
if m.get("role") == "system":
continue
content = m.get("content", "")
if isinstance(content, str):
anthropic_messages.append(
{
"role": m["role"],
"content": [{"type": "text", "text": content}],
}
)
elif isinstance(content, list):
anthropic_messages.append({"role": m["role"], "content": content})
data = {
"model": model,
"messages": anthropic_messages,
"max_tokens": max_tokens,
"stream": True,
}
if system_prompt:
data["system"] = system_prompt
if temperature is not None and 0 < temperature <= 1:
data["temperature"] = temperature
url = f"{base_url}/{endpoint}"
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
}
self._log(f"🚀 开始流式请求...")
response = requests.post(
url, headers=headers, json=data, stream=True, timeout=120
)
if response.status_code != 200:
error_msg = f"HTTP {response.status_code}"
try:
error_data = response.json()
error_msg = error_data.get("error", {}).get("message", error_msg)
except:
pass
yield {"type": "error", "content": error_msg}
return
reasoning_buffer = ""
text_buffer = ""
for line in response.iter_lines():
if not line:
continue
line = line.decode("utf-8")
if line.startswith("data: "):
try:
chunk_data = json.loads(line[6:])
if chunk_data.get("type") == "content_block_start":
pass
elif chunk_data.get("type") == "content_block_delta":
delta = chunk_data.get("delta", {})
if delta.get("type") == "thinking_delta":
thinking_text = delta.get("thinking", "")
if thinking_text:
reasoning_buffer += thinking_text
if show_thinking:
yield {
"type": "thinking",
"content": thinking_text,
}
elif delta.get("type") == "text_delta":
text_content = delta.get("text", "")
if text_content:
text_buffer += text_content
yield {"type": "text", "content": text_content}
elif chunk_data.get("type") == "message_stop":
pass
except json.JSONDecodeError:
continue
self._log(f"📄 流式完成: {len(text_buffer)} 字符")
else:
endpoint = "text/chatcompletion_v2"
self._log(f"🤖 流式对话 (标准API, 模型: {model})")
data = {
"model": model,
"messages": messages,
"max_tokens": max_tokens,
"stream": True,
}
if system_prompt:
data["system_prompt"] = system_prompt
if temperature is not None:
data["temperature"] = temperature
url = f"{self.base_url}/{endpoint}"
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
}
response = requests.post(
url, headers=headers, json=data, stream=True, timeout=120
)
if response.status_code != 200:
error_msg = f"HTTP {response.status_code}"
try:
error_data = response.json()
error_msg = error_data.get("base_resp", {}).get(
"status_msg", error_msg
)
except:
pass
yield {"type": "error", "content": error_msg}
return
text_buffer = ""
for line in response.iter_lines():
if not line:
continue
line = line.decode("utf-8")
if line.startswith("data: "):
try:
chunk_data = json.loads(line[6:])
if chunk_data.get("choices"):
delta = chunk_data["choices"][0].get("delta", {})
content = delta.get("content", "")
if content:
text_buffer += content
yield {"type": "text", "content": content}
except json.JSONDecodeError:
continue
self._log(f"📄 流式完成: {len(text_buffer)} 字符")
def image(
self,
prompt: str,
model: str = "image-01",
n: int = 1,
aspect_ratio: str = "1:1",
width: int = None,
height: int = None,
seed: int = None,
response_format: str = "url",
prompt_optimizer: bool = False,
aigc_watermark: bool = False,
style_type: str = None,
style_weight: float = 0.8,
reference_image: str = None,
) -> list:
"""图像生成(文生图/图生图)
Args:
prompt: 图像的文本描述,最长1500字符
model: 模型名称,可选值:image-01, image-01-live
n: 单次请求生成的图片数量,取值范围[1, 9],默认为1
aspect_ratio: 图像宽高比,默认为1:1,可选值:1:1, 16:9, 4:3, 3:2, 2:3, 3:4, 9:16, 21:9
width: 生成图片的宽度(像素),仅当model为image-01时生效,取值范围[512, 2048],且必须是8的倍数
height: 生成图片的高度(像素),仅当model为image-01时生效,取值范围[512, 2048],且必须是8的倍数
seed: 随机种子,用于复现结果
response_format: 返回图片的形式,默认为url,可选值:url, base64
prompt_optimizer: 是否开启prompt自动优化,默认为False
aigc_watermark: 是否在生成的图片中添加水印,默认为False
style_type: 画风风格类型,仅当model为image-01-live时生效,可选值:漫画, 元气, 中世纪, 水彩
style_weight: 画风权重,取值范围(0, 1],默认0.8
reference_image: 参考图片路径或URL,用于图生图(仅支持人像character类型)
Returns:
图片URL列表或Base64编码列表
"""
# 检测生成模式
if reference_image:
self._log(f"🎨 开始图生图...")
generation_mode = "图生图"
else:
self._log(f"🎨 开始文生图...")
generation_mode = "文生图"
# 参数验证
if len(prompt) > 1500:
raise ValueError(f"图像描述过长,最多支持1500字符,当前{len(prompt)}字符")
if n < 1 or n > 9:
raise ValueError(f"图片数量必须在1-9之间,当前为{n}")
# width和height必须同时设置
if (width is not None) != (height is not None):
raise ValueError("width和height必须同时设置")
if width is not None:
if width < 512 or width > 2048 or width % 8 != 0:
raise ValueError(f"width必须在512-2048之间且为8的倍数,当前为{width}")
if height < 512 or height > 2048 or height % 8 != 0:
raise ValueError(f"height必须在512-2048之间且为8的倍数,当前为{height}")
if model != "image-01":
raise ValueError("width和height参数仅当model为image-01时生效")
if style_type and model != "image-01-live":
raise ValueError("style_type参数仅当model为image-01-live时生效")
data = {
"model": model,
"prompt": prompt,
"response_format": response_format,
"n": n,
"prompt_optimizer": prompt_optimizer,
}
# 图生图专用参数
if reference_image:
# 处理参考图片
processed_ref_image = self._process_image_input(reference_image)
data["subject_reference"] = [
{"type": "character", "image_file": processed_ref_image}
]
self._log(f"📷 参考图片: {reference_image}")
# 优先使用aspect_ratio,如果设置了width和height则使用它们
if width is not None and height is not None:
data["width"] = width
data["height"] = height
else:
data["aspect_ratio"] = aspect_ratio
# 可选参数
if seed is not None:
data["seed"] = seed
if aigc_watermark:
data["aigc_watermark"] = True
# 风格设置(仅对image-01-live生效)
if style_type:
data["style"] = {"style_type": style_type, "style_weight": style_weight}
self._log(f"📋 使用模型: {model}")
self._log(f"🎭 图片数量: {n}")
self._log(
f"📐 尺寸设置: {width}x{height}" if width else f"📐 宽高比: {aspect_ratio}"
)
if style_type:
self._log(f"🎨 风格设置: {style_type} (权重: {style_weight})")
response = self._request("POST", "image_generation", json=data)
# 根据response_format返回不同格式的数据
if response_format == "url":
result = response.get("data", {}).get("image_urls", [])
else:
result = response.get("data", {}).get("image_base64", [])
# 显示生成统计
metadata = response.get("metadata", {})
success_count = int(metadata.get("success_count", len(result)))
failed_count = int(metadata.get("failed_count", 0))
self._log(f"📸 {generation_mode}成功生成: {success_count} 张")
if failed_count > 0:
self._log(f"⚠️ 内容安全拦截: {failed_count} 张")
return result
def video(
self,
prompt: str,
model: str = "MiniMax-Hailuo-2.3",
duration: int = 6,
resolution: str = None,
prompt_optimizer: bool = True,
fast_pretreatment: bool = False,
aigc_watermark: bool = False,
callback_url: str = None,
) -> str:
"""视频生成 - 支持镜头控制和高级参数
Args:
prompt: 视频文本描述(最多2000字符),支持运镜指令如[推进]、[左移]等
model: 视频生成模型
- MiniMax-Hailuo-2.3: 最新模型,支持运镜控制
- MiniMax-Hailuo-02: 经典模型,支持运镜控制
- T2V-01-Director: 导演版,支持运镜控制
- T2V-01: 基础模型
duration: 视频时长(秒),根据模型和分辨率不同有不同限制
resolution: 视频分辨率 [720P, 768P, 1080P]
prompt_optimizer: 是否自动优化prompt,默认True
fast_pretreatment: 是否缩短prompt优化耗时,仅对Hailuo模型生效
aigc_watermark: 是否添加水印,默认False
callback_url: 回调URL用于接收任务状态通知
Returns:
task_id: 视频生成任务ID
"""
self._log(f"🎬 开始生成视频...")
self._log(f"📋 使用模型: {model}")
# 智能选择默认分辨率
if resolution is None:
if model in [
"T2V-01-Director",
"T2V-01",
"I2V-01-Director",
"I2V-01-live",
"I2V-01",
]:
resolution = "720P"
elif model in ["MiniMax-Hailuo-2.3", "MiniMax-Hailuo-02"]:
resolution = "768P" # Hailuo系列默认768P以获得更好质量
else:
resolution = "720P"
self._log(f"🎯 自动选择分辨率: {resolution}")
# 参数验证
if len(prompt) > 2000:
raise ValueError("Prompt长度不能超过2000字符")
# 验证时长和分辨率的组合是否有效
valid_combinations = self._get_valid_duration_resolution(model)
if (duration, resolution) not in valid_combinations:
self._log(f"⚠️ 警告: 时长{duration}s和分辨率{resolution}组合可能不被支持")
self._log(f"💡 建议组合: {valid_combinations[:3]}")
# 检测运镜指令
camera_moves = self._detect_camera_moves(prompt)
if camera_moves:
self._log(f"🎥 检测到运镜指令: {', '.join(camera_moves)}")
data = {
"prompt": prompt,
"model": model,
"duration": duration,
"resolution": resolution,
"prompt_optimizer": prompt_optimizer,
"aigc_watermark": aigc_watermark,
}
# 添加可选参数
if fast_pretreatment and model in ["MiniMax-Hailuo-2.3", "MiniMax-Hailuo-02"]:
data["fast_pretreatment"] = fast_pretreatment
self._log("⚡ 启用快速预处理")
if callback_url:
data["callback_url"] = callback_url
self._log(f"📞 设置回调URL: {callback_url}")
response = self._request("POST", "video_generation", json=data)
task_id = response.get("task_id", "")
self._log(f"🎯 视频任务ID: {task_id}")
return task_id
def _get_valid_duration_resolution(self, model: str) -> list:
"""获取模型支持的时长和分辨率组合(根据官方API文档)
注意:不同模型在T2V(文生视频)和I2V(图生视频)中的支持度可能不同
"""
combinations = {
# Hailuo 系列(支持 T2V 和 I2V)
"MiniMax-Hailuo-2.3": [(6, "768P"), (10, "768P"), (6, "1080P")],
"MiniMax-Hailuo-2.3-Fast": [
(6, "768P"),
(10, "768P"),
(6, "1080P"),
], # 仅 I2V
"MiniMax-Hailuo-02": [
(6, "512P"),
(6, "768P"),
(10, "768P"),
(6, "1080P"),
], # I2V 支持 512P
# T2V 专用模型
"T2V-01-Director": [(6, "720P")],
"T2V-01": [(6, "720P")],
# I2V 专用模型
"I2V-01-Director": [(6, "720P")],
"I2V-01-live": [(6, "720P")],
"I2V-01": [(6, "720P")],
}
return combinations.get(model, [(6, "720P")])
def _detect_camera_moves(self, prompt: str) -> list:
"""检测prompt中的运镜指令"""
camera_moves = [
"[左移]",
"[右移]",
"[左摇]",
"[右摇]",
"[推进]",
"[拉远]",
"[上升]",
"[下降]",
"[上摇]",
"[下摇]",
"[变焦推近]",
"[变焦拉远]",
"[晃动]",
"[跟随]",
"[固定]",
]
detected = []
for move in camera_moves:
if move in prompt:
detected.append(move.strip("[]"))
return detected
def _process_image_input(self, image_input: str) -> str:
"""处理图片输入,支持本地路径和URL,转换为Base64或验证URL
Args:
image_input: 图片路径、URL或Base64 Data URL
Returns:
str: 处理后的图片URL或Base64 Data URL
"""
# 如果已经是Data URL格式,直接返回
if image_input.startswith("data:image/"):
return image_input
# 如果是URL,进行简单验证
if image_input.startswith(("http://", "https://")):
self._log(f"🌐 使用图片URL: {image_input}")
return image_input
# 处理本地文件
try:
image_path = Path(image_input)
if not image_path.exists():
raise FileNotFoundError(f"图片文件不存在: {image_path}")
# 检查文件大小 (统一20MB限制,API会根据用途自行验证)
file_size = image_path.stat().st_size
if file_size > 20 * 1024 * 1024: # 20MB
raise ValueError(
f"图片文件过大: {file_size / 1024 / 1024:.1f}MB (限制: 20MB,图生图建议10MB以内)"
)
# 检查文件格式
mime_type, _ = mimetypes.guess_type(str(image_path))
if mime_type not in ["image/jpeg", "image/jpg", "image/png", "image/webp"]:
raise ValueError(f"不支持的图片格式: {mime_type}")
# 读取并编码为Base64
with open(image_path, "rb") as f:
image_data = f.read()
base64_data = base64.b64encode(image_data).decode("utf-8")
data_url = f"data:{mime_type};base64,{base64_data}"
self._log(
f"📷 图片已编码: {image_path.name} ({len(image_data) / 1024:.1f}KB)"
)
return data_url
except Exception as e:
self._log(f"❌ 图片处理失败: {e}", "ERROR")
raise
def image_to_video(
self,
first_frame_image: str,
prompt: str = "",
model: str = "I2V-01",
duration: int = 6,
resolution: str = None,
prompt_optimizer: bool = True,
fast_pretreatment: bool = False,
aigc_watermark: bool = False,
callback_url: str = None,
) -> str:
"""图生视频 - 将静态图片转换为动态视频
Args:
first_frame_image: 首帧图片(路径、URL或Base64 Data URL)
prompt: 视频描述文本(最多2000字符),支持运镜指令
model: 图生视频模型
- I2V-01-Director: 导演版,支持运镜控制
- I2V-01-live: 卡通/漫画风格增强
- I2V-01: 基础图生视频模型
- MiniMax-Hailuo-2.3/2.3-Fast/02: 也支持图生视频
duration: 视频时长(秒)
resolution: 视频分辨率,None为自动选择
prompt_optimizer: 是否自动优化prompt
fast_pretreatment: 快速预处理(仅Hailuo模型)
aigc_watermark: 是否添加水印
callback_url: 回调URL
Returns:
task_id: 视频生成任务ID
"""
self._log(f"🎬 开始图生视频...")
self._log(f"📋 使用模型: {model}")
# 处理图片输入
processed_image = self._process_image_input(first_frame_image)
# 智能选择默认分辨率
if resolution is None:
if model in ["I2V-01-Director", "I2V-01-live", "I2V-01"]:
resolution = "720P"
elif model in [
"MiniMax-Hailuo-2.3",
"MiniMax-Hailuo-2.3-Fast",
"MiniMax-Hailuo-02",
]:
resolution = "768P" # Hailuo系列默认768P以获得更好质量
else:
resolution = "720P"
self._log(f"🎯 自动选择分辨率: {resolution}")
# 验证参数
if prompt and len(prompt) > 2000:
raise ValueError("Prompt长度不能超过2000字符")
# 验证时长和分辨率组合
valid_combinations = self._get_valid_duration_resolution(model)
if (duration, resolution) not in valid_combinations:
self._log(f"⚠️ 警告: 时长{duration}s和分辨率{resolution}组合可能不被支持")
self._log(f"💡 建议组合: {valid_combinations[:3]}")
# 检测运镜指令
if prompt:
camera_moves = self._detect_camera_moves(prompt)
if camera_moves:
self._log(f"🎥 检测到运镜指令: {', '.join(camera_moves)}")
# 构建请求数据
data = {
"model": model,
"first_frame_image": processed_image,
"duration": duration,
"resolution": resolution,
"prompt_optimizer": prompt_optimizer,
"aigc_watermark": aigc_watermark,
}
# 添加可选参数
if prompt:
data["prompt"] = prompt
if fast_pretreatment and model in [
"MiniMax-Hailuo-2.3",
"MiniMax-Hailuo-2.3-Fast",
"MiniMax-Hailuo-02",
]:
data["fast_pretreatment"] = fast_pretreatment
self._log("⚡ 启用快速预处理")
if callback_url:
data["callback_url"] = callback_url
self._log(f"📞 设置回调URL: {callback_url}")
response = self._request("POST", "video_generation", json=data)
task_id = response.get("task_id", "")
self._log(f"🎯 图生视频任务ID: {task_id}")
return task_id
def start_end_to_video(
self,
first_frame_image: str,
last_frame_image: str,
prompt: str = "",
duration: int = 6,
resolution: str = None,
prompt_optimizer: bool = True,
aigc_watermark: bool = False,
callback_url: str = None,
) -> str:
"""首尾帧生成视频 - 在指定首尾帧之间生成过渡视频
Args:
first_frame_image: 起始帧图片(路径、URL或Base64 Data URL)
last_frame_image: 结束帧图片(路径、URL或Base64 Data URL)
prompt: 视频过渡描述文本(最多2000字符),支持运镜指令
duration: 视频时长(秒),6或10秒
resolution: 视频分辨率,768P或1080P
prompt_optimizer: 是否自动优化prompt
aigc_watermark: 是否添加水印
callback_url: 回调URL
Returns:
task_id: 视频生成任务ID
"""
self._log(f"🎬 开始首尾帧视频生成...")
self._log(f"📋 使用模型: MiniMax-Hailuo-02 (首尾帧专用)")
# 处理图片输入
processed_first_frame = self._process_image_input(first_frame_image)
processed_last_frame = self._process_image_input(last_frame_image)
# 智能选择默认分辨率(首尾帧仅支持768P和1080P)
if resolution is None:
resolution = "768P" # 默认使用768P以获得更好质量
self._log(f"🎯 自动选择分辨率: {resolution}")
# 验证分辨率限制
if resolution not in ["768P", "1080P"]:
raise ValueError("首尾帧视频生成仅支持768P和1080P分辨率")
# 验证时长和分辨率组合
if resolution == "1080P" and duration != 6:
raise ValueError("1080P分辨率仅支持6秒时长")
if duration not in [6, 10]:
raise ValueError("首尾帧视频生成仅支持6秒或10秒时长")
# 验证参数
if prompt and len(prompt) > 2000:
raise ValueError("Prompt长度不能超过2000字符")
# 检测运镜指令
if prompt:
camera_moves = self._detect_camera_moves(prompt)
if camera_moves:
self._log(f"🎥 检测到运镜指令: {', '.join(camera_moves)}")
# 构建请求数据
data = {
"model": "MiniMax-Hailuo-02",
"first_frame_image": processed_first_frame,
"last_frame_image": processed_last_frame,
"duration": duration,
"resolution": resolution,
"prompt_optimizer": prompt_optimizer,
"aigc_watermark": aigc_watermark,
}
# 添加可选参数
if prompt:
data["prompt"] = prompt
if callback_url:
data["callback_url"] = callback_url
self._log(f"📞 设置回调URL: {callback_url}")
response = self._request("POST", "video_generation", json=data)
task_id = response.get("task_id", "")
self._log(f"🎯 首尾帧视频任务ID: {task_id}")
# 显示关键信息
self._log(f"📐 分辨率: {resolution}")
self._log(f"⏱️ 时长: {duration}秒")
self._log(f"🖼️ 首尾帧尺寸将根据首帧自动调整")