From aae461630893f2e36724be286fb1b90936686724 Mon Sep 17 00:00:00 2001 From: nstarikov Date: Tue, 11 Aug 2026 19:38:38 +0300 Subject: [PATCH] fix: retry Polza images after async size rejection --- dzen-assistant/app/image_generation.py | 28 ++++++--- dzen-assistant/app/worker.py | 61 +++++++++++-------- dzen-assistant/tests/test_image_generation.py | 11 +++- 3 files changed, 65 insertions(+), 35 deletions(-) diff --git a/dzen-assistant/app/image_generation.py b/dzen-assistant/app/image_generation.py index 256c3d3..d6a212f 100644 --- a/dzen-assistant/app/image_generation.py +++ b/dzen-assistant/app/image_generation.py @@ -159,22 +159,32 @@ def _safe_public_url(url: str) -> None: raise ImageGenerationError("download_failed", "Не удалось разрешить адрес изображения.") from exc -def error_from_response(response: httpx.Response) -> ImageGenerationError: - body = response.text[:1000].lower() - if response.status_code in {401, 403}: +def classify_provider_error(status_code: int, body: str) -> ImageGenerationError: + normalized = body[:4000].lower() + if status_code in {401, 403}: return ImageGenerationError("token_invalid", "Токен Polza отклонён.") - if response.status_code == 429: - return ImageGenerationError("rate_limited", "Превышен лимит запросов Polza.") - if "balance" in body or "insufficient" in body: + if status_code == 402 or "balance" in normalized or "insufficient" in normalized: 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", "Запрос отклонён политикой провайдера.") - 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", "Выбранная модель недоступна.") - 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) +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: def __init__(self, api_url: str, token: str) -> None: self.api_url, self.token = normalize_api_url(api_url), token diff --git a/dzen-assistant/app/worker.py b/dzen-assistant/app/worker.py index 2fca971..8935d9a 100644 --- a/dzen-assistant/app/worker.py +++ b/dzen-assistant/app/worker.py @@ -18,7 +18,7 @@ from app.config import get_settings from app.database import SessionLocal, init_db from app.models import AppSetting, Article, Frame, Source, Video 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 settings = get_settings() @@ -71,31 +71,42 @@ 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 try: client = PolzaClient(api_url, token) - try: - generation_id = asyncio.run(client.create(model, prompt, "4K")) - except ImageGenerationError as exc: - if not exc.size_error: - raise - generation_id = asyncio.run(client.create(model, prompt, "1792x1024")) + resolution = "4K" + fallback_used = False image_url: str | None = None - for _ in range(120): - with SessionLocal() as session: - job = session.get(ImageGenerationJob, job_id) - if not job: - return - job.status, job.progress, job.stage = "generating", max(job.progress, 20), "Генерируем изображение" - refresh_image_batch_status(session, job.batch) - session.commit() - result = asyncio.run(client.status(generation_id)) - provider_status = str(result.get("status") or (result.get("data") or {}).get("status") or "").lower() - image_url = extract_result_url(result) - if image_url: - break - if provider_status in {"failed", "error", "cancelled", "canceled"}: - raise ImageGenerationError("provider_error", "Polza не смогла создать изображение.") - time.sleep(3) - if not image_url: - raise ImageGenerationError("provider_timeout", "Polza не успела создать изображение.") + 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): + with SessionLocal() as session: + job = session.get(ImageGenerationJob, job_id) + if not job: + return + job.status, job.progress, job.stage = "generating", max(job.progress, 20), "Генерируем изображение" + refresh_image_batch_status(session, job.batch) + session.commit() + result = asyncio.run(client.status(generation_id)) + provider_status = str(result.get("status") or (result.get("data") or {}).get("status") or "").lower() + image_url = extract_result_url(result) + if image_url: + break + if provider_status in {"failed", "error", "cancelled", "canceled"}: + 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) + if retry_with_fallback: + continue + if image_url is None: + raise ImageGenerationError("provider_timeout", "Polza не успела создать изображение.") with SessionLocal() as session: job = session.get(ImageGenerationJob, job_id) if not job: diff --git a/dzen-assistant/tests/test_image_generation.py b/dzen-assistant/tests/test_image_generation.py index e8e86d7..eb783b6 100644 --- a/dzen-assistant/tests/test_image_generation.py +++ b/dzen-assistant/tests/test_image_generation.py @@ -1,6 +1,6 @@ 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 = { @@ -45,6 +45,15 @@ class ImageGenerationPromptTest(unittest.TestCase): 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__": unittest.main()