File size: 7,494 Bytes
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 | from __future__ import annotations
import html
import json
import re
import subprocess
from typing import Any
from urllib.parse import urlparse
MAX_REF_IMAGES = 9
MIME_TYPES = {
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".webp": "image/webp",
".gif": "image/gif",
".mp4": "video/mp4",
".mp3": "audio/mpeg",
".wav": "audio/wav",
".m4a": "audio/mp4",
".ogg": "audio/ogg",
}
def get_mime_type(filename: str, default: str = "application/octet-stream") -> str:
if not filename:
return default
name = filename.lower()
for ext, mime in MIME_TYPES.items():
if name.endswith(ext):
return mime
return default
def extract_from_url(url: str) -> tuple[str, str]:
try:
parsed = urlparse(url.split("?")[0])
host = parsed.netloc
path = parsed.path.lstrip("/")
bucket_name = host.split(".")[0] if "." in host else ""
return bucket_name, path
except Exception:
return "", ""
def normalize_url(value: str | None) -> str:
if not value:
return ""
return html.unescape(str(value))
def safe_json_loads(value: str | None) -> Any:
if not value:
return None
try:
return json.loads(value)
except Exception:
return None
def flatten_image_records(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
output: list[dict[str, Any]] = []
for record in items or []:
images = (((record or {}).get("Output") or {}).get("Items") or [])
for idx, img in enumerate(images):
output.append(
{
"sid": record.get("Sid"),
"model": record.get("Model"),
"prompt": record.get("Prompt"),
"status": record.get("Status"),
"create_time": record.get("CreateTime"),
"image_index": idx,
"image_id": img.get("Id"),
"url": normalize_url(img.get("Url")),
"bucket_name": img.get("BucketName"),
"object_key": img.get("ObjectKey"),
}
)
return output
def image_resolution_config(model_name: str, resolution_choice: str, ratio_choice: str, has_image: bool):
is_4k = (resolution_choice == "4K") and (model_name != "Seedream 5 Lite")
if ratio_choice == "Portrait (9:16)":
ratio_str = "9:16"
size_str = "3040x5504" if is_4k else "1440x2560"
elif ratio_choice == "Landscape (16:9)":
ratio_str = "16:9"
size_str = "5504x3040" if is_4k else "2560x1440"
else:
ratio_str = "adaptive" if has_image else "1:1"
size_str = "4k" if is_4k else ("2k" if has_image else "2048x2048")
return ratio_str, size_str
def clean_video_item(item: dict[str, Any]) -> dict[str, Any]:
status = item.get("Status") or {}
return {
"id": item.get("Id") or item.get("Sid"),
"sid": item.get("Sid"),
"create_time": item.get("CreateTime"),
"update_time": item.get("UpdateTime"),
"model_name": item.get("ModelName"),
"prompt": item.get("Prompt"),
"ratio": item.get("Ratio"),
"resolution": item.get("Resolution"),
"duration": item.get("Duration"),
"task_type": item.get("VideoTaskType"),
"phase": (status.get("Phase") or "").lower() if isinstance(status, dict) else str(status).lower(),
"phase_time": status.get("PhaseTime") if isinstance(status, dict) else None,
"phase_message": status.get("Message") if isinstance(status, dict) else "",
"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"))),
"raw": item,
}
def pick_video_url(item: dict[str, Any]) -> str:
for key in ("video_url", "VideoUrl", "FileUrl", "OutputUrl"):
val = item.get(key)
if val:
return normalize_url(val)
return ""
def extract_image_refs(prompt: str, max_n: int = MAX_REF_IMAGES) -> list[int]:
nums = {int(m.group(1)) for m in re.finditer(r"@image([1-9])\b", prompt or "", flags=re.IGNORECASE)}
return sorted(n for n in nums if 1 <= n <= max_n)
def has_video_ref(prompt: str) -> bool:
return bool(re.search(r"@video1\b", prompt or "", flags=re.IGNORECASE))
def has_audio_ref(prompt: str) -> bool:
return bool(re.search(r"@audio1\b", prompt or "", flags=re.IGNORECASE))
def replace_reference_prompt(prompt: str, label_map: dict[str, str]) -> str:
def repl(match: re.Match[str]) -> str:
key = match.group(1).lower()
label = label_map.get(key)
return f"<<<{label}>>>" if label else match.group(0)
return re.sub(r"@(image[1-9]|video1|audio1)\b", repl, prompt or "", flags=re.IGNORECASE)
def validate_reference_inputs(
prompt: str,
uploaded_images: dict[int, Any],
video_uploaded: bool = False,
audio_uploaded: bool = False,
) -> dict[str, Any]:
detected_imgs = extract_image_refs(prompt or "")
used_video = has_video_ref(prompt or "")
used_audio = has_audio_ref(prompt or "")
uploaded_img_nums = sorted(n for n in uploaded_images.keys() if uploaded_images.get(n))
missing: list[str] = []
ok: list[str] = []
unused: list[str] = []
for n in detected_imgs:
if n in uploaded_img_nums:
ok.append(f"@image{n}")
else:
missing.append(f"@image{n}")
if used_video:
(ok if video_uploaded else missing).append("@video1")
if used_audio:
(ok if audio_uploaded else missing).append("@audio1")
for n in uploaded_img_nums:
if n not in detected_imgs:
unused.append(f"@image{n}")
if video_uploaded and not used_video:
unused.append("@video1")
if audio_uploaded and not used_audio:
unused.append("@audio1")
used_list = [f"@image{n}" for n in detected_imgs]
if used_video:
used_list.append("@video1")
if used_audio:
used_list.append("@audio1")
lines = ["### Validasi Referensi"]
if not used_list:
lines.append("Tidak ada placeholder referensi di prompt.")
else:
lines.append(f"Terdeteksi: {', '.join(used_list)}")
if ok:
lines.append(f"Siap dipakai: {', '.join(ok)}")
if missing:
lines.append(f"Belum diupload: {', '.join(missing)}")
if unused:
lines.append(f"Sudah diupload tapi belum dipakai: {', '.join(unused)}")
if used_list and not missing:
lines.append("Semua referensi lengkap.")
return {
"detected_imgs": detected_imgs,
"used_video": used_video,
"used_audio": used_audio,
"missing": missing,
"ok": ok,
"unused": unused,
"summary_lines": lines,
"summary": "\n".join(lines),
}
def probe_duration_ffprobe(path: str) -> float | None:
try:
cmd = [
"ffprobe",
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
path,
]
out = subprocess.check_output(cmd, stderr=subprocess.STDOUT, text=True).strip()
return float(out) if out else None
except Exception:
return None
|