Download core/byteplus.py from malikrf22/uraura: direct link, hf CLI and curl.
- Browser
- Download file 37.4 kB
-
https://huggingface.co/spaces/malikrf22/uraura/resolve/main/core/byteplus.py
- Command line
-
hf download hf://spaces/malikrf22/uraura/core/byteplus.py
-
curl -L -o byteplus.py https://huggingface.co/spaces/malikrf22/uraura/resolve/main/core/byteplus.py
37.4 kB
| 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" | |