File size: 5,848 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 | from __future__ import annotations
import importlib.util
from importlib.machinery import SourceFileLoader
from functools import lru_cache
from pathlib import Path
from typing import Any, Callable
from huggingface_hub import hf_hub_download
from .config import get_settings
from .constants import FALLBACK_MODEL_NAMES
def _fallback_is_quota_exhausted_error(response_json: dict) -> bool:
if not isinstance(response_json, dict):
return False
meta = response_json.get("ResponseMetadata", {})
meta_error = meta.get("Error", {}) if isinstance(meta, dict) else {}
code_val = ""
msg_val = ""
code_val += str(response_json.get("Code", ""))
code_val += str(response_json.get("code", ""))
msg_val += str(response_json.get("Message", ""))
msg_val += str(response_json.get("message", ""))
if isinstance(meta_error, dict):
code_val += str(meta_error.get("Code", ""))
msg_val += str(meta_error.get("Message", ""))
else:
code_val += str(meta_error)
inner = response_json.get("Result")
if isinstance(inner, dict):
code_val += str(inner.get("Code", ""))
msg_val += str(inner.get("Message", ""))
exhausted_codes = [
"QuotaExceeded",
"QuotaExceeded.FreeTrialQuota",
"RateLimitExceeded",
"InsufficientQuota",
"BillingQuotaExceeded",
"FreeTierQuotaExceeded",
"AccountQuotaExceeded",
]
exhausted_phrases = [
"exhausted its free trial quota",
"free trial quota",
"no remaining quota",
"quota has been exhausted",
"account has exhausted",
"trial quota",
"billing quota",
"run out of quota",
"insufficient quota",
"quota exceeded",
]
low_code = code_val.lower()
low_msg = msg_val.lower()
return any(c.lower() in low_code for c in exhausted_codes) or any(
p.lower() in low_msg for p in exhausted_phrases
)
def _fallback_is_stop_rotation_error(response_json: dict) -> bool:
if not isinstance(response_json, dict):
return False
candidates = [response_json]
inner = response_json.get("Result")
if isinstance(inner, dict):
candidates.append(inner)
for obj in candidates:
err_code = obj.get("errCode")
decision = str(obj.get("decision", "")).upper()
decision_detail = str(obj.get("decisionDetail", "")).upper()
if err_code == 0 and decision == "BLOCK":
return True
if err_code == 0 and "BLOCK" in decision_detail:
return True
error_str = ""
for obj in candidates:
error_str += str(obj.get("Message", ""))
error_str += str(obj.get("message", ""))
error_str += str(obj.get("Error", ""))
error_str += str(obj.get("error", ""))
meta = response_json.get("ResponseMetadata", {})
if isinstance(meta, dict):
meta_error = meta.get("Error", {})
if isinstance(meta_error, dict):
error_str += str(meta_error.get("Message", ""))
error_str += str(meta_error.get("Code", ""))
else:
error_str += str(meta_error)
return "InputImageSensitiveContentDetected" in error_str
def _fallback_extract_task_id(task_result: dict | None):
if not task_result:
return None
if "Result" in task_result and task_result["Result"]:
res = task_result["Result"]
if isinstance(res, dict):
return (
res.get("Id")
or res.get("TaskId")
or res.get("id")
or res.get("taskId")
or res.get("task_id")
)
return task_result.get("Id") or task_result.get("TaskId") or task_result.get("task_id")
def _fallback_extract_status_phase(status_obj: Any) -> str:
if status_obj is None:
return ""
if isinstance(status_obj, dict):
phase = status_obj.get("Phase") or status_obj.get("phase") or status_obj.get("status") or ""
return phase.lower() if isinstance(phase, str) else ""
if isinstance(status_obj, str):
return status_obj.lower()
return ""
@lru_cache(maxsize=1)
def _load_remote_module():
settings = get_settings()
if not settings.hf_use_remote_engine or not settings.hf_token:
return None
try:
local_path = hf_hub_download(
repo_id=settings.hf_core_dataset_repo,
filename=settings.hf_core_filename,
repo_type="dataset",
token=settings.hf_token,
)
module_name = f"orbitbot_remote_core_{Path(local_path).stem}"
loader = SourceFileLoader(module_name, local_path)
spec = importlib.util.spec_from_loader(module_name, loader)
if not spec or not spec.loader:
return None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
except Exception:
return None
def get_model_names() -> list[str]:
module = _load_remote_module()
if module is not None and hasattr(module, "MODEL_NAMES"):
try:
return list(getattr(module, "MODEL_NAMES"))
except Exception:
pass
return FALLBACK_MODEL_NAMES
def get_helper(name: str, fallback: Callable):
module = _load_remote_module()
if module is not None and hasattr(module, name):
fn = getattr(module, name)
if callable(fn):
return fn
return fallback
is_quota_exhausted_error = get_helper("is_quota_exhausted_error", _fallback_is_quota_exhausted_error)
is_stop_rotation_error = get_helper("is_stop_rotation_error", _fallback_is_stop_rotation_error)
extract_task_id = get_helper("extract_task_id", _fallback_extract_task_id)
extract_status_phase = get_helper("extract_status_phase", _fallback_extract_status_phase)
|