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 import genai
|
||||||
from google.genai import types
|
from google.genai import types
|
||||||
|
|
||||||
|
from adapters.Exception import GoogleGenerationException
|
||||||
from models.enums import AspectRatios, Quality
|
from models.enums import AspectRatios, Quality
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
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 = []
|
generated_images = []
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ class GenerationRequest(BaseModel):
|
|||||||
class GenerationResponse(BaseModel):
|
class GenerationResponse(BaseModel):
|
||||||
id: str
|
id: str
|
||||||
status: GenerationStatus
|
status: GenerationStatus
|
||||||
|
failed_reason: Optional[str] = None
|
||||||
linked_character_id: Optional[str] = None
|
linked_character_id: Optional[str] = None
|
||||||
aspect_ratio: AspectRatios
|
aspect_ratio: AspectRatios
|
||||||
quality: Quality
|
quality: Quality
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ from datetime import datetime, UTC
|
|||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
|
|
||||||
|
from adapters.Exception import GoogleGenerationException
|
||||||
from adapters.google_adapter import GoogleAdapter
|
from adapters.google_adapter import GoogleAdapter
|
||||||
from api.models.GenerationRequest import GenerationRequest, GenerationResponse
|
from api.models.GenerationRequest import GenerationRequest, GenerationResponse
|
||||||
# Импортируйте ваши модели DAO, Asset, Generation корректно
|
# Импортируйте ваши модели DAO, Asset, Generation корректно
|
||||||
@@ -28,16 +29,17 @@ async def generate_image_task(
|
|||||||
Обертка для вызова синхронного метода Gemini в отдельном потоке.
|
Обертка для вызова синхронного метода Gemini в отдельном потоке.
|
||||||
Возвращает список байтов сгенерированных изображений.
|
Возвращает список байтов сгенерированных изображений.
|
||||||
"""
|
"""
|
||||||
|
try :
|
||||||
# Запускаем блокирующую операцию в отдельном потоке, чтобы не тормозить Event Loop
|
# Запускаем блокирующую операцию в отдельном потоке, чтобы не тормозить Event Loop
|
||||||
generated_images_io: List[BytesIO] = await asyncio.to_thread(
|
generated_images_io: List[BytesIO] = await asyncio.to_thread(
|
||||||
gemini.generate_image,
|
gemini.generate_image,
|
||||||
prompt=prompt,
|
prompt=prompt,
|
||||||
images_list=media_group_bytes,
|
images_list=media_group_bytes,
|
||||||
aspect_ratio=aspect_ratio,
|
aspect_ratio=aspect_ratio,
|
||||||
quality=quality,
|
quality=quality,
|
||||||
)
|
)
|
||||||
|
except GoogleGenerationException as e:
|
||||||
|
raise e
|
||||||
images_bytes = []
|
images_bytes = []
|
||||||
if generated_images_io:
|
if generated_images_io:
|
||||||
for img_io in generated_images_io:
|
for img_io in generated_images_io:
|
||||||
@@ -154,6 +156,12 @@ class GenerationService:
|
|||||||
quality=generation.quality,
|
quality=generation.quality,
|
||||||
gemini=self.gemini
|
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:
|
except Exception as e:
|
||||||
# Тут стоит добавить логирование ошибки
|
# Тут стоит добавить логирование ошибки
|
||||||
logging.error(f"Generation failed: {e}")
|
logging.error(f"Generation failed: {e}")
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ class GenerationStatus(str, Enum):
|
|||||||
class Generation(BaseModel):
|
class Generation(BaseModel):
|
||||||
id: Optional[str] = None
|
id: Optional[str] = None
|
||||||
status: GenerationStatus = GenerationStatus.RUNNING
|
status: GenerationStatus = GenerationStatus.RUNNING
|
||||||
|
failed_reason: Optional[str] = None
|
||||||
linked_character_id: Optional[str] = None
|
linked_character_id: Optional[str] = None
|
||||||
aspect_ratio: AspectRatios
|
aspect_ratio: AspectRatios
|
||||||
quality: Quality
|
quality: Quality
|
||||||
|
|||||||
Reference in New Issue
Block a user