fix: retry Polza images after async size rejection
This commit is contained in:
parent
3b98061b16
commit
aae4616308
3 changed files with 65 additions and 35 deletions
|
|
@ -159,22 +159,32 @@ def _safe_public_url(url: str) -> None:
|
||||||
raise ImageGenerationError("download_failed", "Не удалось разрешить адрес изображения.") from exc
|
raise ImageGenerationError("download_failed", "Не удалось разрешить адрес изображения.") from exc
|
||||||
|
|
||||||
|
|
||||||
def error_from_response(response: httpx.Response) -> ImageGenerationError:
|
def classify_provider_error(status_code: int, body: str) -> ImageGenerationError:
|
||||||
body = response.text[:1000].lower()
|
normalized = body[:4000].lower()
|
||||||
if response.status_code in {401, 403}:
|
if status_code in {401, 403}:
|
||||||
return ImageGenerationError("token_invalid", "Токен Polza отклонён.")
|
return ImageGenerationError("token_invalid", "Токен Polza отклонён.")
|
||||||
if response.status_code == 429:
|
if status_code == 402 or "balance" in normalized or "insufficient" in normalized:
|
||||||
return ImageGenerationError("rate_limited", "Превышен лимит запросов Polza.")
|
|
||||||
if "balance" in body or "insufficient" in body:
|
|
||||||
return ImageGenerationError("insufficient_balance", "Недостаточно средств в Polza.")
|
return ImageGenerationError("insufficient_balance", "Недостаточно средств в Polza.")
|
||||||
if "moderation" in body or "safety" in body:
|
if status_code == 429:
|
||||||
|
return ImageGenerationError("rate_limited", "Превышен лимит запросов Polza.")
|
||||||
|
if "moderation" in normalized or "safety" in normalized:
|
||||||
return ImageGenerationError("moderation_rejected", "Запрос отклонён политикой провайдера.")
|
return ImageGenerationError("moderation_rejected", "Запрос отклонён политикой провайдера.")
|
||||||
if "model" in body and ("not found" in body or "unavailable" in body):
|
if "model" in normalized and ("not found" in normalized or "unavailable" in normalized):
|
||||||
return ImageGenerationError("model_unavailable", "Выбранная модель недоступна.")
|
return ImageGenerationError("model_unavailable", "Выбранная модель недоступна.")
|
||||||
size_error = any(value in body for value in ("resolution", "size", "quality", "4k", "image_resolution"))
|
size_error = any(value in normalized for value in ("resolution", "size", "quality", "4k", "image_resolution", "image_size"))
|
||||||
return ImageGenerationError("provider_error", "Polza не смогла создать изображение.", size_error=size_error)
|
return ImageGenerationError("provider_error", "Polza не смогла создать изображение.", size_error=size_error)
|
||||||
|
|
||||||
|
|
||||||
|
def error_from_response(response: httpx.Response) -> ImageGenerationError:
|
||||||
|
return classify_provider_error(response.status_code, response.text)
|
||||||
|
|
||||||
|
|
||||||
|
def error_from_status(data: dict[str, Any]) -> ImageGenerationError:
|
||||||
|
error = data.get("error")
|
||||||
|
body = json.dumps(error if error is not None else data, ensure_ascii=False, default=str)
|
||||||
|
return classify_provider_error(400, body)
|
||||||
|
|
||||||
|
|
||||||
class PolzaClient:
|
class PolzaClient:
|
||||||
def __init__(self, api_url: str, token: str) -> None:
|
def __init__(self, api_url: str, token: str) -> None:
|
||||||
self.api_url, self.token = normalize_api_url(api_url), token
|
self.api_url, self.token = normalize_api_url(api_url), token
|
||||||
|
|
|
||||||
|
|
@ -18,7 +18,7 @@ from app.config import get_settings
|
||||||
from app.database import SessionLocal, init_db
|
from app.database import SessionLocal, init_db
|
||||||
from app.models import AppSetting, Article, Frame, Source, Video
|
from app.models import AppSetting, Article, Frame, Source, Video
|
||||||
from app.models import ImageGenerationBatch, ImageGenerationJob
|
from app.models import ImageGenerationBatch, ImageGenerationJob
|
||||||
from app.image_generation import ImageGenerationError, PolzaClient, extract_result_url, save_remote_image
|
from app.image_generation import ImageGenerationError, PolzaClient, error_from_status, extract_result_url, save_remote_image
|
||||||
from app.quality import validate_article_content, validate_transcript_text
|
from app.quality import validate_article_content, validate_transcript_text
|
||||||
|
|
||||||
settings = get_settings()
|
settings = get_settings()
|
||||||
|
|
@ -71,13 +71,18 @@ def generate_article_image(job_id: str) -> None:
|
||||||
api_url, model, prompt, article_id, target = job.api_url, job.model, job.prompt, job.article_id, job.target
|
api_url, model, prompt, article_id, target = job.api_url, job.model, job.prompt, job.article_id, job.target
|
||||||
try:
|
try:
|
||||||
client = PolzaClient(api_url, token)
|
client = PolzaClient(api_url, token)
|
||||||
try:
|
resolution = "4K"
|
||||||
generation_id = asyncio.run(client.create(model, prompt, "4K"))
|
fallback_used = False
|
||||||
except ImageGenerationError as exc:
|
|
||||||
if not exc.size_error:
|
|
||||||
raise
|
|
||||||
generation_id = asyncio.run(client.create(model, prompt, "1792x1024"))
|
|
||||||
image_url: str | None = None
|
image_url: str | None = None
|
||||||
|
while image_url is None:
|
||||||
|
try:
|
||||||
|
generation_id = asyncio.run(client.create(model, prompt, resolution))
|
||||||
|
except ImageGenerationError as exc:
|
||||||
|
if not exc.size_error or fallback_used:
|
||||||
|
raise
|
||||||
|
resolution, fallback_used = "1792x1024", True
|
||||||
|
continue
|
||||||
|
retry_with_fallback = False
|
||||||
for _ in range(120):
|
for _ in range(120):
|
||||||
with SessionLocal() as session:
|
with SessionLocal() as session:
|
||||||
job = session.get(ImageGenerationJob, job_id)
|
job = session.get(ImageGenerationJob, job_id)
|
||||||
|
|
@ -92,9 +97,15 @@ def generate_article_image(job_id: str) -> None:
|
||||||
if image_url:
|
if image_url:
|
||||||
break
|
break
|
||||||
if provider_status in {"failed", "error", "cancelled", "canceled"}:
|
if provider_status in {"failed", "error", "cancelled", "canceled"}:
|
||||||
raise ImageGenerationError("provider_error", "Polza не смогла создать изображение.")
|
provider_error = error_from_status(result)
|
||||||
|
if provider_error.size_error and not fallback_used:
|
||||||
|
resolution, fallback_used, retry_with_fallback = "1792x1024", True, True
|
||||||
|
break
|
||||||
|
raise provider_error
|
||||||
time.sleep(3)
|
time.sleep(3)
|
||||||
if not image_url:
|
if retry_with_fallback:
|
||||||
|
continue
|
||||||
|
if image_url is None:
|
||||||
raise ImageGenerationError("provider_timeout", "Polza не успела создать изображение.")
|
raise ImageGenerationError("provider_timeout", "Polza не успела создать изображение.")
|
||||||
with SessionLocal() as session:
|
with SessionLocal() as session:
|
||||||
job = session.get(ImageGenerationJob, job_id)
|
job = session.get(ImageGenerationJob, job_id)
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import unittest
|
import unittest
|
||||||
|
|
||||||
from app.image_generation import build_prompt, content_blocks, section_context
|
from app.image_generation import build_prompt, content_blocks, error_from_status, section_context
|
||||||
|
|
||||||
|
|
||||||
EDITOR_DATA = {
|
EDITOR_DATA = {
|
||||||
|
|
@ -45,6 +45,15 @@ class ImageGenerationPromptTest(unittest.TestCase):
|
||||||
self.assertIn("Факты второй части.", context)
|
self.assertIn("Факты второй части.", context)
|
||||||
self.assertIn("Заключительный вывод статьи.", context)
|
self.assertIn("Заключительный вывод статьи.", context)
|
||||||
|
|
||||||
|
def test_async_unsupported_4k_status_is_classified_for_fallback(self):
|
||||||
|
error = error_from_status({
|
||||||
|
"status": "failed",
|
||||||
|
"error": {"code": "BAD_REQUEST", "message": "image_size '4K' is not supported"},
|
||||||
|
})
|
||||||
|
|
||||||
|
self.assertTrue(error.size_error)
|
||||||
|
self.assertEqual(error.code, "provider_error")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue