사진 쪽은 MediaService 에 list_media 하나뿐이었다 — 쓰기 경로가 아예 없었고
빌더 화면에서도 보기만 됐다. 서비스·라우터부터 열고 도구를 붙였다.
- crud: set_sort_order / service: hide_media · set_primary
- POST .../media/{id}/hide · /primary — ★ 에이전트 전용 뒷문을 만들지 않는다.
그러면 빌더 화면이 그 기능을 못 쓰고 나중에 붙일 때 로직이 두 벌이 된다
- 도구 셋: list_photos(READ) · hide_photo · set_primary_photo(REVERSIBLE)
★ 대표 사진에 별도 칸을 두지 않았다. primary_media 가 '첫 장' 을 쓰고 목록이
ORDER BY sort_order 라, 지정은 sort_order 를 가장 작게 내리는 일이다 —
칸을 따로 두면 규칙이 둘이 되어 검색 결과의 그림과 화면 첫 장이 갈린다.
★ 내려도 지우지 않는다(REJECTED). origin_url·source_type 이 남아야 재게시
권리(DECISIONS 1-2) 결론이 났을 때 되짚을 수 있다.
★★ 업로드·교체는 만들지 않았다 — 미결 사항을 코드가 먼저 푸는 자리다.
테스트가 레지스트리에 upload·replace 가 없는지 실제로 검사한다.
test_agent_runtime 32 passed(사진 6건 추가).
전체 871 passed / 53 failed — 53 은 이번 변경 전과 동일. npm run lint 통과
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
117 lines
6.1 KiB
Python
117 lines
6.1 KiB
Python
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_sort_order(self, cdb: AsyncSession, place_id, media_id, sort_order: int, ts) -> Tuple[ErrorType, int]:
|
|
pass
|
|
|
|
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_sort_order(self, cdb: AsyncSession, place_id, media_id, sort_order: int, ts) -> Tuple[ErrorType, int]:
|
|
"""사진 순서를 바꾼다.
|
|
|
|
★ 목록이 `ORDER BY sort_order, created_at` 이고 대표 사진은 그 **첫 장**이다
|
|
(site_payload.primary_media). 그래서 '대표로 지정' 은 이 값을 가장 작게 만드는 일이다 —
|
|
별도의 is_primary 칸을 두지 않는 이유는, 두면 두 규칙(칸 · 순서)이 생겨
|
|
검색 결과에 뜨는 그림과 화면 첫 장이 갈릴 수 있기 때문이다."""
|
|
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(sort_order=sort_order, 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
|