File size: 37,424 Bytes
3a72608 8b87e10 3a72608 b08c3df 3a72608 b08c3df 3a72608 b08c3df 3a72608 b08c3df 3a72608 8b87e10 3a72608 8b87e10 3a72608 8b87e10 3a72608 | 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 | from __future__ import annotations
import json
import os
import re
import tempfile
import time
from typing import Any
import requests
from fastapi import HTTPException, UploadFile
from .config import get_settings
from .constants import (
CREATE_TASK_URL,
ENDPOINT_FAST,
ENDPOINT_LEGACY,
ENDPOINT_PRO,
GET_TASK_URL,
IMAGE_GEN_URL,
IMAGE_MODEL_CONFIG,
IMAGE_UPLOAD_URL,
LIST_IMAGE_RECORDS_URL,
LIST_VIDEO_TASKS_URL,
MODEL_MODE_BOTH,
MODEL_MODE_EXPIRED,
MODEL_MODE_FAST_ONLY,
MODEL_MODE_IMAGE_ENABLED,
MODEL_MODE_IMAGE_ONLY,
MODEL_MODE_PRO_ONLY,
UPLOAD_URL,
)
from .remote_engine import (
extract_status_phase,
extract_task_id,
is_quota_exhausted_error,
is_stop_rotation_error,
)
from .utils import (
clean_video_item,
extract_from_url,
extract_image_refs,
flatten_image_records,
get_mime_type,
has_audio_ref,
has_video_ref,
image_resolution_config,
normalize_url,
probe_duration_ffprobe,
replace_reference_prompt,
validate_reference_inputs,
)
VIDEO_MAX_SECONDS = 15
IMAGE_EXHAUSTED_KEYWORDS = [
"剩余额度不足",
"额度不足",
"insufficient",
"quota",
"exceed",
"balance",
"rate limit",
]
def is_image_exhausted_signal(*parts: Any) -> bool:
combined = " ".join(str(part or "") for part in parts).lower()
return any(keyword.lower() in combined for keyword in IMAGE_EXHAUSTED_KEYWORDS)
class ByteplusClient:
def __init__(self) -> None:
self.settings = get_settings()
self.session = requests.Session()
def _proxies(self, proxy: str | None) -> dict[str, str] | None:
if proxy and proxy.strip():
proxy = proxy.strip()
return {"http": proxy, "https": proxy}
return None
def _headers(self, cookie: str, csrf_token: str) -> dict[str, str]:
return {
"Accept": "application/json, text/plain, */*",
"Accept-Language": "en-US,en;q=0.9",
"Connection": "keep-alive",
"Origin": "https://console.byteplus.com",
"Referer": "https://console.byteplus.com/",
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36"
),
"X-Csrf-Token": csrf_token,
"Cookie": cookie,
}
def _raise_request_error(self, exc: Exception, url: str, proxy: str | None) -> None:
host = url.split('/')[2] if '://' in url else url
proxy_hint = " via proxy" if proxy else ""
if isinstance(exc, requests.exceptions.ProxyError):
detail = str(exc)
if "407" in detail:
raise HTTPException(
status_code=400,
detail="Proxy gagal dipakai: 407 Proxy Authentication Required. Periksa username/password proxy Anda.",
) from exc
raise HTTPException(
status_code=400,
detail=f"Proxy error{proxy_hint} saat menghubungi {host}: {detail}",
) from exc
if isinstance(exc, requests.exceptions.ConnectTimeout):
raise HTTPException(
status_code=504,
detail=f"Koneksi timeout{proxy_hint} saat menghubungi {host}. Coba ganti proxy atau ulangi lagi.",
) from exc
if isinstance(exc, requests.exceptions.ReadTimeout):
raise HTTPException(
status_code=504,
detail=f"Server BytePlus terlalu lama merespons{proxy_hint}. Coba ulangi lagi.",
) from exc
if isinstance(exc, requests.exceptions.ConnectionError):
raise HTTPException(
status_code=502,
detail=f"Koneksi ke {host} gagal{proxy_hint}: {str(exc)}",
) from exc
if isinstance(exc, requests.exceptions.RequestException):
raise HTTPException(
status_code=502,
detail=f"Request ke {host} gagal{proxy_hint}: {str(exc)}",
) from exc
raise HTTPException(status_code=500, detail=f"Error internal request: {type(exc).__name__}: {str(exc)}") from exc
def _request(
self,
method: str,
url: str,
*,
cookie: str,
csrf_token: str,
proxy: str | None,
timeout: tuple[int, int] | None = None,
**kwargs,
) -> requests.Response:
headers = kwargs.pop("headers", {})
merged_headers = self._headers(cookie, csrf_token)
merged_headers.update(headers)
try:
return self.session.request(
method=method.upper(),
url=url,
headers=merged_headers,
proxies=self._proxies(proxy),
timeout=timeout or self.settings.byteplus_timeout,
**kwargs,
)
except Exception as exc:
self._raise_request_error(exc, url, proxy)
def validate_credentials(self, cookie: str, csrf_token: str, proxy: str) -> dict[str, Any]:
if not cookie.strip() or not csrf_token.strip() or not proxy.strip():
raise HTTPException(status_code=400, detail="Cookie, CSRF token, dan proxy wajib diisi.")
payload = {
"Name": "seedance-1-0-pro",
"Prompt": "a simple landscape",
"TaskType": "BasicMode",
"VideoTaskType": "text_to_video",
"ModelName": "seed-2-0-code",
"ModelVersion": "260128",
"Ratio": "16:9",
"Resolution": "480p",
"GroupId": f"credtest-{int(time.time() * 1000)}",
"Duration": 2,
"Seed": -1,
"EndpointID": "seedance-1-0-pro-250528",
"Watermark": False,
"GenerationTimeout": 48,
"GenerateAudio": False,
"DurationMode": "duration",
"Draft": False,
}
resp = self._request(
"POST",
CREATE_TASK_URL,
cookie=cookie,
csrf_token=csrf_token,
proxy=proxy,
json=payload,
headers={"Content-Type": "application/json"},
timeout=(20, 40),
)
try:
body = resp.json()
except Exception:
body = {"raw": resp.text[:500]}
if resp.status_code in (401, 403):
raise HTTPException(status_code=400, detail="Cookie/CSRF tidak valid atau sudah expired.")
if resp.status_code != 200:
raise HTTPException(status_code=400, detail=f"Proxy atau akun BytePlus menolak request (HTTP {resp.status_code}).")
if is_stop_rotation_error(body):
raise HTTPException(status_code=400, detail="Request test diblokir server BytePlus.")
task_id = extract_task_id(body)
if not task_id:
if is_quota_exhausted_error(body):
raise HTTPException(status_code=400, detail="Quota akun BytePlus habis. Ganti akun/cookie baru.")
raise HTTPException(status_code=400, detail="Credential belum valid untuk generate task di BytePlus.")
return {"ok": True, "task_id": task_id}
def _upload_content(
self,
filename: str,
content: bytes,
*,
cookie: str,
csrf_token: str,
proxy: str | None,
extra_form: dict[str, Any] | None = None,
upload_url: str = UPLOAD_URL,
) -> dict[str, Any]:
if not content:
raise HTTPException(status_code=400, detail=f"File {filename} kosong.")
form_data = {"biz": "experience_video", "security": "true"}
if extra_form:
form_data.update(extra_form)
files_payload = {"file": (filename, content, get_mime_type(filename))}
resp = self._request(
"POST",
upload_url,
cookie=cookie,
csrf_token=csrf_token,
proxy=proxy,
data=form_data,
files=files_payload,
)
if resp.status_code != 200:
raise HTTPException(status_code=502, detail=f"Upload ke BytePlus gagal (HTTP {resp.status_code}).")
data = resp.json()
result = data.get("Result") or {}
url = result.get("Url") or result.get("url") or result.get("URL") or ""
bucket, object_key_from_url = extract_from_url(url)
bucket = result.get("Bucket") or result.get("BucketName") or bucket
prefix = result.get("Prefix") or result.get("ObjectKey") or object_key_from_url
if not url:
raise HTTPException(status_code=502, detail="Upload berhasil tetapi URL file tidak ditemukan.")
return {
"BucketName": bucket,
"ObjectKey": prefix,
"Url": url,
"Bucket": bucket,
"Prefix": prefix,
}
async def upload_file(
self,
file: UploadFile,
*,
cookie: str,
csrf_token: str,
proxy: str | None,
extra_form: dict[str, Any] | None = None,
) -> dict[str, Any]:
content = await file.read()
return self._upload_content(
file.filename or "upload.bin",
content,
cookie=cookie,
csrf_token=csrf_token,
proxy=proxy,
extra_form=extra_form,
)
def _create_video_payload(
self,
*,
generation_mode: str,
prompt: str,
duration: int,
resolution: str,
ratio: str,
generate_audio: bool,
endpoint_id: str,
first_frame: dict[str, Any] | None = None,
last_frame: dict[str, Any] | None = None,
) -> dict[str, Any]:
if generation_mode == "text_to_video":
video_task_type = "text_to_video"
elif last_frame:
video_task_type = "first_last_frame"
else:
video_task_type = "first_frame"
payload: dict[str, Any] = {
"Name": "dreamina-seedance-2-0-fast",
"Prompt": prompt,
"TaskType": "BasicMode",
"VideoTaskType": video_task_type,
"ModelName": endpoint_id,
"ModelVersion": "260128",
"Ratio": ratio,
"Resolution": resolution,
"GroupId": f"orbitbot-{int(time.time() * 1000)}",
"Duration": int(duration),
"Seed": -1,
"EndpointID": endpoint_id,
"Watermark": False,
"GenerationTimeout": 48,
"GenerateAudio": bool(generate_audio),
"DurationMode": "duration",
"Draft": False,
}
if generation_mode == "image_to_video" and first_frame:
payload["FirstFrameImageTosLocation"] = first_frame
if last_frame:
payload["LastFrameImageTosLocation"] = last_frame
return payload
def _create_reference_payload(
self,
*,
prompt: str,
rich_prompt: str,
duration: int,
resolution: str,
ratio: str,
generate_audio: bool,
endpoint_id: str,
reference_images: list[dict[str, Any]],
reference_videos: list[dict[str, Any]],
reference_audios: list[dict[str, Any]],
) -> dict[str, Any]:
payload: dict[str, Any] = {
"Name": "dreamina-seedance-2-0-fast",
"Prompt": prompt,
"TaskType": "BasicMode",
"VideoTaskType": "reference_media",
"ModelName": endpoint_id,
"ModelVersion": "260128",
"Ratio": ratio,
"Resolution": resolution,
"GroupId": f"orbitbot-ref-{int(time.time() * 1000)}",
"Duration": int(duration),
"Seed": -1,
"EndpointID": endpoint_id,
"Watermark": False,
"GenerationTimeout": 48,
"GenerateAudio": bool(generate_audio),
"DurationMode": "duration",
"RichTextTemplatePrompt": rich_prompt,
}
if reference_images:
payload["ReferenceImages"] = reference_images
if reference_videos:
payload["ReferenceVideos"] = reference_videos
if reference_audios:
payload["ReferenceAudios"] = reference_audios
return payload
def create_video_task_smart(
self,
*,
access_code: str,
cookie: str,
csrf_token: str,
proxy: str | None,
payload: dict[str, Any],
available_models: list[str],
store,
) -> dict[str, Any]:
if not available_models:
raise HTTPException(status_code=400, detail="Semua model sudah exhausted. Simpan credential baru untuk reset.")
newly_exhausted: list[str] = []
for model_name in available_models:
payload_try = dict(payload)
payload_try["ModelName"] = model_name
resp = self._request(
"POST",
CREATE_TASK_URL,
cookie=cookie,
csrf_token=csrf_token,
proxy=proxy,
headers={"Content-Type": "application/json"},
json=payload_try,
)
try:
body = resp.json()
except Exception:
body = {"raw": resp.text[:500]}
if resp.status_code == 200:
if is_stop_rotation_error(body):
raise HTTPException(
status_code=400,
detail="Konten diblokir server BytePlus. Ganti prompt atau media referensi.",
)
task_id = extract_task_id(body)
if task_id:
return {
"task_id": task_id,
"used_model": model_name,
"raw": body,
"newly_exhausted": newly_exhausted,
}
if is_quota_exhausted_error(body):
store.add_exhausted_model(access_code, model_name)
newly_exhausted.append(model_name)
continue
message = body.get("Message") or body.get("message") or "Task gagal dibuat tanpa pesan yang jelas dari BytePlus."
raise HTTPException(status_code=400, detail=str(message))
if is_quota_exhausted_error(body):
store.add_exhausted_model(access_code, model_name)
newly_exhausted.append(model_name)
continue
try:
message = body.get("Message") or body.get("message") or resp.text[:300]
except Exception:
message = f"HTTP {resp.status_code}"
raise HTTPException(status_code=400, detail=f"BytePlus menolak request: {message}")
raise HTTPException(status_code=502, detail="Semua model yang tersedia gagal membuat task video.")
def get_video_task(self, task_id: str, *, cookie: str, csrf_token: str, proxy: str | None) -> dict[str, Any]:
resp = self._request(
"POST",
GET_TASK_URL,
cookie=cookie,
csrf_token=csrf_token,
proxy=proxy,
headers={"Content-Type": "application/json"},
json={"Id": task_id},
timeout=(20, 60),
)
if resp.status_code != 200:
raise HTTPException(status_code=502, detail=f"Gagal membaca status task (HTTP {resp.status_code}).")
data = resp.json()
item = data.get("Result") or {}
phase = extract_status_phase(item.get("Status"))
return {
"task_id": task_id,
"phase": phase,
"video_url": normalize_url(item.get("VideoUrl") or item.get("FileUrl") or item.get("OutputUrl")),
"first_frame_url": normalize_url(item.get("FirstFrameImageUrl")),
"output_first_frame_url": normalize_url(((item.get("OutputVideoFirstFrame") or {}).get("Url"))),
"prompt": item.get("Prompt"),
"status": item.get("Status"),
"raw": item,
}
def list_video_tasks(self, *, cookie: str, csrf_token: str, proxy: str | None, limit: int = 12) -> dict[str, Any]:
resp = self._request(
"POST",
LIST_VIDEO_TASKS_URL,
cookie=cookie,
csrf_token=csrf_token,
proxy=proxy,
headers={"Content-Type": "application/json"},
json={"Filter": {}},
timeout=(20, 80),
)
if resp.status_code != 200:
raise HTTPException(status_code=502, detail=f"Gagal membaca daftar hasil video (HTTP {resp.status_code}).")
data = resp.json()
result = data.get("Result") or {}
items = result.get("Items") or []
clean_items = [clean_video_item(item) for item in items[:limit]]
return {"items": clean_items, "next_token": result.get("NextToken")}
def list_image_records(
self,
*,
cookie: str,
csrf_token: str,
proxy: str | None,
page_index: int = 1,
page_size: int = 6,
) -> dict[str, Any]:
resp = self._request(
"POST",
LIST_IMAGE_RECORDS_URL,
cookie=cookie,
csrf_token=csrf_token,
proxy=proxy,
headers={"Content-Type": "application/json"},
json={"PageIndex": page_index, "PageSize": page_size},
timeout=(20, 80),
)
if resp.status_code != 200:
raise HTTPException(status_code=502, detail=f"Gagal membaca daftar hasil foto (HTTP {resp.status_code}).")
data = resp.json()
result = data.get("Result") or {}
items = result.get("Items") or []
return {
"total": result.get("Total", 0),
"records": items,
"images": flatten_image_records(items),
}
def _upload_image_for_imgen(
self,
filename: str,
content: bytes,
*,
cookie: str,
csrf_token: str,
proxy: str | None,
) -> dict[str, Any]:
return self._upload_content(
filename,
content,
cookie=cookie,
csrf_token=csrf_token,
proxy=proxy,
upload_url=IMAGE_UPLOAD_URL,
)
def create_image_generation(
self,
*,
access_code: str,
cookie: str,
csrf_token: str,
proxy: str | None,
prompt: str,
image_model_name: str,
resolution_choice: str,
ratio_choice: str,
image_count: int,
reference_images: list[tuple[str, bytes]],
available_models: list[str],
store,
) -> dict[str, Any]:
if image_model_name not in IMAGE_MODEL_CONFIG:
raise HTTPException(status_code=400, detail="Model image tidak dikenal.")
if not available_models:
raise HTTPException(status_code=400, detail="Semua model rotasi exhausted. Simpan credential baru untuk reset.")
cfg = IMAGE_MODEL_CONFIG[image_model_name]
max_count = min(int(image_count), int(cfg["max_images"]))
images_payload = []
for filename, content in reference_images:
images_payload.append(
self._upload_image_for_imgen(
filename,
content,
cookie=cookie,
csrf_token=csrf_token,
proxy=proxy,
)
)
ratio_str, size_str = image_resolution_config(
image_model_name,
resolution_choice,
ratio_choice,
has_image=bool(images_payload),
)
url_patterns = [
r'(https://[^\s"\'\\]+\.(?:jpg|jpeg|png|webp)[^\s"\'\\]*)',
r'(https://[^\s"\'\\]*ark-common-storage[^\s"\'\\]*)',
r'(https://[^\s"\'\\]*tos-ap-southeast[^\s"\'\\]*)',
r'(https://[^\s"\'\\]*imagex[^\s"\'\\]*)',
r'(https://[^\s"\'\\]*byteimg[^\s"\'\\]*)',
]
exhausted_count = 0
last_non_exhausted_error: str | None = None
for model_name in available_models:
try:
payload = {
"From": "pc",
"Model": model_name,
"EndpointId": cfg["endpoint_id"],
"Type": "normal",
"Images": images_payload,
"Prompt": prompt,
"Ratio": ratio_str,
"Size": size_str,
"ImageCount": max_count,
"Watermark": False,
"GuidanceScale": 1,
"Seed": -1,
}
resp = self._request(
"POST",
IMAGE_GEN_URL,
cookie=cookie,
csrf_token=csrf_token,
proxy=proxy,
headers={"Content-Type": "application/json"},
json=payload,
timeout=(20, 180),
stream=True,
)
if resp.status_code != 200:
body = {}
try:
body = resp.json()
except Exception:
body = {"raw": resp.text[:500]}
if is_quota_exhausted_error(body) or is_image_exhausted_signal(body):
raise HTTPException(status_code=409, detail=f"IMAGE_EXHAUSTED::{model_name}")
message = body.get("Message") or body.get("message") or body.get("raw") or f"HTTP {resp.status_code}"
raise HTTPException(status_code=400, detail=f"BytePlus image request ditolak: {message}")
found_urls: list[str] = []
should_mark_exhausted = False
stop_rotation = False
for line in resp.iter_lines():
if not line:
continue
decoded = line.decode("utf-8", errors="replace")
raw_json = decoded[6:] if decoded.startswith("data: ") else decoded
try:
data_obj = json.loads(raw_json)
if is_stop_rotation_error(data_obj):
stop_rotation = True
break
code_val = data_obj.get("code", data_obj.get("Code", None))
msg_val = data_obj.get("msg", data_obj.get("Msg", data_obj.get("message", data_obj.get("Message", ""))))
if is_image_exhausted_signal(code_val, msg_val, data_obj, raw_json):
should_mark_exhausted = True
break
if code_val not in (None, 0, "0", 200, "200", ""):
raise HTTPException(status_code=400, detail=f"BytePlus image error: {msg_val or code_val}")
except HTTPException:
raise
except Exception:
if is_image_exhausted_signal(raw_json):
should_mark_exhausted = True
break
pass
for pattern in url_patterns:
for match in re.findall(pattern, decoded):
cleaned = normalize_url(match.replace("\u0026", "&").rstrip('\"'))
if cleaned and cleaned not in found_urls:
found_urls.append(cleaned)
if stop_rotation:
raise HTTPException(status_code=400, detail="Konten/gambar referensi diblokir BytePlus. Ganti prompt atau gambar.")
if should_mark_exhausted:
raise HTTPException(status_code=409, detail=f"IMAGE_EXHAUSTED::{model_name}")
if found_urls:
return {
"used_model": model_name,
"images": [{"url": u} for u in found_urls],
"ratio": ratio_str,
"size": size_str,
}
raise HTTPException(status_code=400, detail="BytePlus tidak mengembalikan hasil gambar.")
except HTTPException as exc:
detail = str(exc.detail)
if exc.status_code == 409 or is_image_exhausted_signal(detail):
store.add_exhausted_model(access_code, model_name)
exhausted_count += 1
continue
last_non_exhausted_error = detail
raise
if exhausted_count > 0 and exhausted_count == len(available_models):
raise HTTPException(status_code=400, detail="Semua model gambar pada akun ini sedang habis kuota. Silakan ganti credential atau tunggu reset.")
raise HTTPException(status_code=502, detail=last_non_exhausted_error or "Semua model gagal menghasilkan gambar.")
def create_reference_generation(
self,
*,
access_code: str,
cookie: str,
csrf_token: str,
proxy: str | None,
prompt: str,
duration: int,
resolution: str,
ratio: str,
generate_audio: bool,
endpoint_id: str,
model_version: str,
image_files: dict[int, tuple[str, bytes]],
video_file: tuple[str, bytes] | None,
audio_file: tuple[str, bytes] | None,
available_models: list[str],
store,
) -> dict[str, Any]:
validation = validate_reference_inputs(
prompt,
image_files,
video_uploaded=video_file is not None,
audio_uploaded=audio_file is not None,
)
if validation["missing"]:
raise HTTPException(
status_code=400,
detail=f"Referensi belum lengkap: {', '.join(validation['missing'])}",
)
detected_refs = extract_image_refs(prompt)
use_video = has_video_ref(prompt)
use_audio = has_audio_ref(prompt)
if not detected_refs and not use_video and not use_audio:
raise HTTPException(status_code=400, detail="Prompt reference generation harus memakai @imageN, @video1, atau @audio1.")
if video_file is not None:
with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(video_file[0])[1] or ".mp4") as tmp:
tmp.write(video_file[1])
tmp_path = tmp.name
try:
duration_probe = probe_duration_ffprobe(tmp_path)
finally:
try:
os.remove(tmp_path)
except OSError:
pass
if duration_probe and duration_probe > VIDEO_MAX_SECONDS:
raise HTTPException(
status_code=400,
detail=f"Video referensi terlalu panjang ({duration_probe:.1f}s). Maksimal {VIDEO_MAX_SECONDS} detik.",
)
label_map: dict[str, str] = {}
for n in detected_refs:
label_map[f"image{n}"] = f"image_1_{n}"
if use_video:
label_map["video1"] = "video_1_1"
if use_audio:
label_map["audio1"] = "voice_1_2"
rich_prompt = replace_reference_prompt(prompt, label_map)
reference_images: list[dict[str, Any]] = []
reference_videos: list[dict[str, Any]] = []
reference_audios: list[dict[str, Any]] = []
for n in detected_refs:
filename, content = image_files[n]
uploaded = self._upload_content(
filename,
content,
cookie=cookie,
csrf_token=csrf_token,
proxy=proxy,
extra_form={
"type": "image",
"modelName": endpoint_id,
"modelVersion": model_version,
},
)
reference_images.append(
{
"BucketName": uploaded["Bucket"],
"ObjectKey": uploaded["Prefix"],
"Url": uploaded["Url"],
"Label": label_map[f"image{n}"],
}
)
if use_video and video_file is not None:
filename, content = video_file
uploaded = self._upload_content(
filename,
content,
cookie=cookie,
csrf_token=csrf_token,
proxy=proxy,
extra_form={
"type": "video",
"modelName": endpoint_id,
"modelVersion": model_version,
"withFirstFrame": "true",
},
)
reference_videos.append(
{
"BucketName": uploaded["Bucket"],
"ObjectKey": uploaded["Prefix"],
"Url": uploaded["Url"],
"Label": label_map["video1"],
}
)
if use_audio and audio_file is not None:
filename, content = audio_file
uploaded = self._upload_content(
filename,
content,
cookie=cookie,
csrf_token=csrf_token,
proxy=proxy,
extra_form={
"type": "audio",
"modelName": endpoint_id,
"modelVersion": model_version,
},
)
reference_audios.append(
{
"BucketName": uploaded["Bucket"],
"ObjectKey": uploaded["Prefix"],
"Url": uploaded["Url"],
"Label": label_map["audio1"],
}
)
payload = self._create_reference_payload(
prompt=prompt,
rich_prompt=rich_prompt,
duration=duration,
resolution=resolution,
ratio=ratio,
generate_audio=generate_audio,
endpoint_id=endpoint_id,
reference_images=reference_images,
reference_videos=reference_videos,
reference_audios=reference_audios,
)
created = self.create_video_task_smart(
access_code=access_code,
cookie=cookie,
csrf_token=csrf_token,
proxy=proxy,
payload=payload,
available_models=available_models,
store=store,
)
task_status = self.get_video_task(
created["task_id"],
cookie=cookie,
csrf_token=csrf_token,
proxy=proxy,
)
return {
"task_id": created["task_id"],
"used_model": created.get("used_model"),
"task": task_status,
"reference_summary": validation,
}
def get_enabled_rules(model_mode: int) -> dict[str, Any]:
if model_mode == MODEL_MODE_EXPIRED:
return {
"enabled_mode": 0,
"video_enabled": True,
"image_enabled": False,
"reference_enabled": False,
"video_modes": ["text_to_video", "image_to_video"],
"allowed_video_models": ["Seedance 1.5 Pro"],
"allowed_reference_models": [],
"max_video_duration": 12,
"can_choose_video_model": False,
}
if model_mode == MODEL_MODE_PRO_ONLY:
return {
"enabled_mode": 1,
"video_enabled": True,
"image_enabled": False,
"reference_enabled": True,
"video_modes": ["text_to_video", "image_to_video", "reference_generation"],
"allowed_video_models": ["Seedance 2.0"],
"allowed_reference_models": ["Seedance 2.0"],
"max_video_duration": 15,
"can_choose_video_model": False,
}
if model_mode == MODEL_MODE_FAST_ONLY:
return {
"enabled_mode": 2,
"video_enabled": True,
"image_enabled": False,
"reference_enabled": True,
"video_modes": ["text_to_video", "image_to_video", "reference_generation"],
"allowed_video_models": ["Seedance 2.0 Fast"],
"allowed_reference_models": ["Seedance 2.0 Fast"],
"max_video_duration": 15,
"can_choose_video_model": False,
}
if model_mode == MODEL_MODE_BOTH:
return {
"enabled_mode": 3,
"video_enabled": True,
"image_enabled": False,
"reference_enabled": True,
"video_modes": ["text_to_video", "image_to_video", "reference_generation"],
"allowed_video_models": ["Seedance 2.0", "Seedance 2.0 Fast", "Seedance 1.5 Pro"],
"allowed_reference_models": ["Seedance 2.0", "Seedance 2.0 Fast"],
"max_video_duration": 15,
"can_choose_video_model": True,
}
if model_mode == MODEL_MODE_IMAGE_ENABLED:
return {
"enabled_mode": 4,
"video_enabled": True,
"image_enabled": True,
"reference_enabled": True,
"video_modes": ["text_to_video", "image_to_video", "reference_generation"],
"allowed_video_models": ["Seedance 2.0", "Seedance 2.0 Fast", "Seedance 1.5 Pro"],
"allowed_reference_models": ["Seedance 2.0", "Seedance 2.0 Fast"],
"max_video_duration": 15,
"can_choose_video_model": True,
}
if model_mode == MODEL_MODE_IMAGE_ONLY:
return {
"enabled_mode": 5,
"video_enabled": False,
"image_enabled": True,
"reference_enabled": False,
"video_modes": [],
"allowed_video_models": [],
"allowed_reference_models": [],
"max_video_duration": 0,
"can_choose_video_model": False,
}
raise HTTPException(status_code=403, detail="enabled mode tidak dikenali.")
def _allowed_resolutions(model_mode: int, model_choice: str, generation_mode: str) -> list[str]:
if model_mode in (MODEL_MODE_BOTH, MODEL_MODE_IMAGE_ENABLED):
if generation_mode == "reference_generation":
return ["480p", "720p"] if model_choice == "Seedance 2.0 Fast" else ["480p", "720p", "1080p"]
return ["480p", "720p"] if model_choice == "Seedance 2.0 Fast" else ["480p", "720p", "1080p"]
return ["480p", "720p"]
def validate_video_request(model_mode: int, generation_mode: str, model_choice: str, duration: int, resolution: str) -> None:
rules = get_enabled_rules(model_mode)
if generation_mode not in rules["video_modes"]:
raise HTTPException(
status_code=403,
detail=f"Mode {generation_mode} tidak diizinkan untuk enabled={model_mode}.",
)
if int(duration) > int(rules["max_video_duration"]):
raise HTTPException(
status_code=400,
detail=f"Durasi melebihi batas paket ini. Maksimum {rules['max_video_duration']} detik.",
)
allowed_models = rules["allowed_reference_models"] if generation_mode == "reference_generation" else rules["allowed_video_models"]
if model_choice not in allowed_models:
raise HTTPException(
status_code=403,
detail=f"Model {model_choice} tidak diizinkan untuk enabled={model_mode} dan mode {generation_mode}.",
)
allowed_resolutions = _allowed_resolutions(model_mode, model_choice, generation_mode)
if resolution not in allowed_resolutions:
raise HTTPException(
status_code=400,
detail=f"Resolusi {resolution} tidak diizinkan. Pilihan valid: {', '.join(allowed_resolutions)}.",
)
def resolve_video_endpoint(model_mode: int, model_choice: str | None) -> tuple[str, str]:
if model_mode == MODEL_MODE_IMAGE_ONLY:
raise HTTPException(status_code=403, detail="Paket akses ini hanya untuk image generation.")
if model_mode == MODEL_MODE_EXPIRED:
return ENDPOINT_LEGACY, "Seedance 1.5 Pro"
if model_mode == MODEL_MODE_FAST_ONLY:
return ENDPOINT_FAST, "Seedance 2.0 Fast"
if model_mode in (MODEL_MODE_BOTH, MODEL_MODE_IMAGE_ENABLED):
if model_choice == "Seedance 2.0 Fast":
return ENDPOINT_FAST, "Seedance 2.0 Fast"
if model_choice == "Seedance 1.5 Pro":
return ENDPOINT_LEGACY, "Seedance 1.5 Pro"
return ENDPOINT_PRO, "Seedance 2.0"
return ENDPOINT_PRO, "Seedance 2.0"
def resolve_reference_endpoint(model_mode: int, model_choice: str | None) -> tuple[str, str, str]:
if model_mode in (MODEL_MODE_EXPIRED, MODEL_MODE_IMAGE_ONLY):
raise HTTPException(status_code=403, detail="Reference Generation tidak tersedia untuk paket akses ini.")
if model_mode == MODEL_MODE_FAST_ONLY:
return ENDPOINT_FAST, "Seedance 2.0 Fast", "260128"
if model_mode in (MODEL_MODE_BOTH, MODEL_MODE_IMAGE_ENABLED):
if model_choice == "Seedance 2.0 Fast":
return ENDPOINT_FAST, "Seedance 2.0 Fast", "260128"
return ENDPOINT_PRO, "Seedance 2.0", "260128"
return ENDPOINT_PRO, "Seedance 2.0", "260128"
|