여러 줄 주석이 설명보다 경위(예전·실측·지적)를 적고 있어 읽는 사람이 결론을 찾기 어려웠다. - ts·tsx·js·mjs·css·py 478개: 여러 줄 주석은 첫 문장 한 줄로, 과거형·날짜 문장은 삭제 - 주석 위치는 TypeScript 파서·파이썬 tokenize/ast 로 찾는다 — 문자열 안의 # · /* 는 건드리지 않는다 - eslint·ts·noqa·type: ignore 같은 지시 주석은 그대로 둔다 파이썬 275개 정리 전후 AST 동일, TS 298개 주석 뺀 토큰 동일(빈 JSX 주석 10곳만 차이). site·frontend·admin tsc, site vitest 105 passed Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
116 lines
4.6 KiB
Python
116 lines
4.6 KiB
Python
"""사진 분류 + alt 생성 — VISION 잡이 하는 일."""
|
|
import uuid
|
|
|
|
from common.database.db_session_manager import DB_SESSION_MNG
|
|
from common.database.model.models import place_photos, places
|
|
from common.enums import DBWRType, ErrorType, MediaStatus, PlaceCategory
|
|
from common.logger import LOG
|
|
from common.utils.gtime import GTime
|
|
from config.server_configs import external_api_config
|
|
from crud.media_crud import MediaCRUD
|
|
from crud.place_crud import PlaceCRUD
|
|
from services.external import gemini
|
|
from services.llm import provider
|
|
from common.job_errors import PermanentJobError
|
|
|
|
_media_crud = MediaCRUD()
|
|
_place_crud = PlaceCRUD()
|
|
|
|
|
|
class VisionAborted(PermanentJobError):
|
|
"""재시도해도 소용없는 중단 — 잡의 last_error 로 남는다."""
|
|
|
|
|
|
async def run_vision(job: dict) -> dict:
|
|
"""VISION 잡 핸들러."""
|
|
payload = job["payload"]
|
|
place_id = payload["place_id"]
|
|
owner_user_id = payload["owner_user_id"]
|
|
force = bool(payload.get("force"))
|
|
|
|
if not gemini.is_configured():
|
|
raise VisionAborted("API 키 미설정 — 사진 분석을 할 수 없다")
|
|
|
|
err, place = await DB_SESSION_MNG.execute_lambda(
|
|
places.DBType(),
|
|
DBWRType.DB_READ.value,
|
|
lambda s: _place_crud.get_place(s, uuid.UUID(owner_user_id), uuid.UUID(place_id)),
|
|
)
|
|
if err != ErrorType.SUCCESS or place is None:
|
|
raise VisionAborted(f"사업장을 찾을 수 없다: {place_id}")
|
|
|
|
# force 가 아니면 아직 분석 안 된 사진만 — 같은 사진을 다시 태우면 요금만 나간다.
|
|
list_err, rows = await DB_SESSION_MNG.execute_lambda(
|
|
place_photos.DBType(),
|
|
DBWRType.DB_READ.value,
|
|
lambda s: _media_crud.list_media(s, uuid.UUID(place_id), unlabeled_only=not force),
|
|
)
|
|
if list_err != ErrorType.SUCCESS:
|
|
raise VisionAborted(f"사진 조회 실패: {list_err.name}")
|
|
if not rows:
|
|
return {"place_id": place_id, "analyzed": 0, "note": "분석할 사진이 없다"}
|
|
|
|
# 객실·메뉴 이름을 힌트로 준다 — 라벨이 units 와 같은 어휘로 나오면 매칭이 쉬워진다.
|
|
unit_err, unit_rows = await DB_SESSION_MNG.execute_lambda(
|
|
place_photos.DBType(),
|
|
DBWRType.DB_READ.value,
|
|
lambda s: _place_crud.list_units(s, uuid.UUID(place_id)),
|
|
)
|
|
unit_names = [u.name for u in (unit_rows or [])] if unit_err == ErrorType.SUCCESS else []
|
|
unit_by_id = {u.unit_id: u.name for u in (unit_rows or [])} if unit_err == ErrorType.SUCCESS else {}
|
|
|
|
images = [
|
|
gemini.ImageInput(
|
|
origin_url=r.origin_url or r.url,
|
|
fetch_url=r.url,
|
|
unit_name_hint=unit_by_id.get(r.unit_id),
|
|
)
|
|
for r in rows
|
|
]
|
|
by_key = {(r.origin_url or r.url): r for r in rows}
|
|
|
|
threshold = external_api_config.vision_confidence_threshold
|
|
active_provider = provider.active()
|
|
model = (
|
|
external_api_config.openai_vision_model if active_provider.__name__.endswith("openai")
|
|
else external_api_config.gemini_vision_model
|
|
)
|
|
try:
|
|
results = await gemini.analyze_images(
|
|
images,
|
|
category=PlaceCategory(place.category),
|
|
unit_names=unit_names,
|
|
model=model,
|
|
confidence_threshold=threshold,
|
|
)
|
|
except gemini.GeminiNotConfigured as ex:
|
|
raise VisionAborted(str(ex)) from ex
|
|
|
|
now = GTime.UTC()
|
|
stat = {"place_id": place_id, "analyzed": len(rows), "approved": 0, "needs_review": 0, "failed": 0}
|
|
for result in results:
|
|
row = by_key.get(result.origin_url)
|
|
if row is None:
|
|
continue
|
|
if not result.ok:
|
|
# 분석 실패 — 사진은 그대로 두고 사람 확인 큐에 남긴다.
|
|
stat["failed"] += 1
|
|
continue
|
|
# 신뢰도 미달이면 라벨은 저장하되 승인 상태로 올리지 않는다.
|
|
approved = not result.needs_review
|
|
status = MediaStatus.APPROVED.value if approved else MediaStatus.PENDING_REVIEW.value
|
|
run_err, _rc = await DB_SESSION_MNG.execute_lambda_claim(
|
|
place_photos.DBType(),
|
|
lambda s, r=result, st=status: _media_crud.apply_vision(
|
|
s, by_key[r.origin_url].media_id, r.label, r.alt_text, r.confidence, st, now
|
|
),
|
|
)
|
|
if run_err != ErrorType.SUCCESS:
|
|
stat["failed"] += 1
|
|
continue
|
|
stat["approved" if approved else "needs_review"] += 1
|
|
|
|
LOG.i(f"[vision] place={place_id} {stat['analyzed']}장 → 자동반영 {stat['approved']} · "
|
|
f"확인필요 {stat['needs_review']} · 실패 {stat['failed']} (임계값 {threshold})")
|
|
return stat
|