from abc import ABC, abstractmethod from typing import Tuple from sqlalchemy import and_, func, or_, select, update from sqlalchemy.ext.asyncio import AsyncSession from common.database.db_session_manager import DB_SESSION_MNG from common.database.model.models import place_photos from common.enums import ErrorType, MediaStatus from common.logger import LOG from common.utils.gtime import GTime # 사진 CRUD. 항상 place_id 로 스코프한다. class IMediaCRUD(ABC): @abstractmethod async def list_media( self, cdb: AsyncSession, place_id, status=None, unlabeled_only=False, unit_id=None, alt_required=False ) -> Tuple[ErrorType, list]: pass @abstractmethod async def apply_vision(self, cdb: AsyncSession, media_id, label, alt_text, confidence, status, ts) -> Tuple[ErrorType, int]: pass @abstractmethod async def set_status(self, cdb: AsyncSession, place_id, media_id, status: int, ts) -> Tuple[ErrorType, int]: pass class MediaCRUD(IMediaCRUD): async def list_media( self, cdb: AsyncSession, place_id, status=None, unlabeled_only: bool = False, unit_id=None, alt_required: bool = False ) -> Tuple[ErrorType, list]: """사진 목록. unlabeled_only=True 면 아직 Vision 분석이 안 된 것만(재분석 비용 절약). ★ "분석 안 됨"의 기준은 **alt_text 가 비었는가**다. label 이 아니다. 수집 어댑터가 페이지에서 주운 캡션을 label 에 넣어 두기 때문에(base.CollectedMedia 주석: "Vision 이 확정하기 전의 후보 라벨"), label 로 판정하면 캡션이 있는 사진은 전부 '이미 분석됨'으로 건너뛴다 — 실제로 네이버에서 긁은 사진 10장이 통째로 그렇게 빠져 Vision 이 "분석할 사진이 없다"로 끝났고, alt 가 없어 발행도 못 했다. alt 는 Vision 만 채우고 발행 조건이기도 하므로 기준으로 삼기에 정확하다. unit_id 는 객실·메뉴 단위 사진만 추린다(빌더가 객실 카드에 붙일 사진을 고를 때). ★ alt_required=True 는 status 필터와 짝으로만 쓴다 — alt 가 빈 사진은 빌더가 렌더하지 않으므로(services/snapshot.py), '발행되면 실릴 것'을 물었을 때 승인만 보면 답이 틀린다.""" try: conditions = [place_photos.place_id == place_id, place_photos.deleted == False] # noqa: E712 if status is not None: conditions.append(place_photos.status == status) if unlabeled_only: conditions.append( or_(place_photos.alt_text.is_(None), func.btrim(place_photos.alt_text) == "") ) if unit_id is not None: conditions.append(place_photos.unit_id == unit_id) if alt_required: # 공백만 있는 alt 도 빌더에선 '없음'이다 — 같은 기준으로 거른다. conditions.append(place_photos.alt_text.is_not(None)) conditions.append(func.btrim(place_photos.alt_text) != "") query = select(place_photos).where(and_(*conditions)).order_by(place_photos.sort_order.asc(), place_photos.created_at.asc()) err_type, rows = await DB_SESSION_MNG.execute(cdb, query) return (err_type, list(rows) if err_type == ErrorType.SUCCESS else []) except Exception as ex: LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED, [] async def apply_vision(self, cdb: AsyncSession, media_id, label, alt_text, confidence, status: int, ts) -> Tuple[ErrorType, int]: """Vision 분석 결과를 반영한다. ★ 신뢰도가 낮으면 status 를 PENDING_REVIEW 로 남긴다 — 자동 반영하지 않는다. 라벨·alt 는 저장하되(사람이 보고 고칠 재료), 승인 상태로 올리지 않는 게 핵심이다.""" try: query = ( update(place_photos) .where(place_photos.media_id == media_id, place_photos.deleted == False) # noqa: E712 .values(label=label, alt_text=alt_text, vision_confidence=confidence, status=status, updated_at=ts) ) return await DB_SESSION_MNG.add_with_rowcount(cdb, query) except Exception as ex: LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED, 0 async def set_status(self, cdb: AsyncSession, place_id, media_id, status: int, ts) -> Tuple[ErrorType, int]: """사람이 사진을 승인/반려한다.""" try: query = ( update(place_photos) .where(place_photos.media_id == media_id, place_photos.place_id == place_id, place_photos.deleted == False) # noqa: E712 .values(status=status, updated_at=ts) ) return await DB_SESSION_MNG.add_with_rowcount(cdb, query) except Exception as ex: LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED, 0