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