Spaces:
Running on Zero
Running on Zero
File size: 5,249 Bytes
35d8fb6 58dde1b 35d8fb6 edfe665 35d8fb6 3d6ae90 35d8fb6 cb0af6c 35d8fb6 | 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 | """Typed API errors shared by the /api/v1 routes and the legacy Gradio adapters.
Services raise these; each interface renders them its own way:
* ``/api/v1`` maps ``status`` to the HTTP status code and serialises
``to_body()`` as the response body.
* The legacy Gradio endpoints return HTTP 200 with ``to_legacy_dict()`` —
the ``{"error": ..., "segments": []}`` shape production clients parse.
Never raise a bare ``Exception`` out of a service: an unmapped error becomes a
500 with no ``code`` for the caller to branch on.
"""
from __future__ import annotations
# HTTP statuses, named so call sites read as intent rather than magic numbers.
HTTP_BAD_REQUEST = 400
HTTP_PAYMENT_REQUIRED = 402
HTTP_FORBIDDEN = 403
HTTP_NOT_FOUND = 404
HTTP_UNPROCESSABLE = 422
HTTP_UNPROCESSABLE_ENTITY = 422
HTTP_TOO_MANY_REQUESTS = 429
HTTP_BAD_GATEWAY = 502
HTTP_SERVICE_UNAVAILABLE = 503
class ApiError(Exception):
"""Base class for every error a service is allowed to raise."""
status = HTTP_BAD_REQUEST
code = "error"
def __init__(self, message: str, **extra):
super().__init__(message)
self.message = message
# Extra keys are merged into both renderings (e.g. retry_after_s).
self.extra = {k: v for k, v in extra.items() if v is not None}
def to_body(self) -> dict:
"""The /api/v1 error body."""
return {"code": self.code, "message": self.message, "detail": self.extra or None}
def to_legacy_dict(self, audio_id: str | None = None) -> dict:
"""The legacy HTTP-200 error shape."""
body = {"error": self.message, "error_code": self.code, "segments": [], **self.extra}
if audio_id is not None:
body["audio_id"] = audio_id
return body
class ValidationError(ApiError):
"""Caller sent a malformed or unsupported parameter."""
status = HTTP_BAD_REQUEST
code = "invalid_request"
class SessionNotFoundError(ApiError):
"""The audio_id is unknown, malformed, or its session has expired."""
status = HTTP_NOT_FOUND
code = "session_not_found"
def __init__(self, message: str = "Session not found or expired", **extra):
super().__init__(message, **extra)
class BatchNotFoundError(ApiError):
"""The native batch handle is unknown, expired, or owned by another caller."""
status = HTTP_NOT_FOUND
code = "batch_not_found"
def __init__(self, message: str = "Batch not found or expired", **extra):
super().__init__(message, **extra)
class NotFoundError(ApiError):
"""The requested catalog entry does not exist."""
status = HTTP_NOT_FOUND
code = "not_found"
class CatalogUnavailableError(ApiError):
"""The recitation catalog or its storage could not be read.
A server-side dependency failure, not a caller mistake — so 503, and the
caller can sensibly retry.
"""
status = HTTP_SERVICE_UNAVAILABLE
code = "catalog_unavailable"
class DownloadFailedError(ApiError):
"""The source URL could not be fetched."""
status = HTTP_BAD_REQUEST
code = "download_failed"
class NoSpeechError(ApiError):
"""Segmentation found nothing to align."""
status = HTTP_UNPROCESSABLE
code = "no_speech_detected"
def __init__(self, message: str = "No speech detected in audio", **extra):
super().__init__(message, **extra)
class AlignmentFailedError(ApiError):
"""The pipeline ran but produced no usable alignment."""
status = HTTP_UNPROCESSABLE
code = "alignment_failed"
class TimingFailedError(ApiError):
"""Word timing failed."""
status = HTTP_BAD_GATEWAY
code = "timing_failed"
class GpuQuotaError(ApiError):
"""ZeroGPU quota is exhausted for this caller.
402 rather than 429: the caller is not being rate-limited for misbehaving,
they have consumed an allowance that only time or an upgrade restores.
"""
status = HTTP_PAYMENT_REQUIRED
code = "gpu_quota_exhausted"
def __init__(self, message: str, *, anonymous: bool = False, reset_time=None):
super().__init__(message, reset_time=reset_time)
self.anonymous = anonymous
self.reset_time = reset_time
if anonymous:
self.code = "gpu_quota_anonymous"
def to_legacy_dict(self, audio_id: str | None = None) -> dict:
# Production clients read `reset_time` at the top level even when null.
body = super().to_legacy_dict(audio_id)
body["reset_time"] = self.reset_time
return body
class GpuUnavailableError(ApiError):
"""ZeroGPU could not grant a Space slot after bounded server retries."""
status = 503
code = "gpu_temporarily_unavailable"
def __init__(self, message: str = "GPU capacity is temporarily unavailable."):
super().__init__(message, retry_after_s=5)
class CpuRateLimitedError(ApiError):
"""The shared CPU path is saturated or the caller exceeded fair use."""
status = HTTP_TOO_MANY_REQUESTS
code = "cpu_rate_limited"
def __init__(self, message: str, *, code: str | None = None, retry_after_s: int = 30):
super().__init__(message, retry_after_s=retry_after_s)
self.retry_after_s = retry_after_s
if code:
self.code = code
|