catch exception
This commit is contained in:
3
adapters/Exception.py
Normal file
3
adapters/Exception.py
Normal file
@@ -0,0 +1,3 @@
|
||||
class GoogleGenerationException(Exception):
|
||||
message: str
|
||||
pass
|
||||
@@ -7,6 +7,7 @@ from PIL import Image
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from adapters.Exception import GoogleGenerationException
|
||||
from models.enums import AspectRatios, Quality
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -85,6 +86,8 @@ class GoogleAdapter:
|
||||
),
|
||||
)
|
||||
)
|
||||
if response.parts is None and response.candidates[0].finish_reason is not None:
|
||||
raise GoogleGenerationException(f"Generation blocked in cause of {response.candidates[0].finish_reason.value}")
|
||||
|
||||
generated_images = []
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ class GenerationRequest(BaseModel):
|
||||
class GenerationResponse(BaseModel):
|
||||
id: str
|
||||
status: GenerationStatus
|
||||
failed_reason: Optional[str] = None
|
||||
linked_character_id: Optional[str] = None
|
||||
aspect_ratio: AspectRatios
|
||||
quality: Quality
|
||||
|
||||
@@ -5,6 +5,7 @@ from datetime import datetime, UTC
|
||||
from typing import List, Optional
|
||||
from io import BytesIO
|
||||
|
||||
from adapters.Exception import GoogleGenerationException
|
||||
from adapters.google_adapter import GoogleAdapter
|
||||
from api.models.GenerationRequest import GenerationRequest, GenerationResponse
|
||||
# Импортируйте ваши модели DAO, Asset, Generation корректно
|
||||
@@ -28,7 +29,7 @@ async def generate_image_task(
|
||||
Обертка для вызова синхронного метода Gemini в отдельном потоке.
|
||||
Возвращает список байтов сгенерированных изображений.
|
||||
"""
|
||||
|
||||
try :
|
||||
# Запускаем блокирующую операцию в отдельном потоке, чтобы не тормозить Event Loop
|
||||
generated_images_io: List[BytesIO] = await asyncio.to_thread(
|
||||
gemini.generate_image,
|
||||
@@ -37,7 +38,8 @@ async def generate_image_task(
|
||||
aspect_ratio=aspect_ratio,
|
||||
quality=quality,
|
||||
)
|
||||
|
||||
except GoogleGenerationException as e:
|
||||
raise e
|
||||
images_bytes = []
|
||||
if generated_images_io:
|
||||
for img_io in generated_images_io:
|
||||
@@ -154,6 +156,12 @@ class GenerationService:
|
||||
quality=generation.quality,
|
||||
gemini=self.gemini
|
||||
)
|
||||
except GoogleGenerationException as e:
|
||||
generation.status = GenerationStatus.FAILED
|
||||
generation.failed_reason = str(e.message)
|
||||
generation.updated_at = datetime.now(UTC)
|
||||
await self.dao.generations.update_generation(generation)
|
||||
raise
|
||||
except Exception as e:
|
||||
# Тут стоит добавить логирование ошибки
|
||||
logging.error(f"Generation failed: {e}")
|
||||
|
||||
@@ -16,6 +16,7 @@ class GenerationStatus(str, Enum):
|
||||
class Generation(BaseModel):
|
||||
id: Optional[str] = None
|
||||
status: GenerationStatus = GenerationStatus.RUNNING
|
||||
failed_reason: Optional[str] = None
|
||||
linked_character_id: Optional[str] = None
|
||||
aspect_ratio: AspectRatios
|
||||
quality: Quality
|
||||
|
||||
Reference in New Issue
Block a user