Compare commits
4 Commits
cf1055bdf9
...
v0.1.43
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
47020fd649 | ||
|
|
88bbf3ca25 | ||
|
|
8152b71119 | ||
|
|
d6ee62230e |
18
CHANGELOG.md
18
CHANGELOG.md
@@ -6,6 +6,24 @@
|
||||
|
||||
## 2026-06-15
|
||||
|
||||
### 🎯 #356 영상-식당 관련도 LLM 평가 (v0.1.43)
|
||||
- DB: video_restaurants 컬럼 추가 (relevance/relevance_reason/relevance_evaluated_at) + idx_vr_relevance
|
||||
- VideoRelevanceService 신규 (#322 RestaurantVerifyService 패턴 모방, @Async verifyAsync/verify/verifyAll)
|
||||
- PipelineService.processExtract — linkVideoRestaurant 후 verifyAsync(linkId) 자동 트리거
|
||||
- GET /api/restaurants/{id}/videos: 기본 strong/unknown만 응답 (안전 기본값), ?include_weak=true 시 모두
|
||||
- AdminVideoRelevanceController 신규 (pending/all/{id}/evaluate/{id} PATCH)
|
||||
- 응답 매핑: relevance, relevance_reason 필드 동봉
|
||||
- 기존 1244 링크는 'unknown' 시작 → 어드민 백필로 점진 평가
|
||||
- 설계서: docs/design/356-video-relevance-llm/README.md
|
||||
- Refs: #356 (close)
|
||||
|
||||
### 🧹 #351 admin SSE 6곳 consumeSseStream 통일 (v0.1.42)
|
||||
- VideosPanel 4곳(bulkTranscript/Extract, rebuildVectors, remapCuisine, remapFoods)
|
||||
- RestaurantsPanel 2곳(bulkTabling, bulkCatchtable)
|
||||
- response.body?.getReader 직접 호출 0건 (lib/admin-utils.ts의 consumeSseStream 활용)
|
||||
- 149줄 삭제 → 74줄 압축, npm test 13/13 통과
|
||||
- Refs: #351 (close)
|
||||
|
||||
### 🧪 #343 Jest+RTL 인프라 + ARIA Tabs + remotePatterns (v0.1.40)
|
||||
- Jest 30 + jest-environment-jsdom + RTL + jest-dom matchers 도입
|
||||
- next/jest 자동 SWC 통합, jest.config.ts + jest.setup.ts (setupFilesAfterEnv)
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.tasteby.controller;
|
||||
|
||||
import com.tasteby.security.AuthUtil;
|
||||
import com.tasteby.service.RestaurantService;
|
||||
import com.tasteby.service.VideoRelevanceService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* #356 영상-식당 관련도 LLM 평가 어드민 API.
|
||||
* - 미평가 카운트 / 일괄 백필 / 단건 재평가 / 수동 토글
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/video-relevance")
|
||||
public class AdminVideoRelevanceController {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(AdminVideoRelevanceController.class);
|
||||
private static final Set<String> VALID = Set.of("strong", "weak", "incidental", "unknown");
|
||||
|
||||
private final RestaurantService restaurantService;
|
||||
private final VideoRelevanceService relevanceService;
|
||||
|
||||
public AdminVideoRelevanceController(RestaurantService restaurantService, VideoRelevanceService relevanceService) {
|
||||
this.restaurantService = restaurantService;
|
||||
this.relevanceService = relevanceService;
|
||||
}
|
||||
|
||||
@GetMapping("/pending")
|
||||
public Map<String, Object> pendingCount() {
|
||||
var admin = AuthUtil.requireAdmin();
|
||||
int n = restaurantService.countUnevaluatedLinks();
|
||||
log.info("[ADMIN] {} video-relevance pending: {}", admin.getSubject(), n);
|
||||
return Map.of("pending", n);
|
||||
}
|
||||
|
||||
@PostMapping("/all")
|
||||
public Map<String, Object> verifyAll(@RequestParam(defaultValue = "10") int batchSize) {
|
||||
var admin = AuthUtil.requireAdmin();
|
||||
log.info("[ADMIN] {} triggered video-relevance verifyAll(batchSize={})", admin.getSubject(), batchSize);
|
||||
int processed = relevanceService.verifyAll(batchSize);
|
||||
return Map.of("processed", processed);
|
||||
}
|
||||
|
||||
@PostMapping("/{linkId}/evaluate")
|
||||
public Map<String, Object> evaluateOne(@PathVariable String linkId) {
|
||||
var admin = AuthUtil.requireAdmin();
|
||||
log.info("[ADMIN] {} video-relevance evaluate({})", admin.getSubject(), linkId);
|
||||
relevanceService.verify(linkId);
|
||||
return Map.of("success", true, "linkId", linkId);
|
||||
}
|
||||
|
||||
@PatchMapping("/{linkId}")
|
||||
public Map<String, Object> setRelevance(@PathVariable String linkId, @RequestBody Map<String, Object> body) {
|
||||
var admin = AuthUtil.requireAdmin();
|
||||
Object relObj = body.get("relevance");
|
||||
if (!(relObj instanceof String relevance) || !VALID.contains(relevance)) {
|
||||
return Map.of("success", false, "error", "relevance must be one of strong|weak|incidental|unknown");
|
||||
}
|
||||
String reason = body.get("reason") instanceof String s ? s : "manual";
|
||||
restaurantService.updateLinkRelevance(linkId, relevance, reason);
|
||||
log.info("[ADMIN] {} manual relevance={} for link {}", admin.getSubject(), relevance, linkId);
|
||||
return Map.of("success", true, "linkId", linkId, "relevance", relevance);
|
||||
}
|
||||
}
|
||||
@@ -413,8 +413,10 @@ public class RestaurantController {
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/videos")
|
||||
public List<Map<String, Object>> videos(@PathVariable String id) {
|
||||
String key = cache.makeKey("restaurant_videos", id);
|
||||
public List<Map<String, Object>> videos(
|
||||
@PathVariable String id,
|
||||
@RequestParam(name = "include_weak", defaultValue = "false") boolean includeWeak) {
|
||||
String key = cache.makeKey("restaurant_videos", id, includeWeak ? "all" : "strong");
|
||||
String cached = cache.getRaw(key);
|
||||
if (cached != null) {
|
||||
try {
|
||||
@@ -423,7 +425,7 @@ public class RestaurantController {
|
||||
}
|
||||
var r = restaurantService.findById(id);
|
||||
if (r == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Restaurant not found");
|
||||
var result = restaurantService.findVideoLinks(id);
|
||||
var result = restaurantService.findVideoLinks(id, includeWeak);
|
||||
cache.set(key, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -28,9 +28,21 @@ public interface RestaurantMapper {
|
||||
|
||||
int countUnverified();
|
||||
|
||||
// #356 영상-식당 관련도
|
||||
void updateLinkRelevance(@Param("linkId") String linkId,
|
||||
@Param("relevance") String relevance,
|
||||
@Param("reason") String reason);
|
||||
|
||||
Map<String, Object> findLinkContext(@Param("linkId") String linkId);
|
||||
|
||||
List<Map<String, Object>> findUnevaluatedLinks(@Param("limit") int limit);
|
||||
|
||||
int countUnevaluatedLinks();
|
||||
|
||||
Restaurant findById(@Param("id") String id);
|
||||
|
||||
List<Map<String, Object>> findVideoLinks(@Param("restaurantId") String restaurantId);
|
||||
List<Map<String, Object>> findVideoLinks(@Param("restaurantId") String restaurantId,
|
||||
@Param("includeWeak") boolean includeWeak);
|
||||
|
||||
void insertRestaurant(Restaurant r);
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ public class PipelineService {
|
||||
private final VectorService vectorService;
|
||||
private final CacheService cacheService;
|
||||
private final RestaurantVerifyService verifyService;
|
||||
private final VideoRelevanceService relevanceService;
|
||||
|
||||
public PipelineService(YouTubeService youTubeService,
|
||||
ExtractorService extractorService,
|
||||
@@ -37,7 +38,8 @@ public class PipelineService {
|
||||
VideoService videoService,
|
||||
VectorService vectorService,
|
||||
CacheService cacheService,
|
||||
RestaurantVerifyService verifyService) {
|
||||
RestaurantVerifyService verifyService,
|
||||
VideoRelevanceService relevanceService) {
|
||||
this.youTubeService = youTubeService;
|
||||
this.extractorService = extractorService;
|
||||
this.geocodingService = geocodingService;
|
||||
@@ -46,6 +48,7 @@ public class PipelineService {
|
||||
this.vectorService = vectorService;
|
||||
this.cacheService = cacheService;
|
||||
this.verifyService = verifyService;
|
||||
this.relevanceService = relevanceService;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -145,13 +148,16 @@ public class PipelineService {
|
||||
evaluationJson = JsonUtil.toJson(s);
|
||||
}
|
||||
|
||||
restaurantService.linkVideoRestaurant(
|
||||
String linkId = restaurantService.linkVideoRestaurant(
|
||||
videoDbId, restId,
|
||||
foods instanceof List<?> ? (List<String>) foods : null,
|
||||
evaluationJson,
|
||||
guests instanceof List<?> ? (List<String>) guests : null
|
||||
);
|
||||
|
||||
// #356 — 신규 등록 직후 비동기 관련도 평가
|
||||
relevanceService.verifyAsync(linkId);
|
||||
|
||||
// Vector embeddings
|
||||
var chunks = VectorService.buildChunks(name, restData, title);
|
||||
if (!chunks.isEmpty()) {
|
||||
|
||||
@@ -77,7 +77,11 @@ public class RestaurantService {
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> findVideoLinks(String restaurantId) {
|
||||
var rows = mapper.findVideoLinks(restaurantId);
|
||||
return findVideoLinks(restaurantId, false);
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> findVideoLinks(String restaurantId, boolean includeWeak) {
|
||||
var rows = mapper.findVideoLinks(restaurantId, includeWeak);
|
||||
return rows.stream().map(row -> {
|
||||
var m = JsonUtil.lowerKeys(row);
|
||||
m.put("foods_mentioned", JsonUtil.parseStringList(m.get("foods_mentioned")));
|
||||
@@ -87,6 +91,26 @@ public class RestaurantService {
|
||||
}).toList();
|
||||
}
|
||||
|
||||
// #356 영상-식당 관련도
|
||||
public void updateLinkRelevance(String linkId, String relevance, String reason) {
|
||||
mapper.updateLinkRelevance(linkId, relevance, reason);
|
||||
}
|
||||
|
||||
public Map<String, Object> findLinkContext(String linkId) {
|
||||
var row = mapper.findLinkContext(linkId);
|
||||
return row != null ? JsonUtil.lowerKeys(row) : null;
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> findUnevaluatedLinks(int limit) {
|
||||
return mapper.findUnevaluatedLinks(limit).stream()
|
||||
.map(JsonUtil::lowerKeys)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public int countUnevaluatedLinks() {
|
||||
return mapper.countUnevaluatedLinks();
|
||||
}
|
||||
|
||||
public void update(String id, Map<String, Object> fields) {
|
||||
mapper.updateFields(id, fields);
|
||||
}
|
||||
@@ -138,12 +162,13 @@ public class RestaurantService {
|
||||
}
|
||||
}
|
||||
|
||||
public void linkVideoRestaurant(String videoId, String restaurantId, List<String> foods, String evaluation, List<String> guests) {
|
||||
public String linkVideoRestaurant(String videoId, String restaurantId, List<String> foods, String evaluation, List<String> guests) {
|
||||
String id = IdGenerator.newId();
|
||||
String foodsJson = foods != null ? JsonUtil.toJson(foods) : null;
|
||||
String guestsJson = guests != null ? JsonUtil.toJson(guests) : null;
|
||||
String evalJson = JsonUtil.normalizeEvaluation(evaluation);
|
||||
mapper.linkVideoRestaurant(id, videoId, restaurantId, foodsJson, evalJson, guestsJson);
|
||||
return id;
|
||||
}
|
||||
|
||||
public void updateCuisineType(String id, String cuisineType) {
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
package com.tasteby.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* #356 영상-식당 관련도 LLM 평가.
|
||||
* 설계서: docs/design/356-video-relevance-llm/README.md
|
||||
*
|
||||
* 신규 등록 시 자동 평가 + 어드민 백필. 결과는 video_restaurants.relevance에 저장.
|
||||
* - strong: 본격 다룸 (방문 리뷰, 메뉴 평가)
|
||||
* - weak: 잠깐 언급, 비교 대상
|
||||
* - incidental: 일반 토픽 중 단순 언급, 입점 전
|
||||
* - unknown: 미평가 or LLM 실패 (안전 기본값으로 표시 유지)
|
||||
*/
|
||||
@Service
|
||||
public class VideoRelevanceService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(VideoRelevanceService.class);
|
||||
private static final Set<String> VALID = Set.of("strong", "weak", "incidental", "unknown");
|
||||
private static final long BACKFILL_SLEEP_MS = 200;
|
||||
|
||||
private final RestaurantService restaurantService;
|
||||
private final OciGenAiService genAi;
|
||||
private final ObjectMapper jsonMapper = new ObjectMapper();
|
||||
|
||||
public VideoRelevanceService(RestaurantService restaurantService, OciGenAiService genAi) {
|
||||
this.restaurantService = restaurantService;
|
||||
this.genAi = genAi;
|
||||
}
|
||||
|
||||
@Async
|
||||
public void verifyAsync(String linkId) {
|
||||
try {
|
||||
verify(linkId);
|
||||
} catch (Exception e) {
|
||||
log.warn("verifyAsync failed for link {}: {}", linkId, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void verify(String linkId) {
|
||||
Map<String, Object> ctx = restaurantService.findLinkContext(linkId);
|
||||
if (ctx == null) return;
|
||||
VerifyResult result;
|
||||
try {
|
||||
String prompt = buildPrompt(ctx);
|
||||
String response = genAi.chat(prompt, 120);
|
||||
result = parseRelevance(response);
|
||||
} catch (Exception e) {
|
||||
log.warn("verify({}) LLM failed: {} — keeping unknown", linkId, e.getMessage());
|
||||
return;
|
||||
}
|
||||
restaurantService.updateLinkRelevance(linkId, result.relevance(), truncate(result.reason(), 120));
|
||||
}
|
||||
|
||||
public int verifyAll(int batchSize) {
|
||||
int total = 0;
|
||||
List<Map<String, Object>> batch;
|
||||
while (!(batch = restaurantService.findUnevaluatedLinks(batchSize)).isEmpty()) {
|
||||
for (Map<String, Object> row : batch) {
|
||||
String linkId = (String) row.get("link_id");
|
||||
if (linkId == null) continue;
|
||||
try {
|
||||
verify(linkId);
|
||||
} catch (Exception e) {
|
||||
log.warn("verifyAll({}) failed: {}", linkId, e.getMessage());
|
||||
}
|
||||
total++;
|
||||
try { Thread.sleep(BACKFILL_SLEEP_MS); } catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
return total;
|
||||
}
|
||||
}
|
||||
if (batch.size() < batchSize) break;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
// ---- pure helpers ----
|
||||
|
||||
String buildPrompt(Map<String, Object> ctx) {
|
||||
String foods = safeStr(ctx.get("foods_mentioned"));
|
||||
String evaluation = safeStr(ctx.get("evaluation"));
|
||||
return "다음 YouTube 영상이 이 식당을 어떻게 다루는지 판정하라.\n\n" +
|
||||
"식당명: " + safeStr(ctx.get("restaurant_name")) + "\n" +
|
||||
"주소: " + safeStr(ctx.get("address")) + "\n" +
|
||||
"음식 분류: " + safeStr(ctx.get("cuisine_type")) + "\n" +
|
||||
"언급된 음식: " + (foods.isEmpty() ? "(없음)" : foods) + "\n\n" +
|
||||
"영상 제목: " + safeStr(ctx.get("video_title")) + "\n" +
|
||||
"영상 채널: " + safeStr(ctx.get("channel_name")) + "\n" +
|
||||
"영상에 등장한 평가: " + (evaluation.isEmpty() ? "(없음)" : evaluation) + "\n\n" +
|
||||
"응답 형식(JSON만, 다른 텍스트 없이):\n" +
|
||||
"{\"relevance\": \"strong\"|\"weak\"|\"incidental\", \"reason\": \"20자 이내 한국어\"}\n\n" +
|
||||
"가이드:\n" +
|
||||
"- strong: 영상이 이 식당을 본격 다룸 (방문 리뷰, 메뉴 평가).\n" +
|
||||
"- weak: 잠깐 언급, 다른 식당과 비교 대상으로 등장.\n" +
|
||||
"- incidental: 일반 토픽 중 단순 언급, 식당 입점 전 영상.\n" +
|
||||
"- 판단 모호 시 strong (보수적 — 사용자에게 표시 유지).";
|
||||
}
|
||||
|
||||
private static final Pattern JSON_BLOCK = Pattern.compile("\\{[^{}]*\\}", Pattern.DOTALL);
|
||||
|
||||
VerifyResult parseRelevance(String raw) {
|
||||
if (raw == null) return VerifyResult.unknown();
|
||||
String trimmed = raw.trim();
|
||||
String json = (trimmed.startsWith("{") && trimmed.endsWith("}")) ? trimmed : null;
|
||||
if (json == null) {
|
||||
Matcher m = JSON_BLOCK.matcher(raw);
|
||||
if (m.find()) json = m.group();
|
||||
}
|
||||
if (json == null) return VerifyResult.unknown();
|
||||
try {
|
||||
JsonNode node = jsonMapper.readTree(json);
|
||||
String rel = node.path("relevance").asText("unknown").toLowerCase();
|
||||
if (!VALID.contains(rel)) rel = "unknown";
|
||||
String reason = node.path("reason").asText("");
|
||||
return new VerifyResult(rel, reason);
|
||||
} catch (Exception e) {
|
||||
return VerifyResult.unknown();
|
||||
}
|
||||
}
|
||||
|
||||
private static String safeStr(Object o) {
|
||||
return o == null ? "" : o.toString();
|
||||
}
|
||||
|
||||
private static String truncate(String s, int max) {
|
||||
return s == null ? null : (s.length() <= max ? s : s.substring(0, max));
|
||||
}
|
||||
|
||||
public record VerifyResult(String relevance, String reason) {
|
||||
public static VerifyResult unknown() { return new VerifyResult("unknown", "parse_failed"); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
-- #356 영상-식당 관련도 LLM 평가
|
||||
ALTER TABLE video_restaurants ADD (
|
||||
relevance VARCHAR2(16) DEFAULT 'unknown' NOT NULL,
|
||||
relevance_reason VARCHAR2(120),
|
||||
relevance_evaluated_at TIMESTAMP
|
||||
);
|
||||
CREATE INDEX idx_vr_relevance ON video_restaurants(relevance);
|
||||
@@ -69,14 +69,20 @@
|
||||
</select>
|
||||
|
||||
<select id="findVideoLinks" resultType="map">
|
||||
SELECT v.video_id, v.title, v.url,
|
||||
<!-- #356 — relevance 컬럼 SELECT + includeWeak 가드 -->
|
||||
SELECT vr.id AS link_id,
|
||||
v.video_id, v.title, v.url,
|
||||
TO_CHAR(v.published_at, 'YYYY-MM-DD"T"HH24:MI:SS') AS published_at,
|
||||
vr.foods_mentioned, vr.evaluation, vr.guests,
|
||||
vr.relevance, vr.relevance_reason,
|
||||
c.channel_name, c.channel_id
|
||||
FROM video_restaurants vr
|
||||
JOIN videos v ON v.id = vr.video_id
|
||||
JOIN channels c ON c.id = v.channel_id
|
||||
WHERE vr.restaurant_id = #{restaurantId}
|
||||
<if test="includeWeak == null or !includeWeak">
|
||||
AND vr.relevance IN ('strong', 'unknown')
|
||||
</if>
|
||||
ORDER BY v.published_at DESC
|
||||
</select>
|
||||
|
||||
@@ -315,4 +321,36 @@
|
||||
SELECT COUNT(*) FROM restaurants WHERE verified_at IS NULL
|
||||
</select>
|
||||
|
||||
<!-- ===== #356 영상-식당 관련도 ===== -->
|
||||
|
||||
<update id="updateLinkRelevance">
|
||||
UPDATE video_restaurants
|
||||
SET relevance = #{relevance},
|
||||
relevance_reason = #{reason,jdbcType=VARCHAR},
|
||||
relevance_evaluated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = #{linkId}
|
||||
</update>
|
||||
|
||||
<select id="findLinkContext" resultType="map">
|
||||
<!-- LLM 평가에 필요한 정보 -->
|
||||
SELECT vr.id AS link_id, vr.foods_mentioned, vr.evaluation,
|
||||
r.id AS restaurant_id, r.name AS restaurant_name, r.address, r.cuisine_type,
|
||||
v.title AS video_title, c.channel_name
|
||||
FROM video_restaurants vr
|
||||
JOIN restaurants r ON r.id = vr.restaurant_id
|
||||
JOIN videos v ON v.id = vr.video_id
|
||||
JOIN channels c ON c.id = v.channel_id
|
||||
WHERE vr.id = #{linkId}
|
||||
</select>
|
||||
|
||||
<select id="findUnevaluatedLinks" resultType="map">
|
||||
SELECT id AS link_id FROM video_restaurants
|
||||
WHERE relevance_evaluated_at IS NULL
|
||||
FETCH FIRST #{limit} ROWS ONLY
|
||||
</select>
|
||||
|
||||
<select id="countUnevaluatedLinks" resultType="int">
|
||||
SELECT COUNT(*) FROM video_restaurants WHERE relevance_evaluated_at IS NULL
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
|
||||
172
docs/design/356-video-relevance-llm/README.md
Normal file
172
docs/design/356-video-relevance-llm/README.md
Normal file
@@ -0,0 +1,172 @@
|
||||
# 설계서: 영상-식당 관련도 LLM 평가로 약한 매칭 자동 숨김 (#356)
|
||||
|
||||
> **상태**: Approved
|
||||
> **작성**: [AI] Architect · **최종수정**: 2026-06-15
|
||||
> **추적성** — Redmine: #356 · 유사 패턴: #322(식당 LLM 검증, 09-Done) · 부모 영역: #270(영상→식당 추출 파이프라인 현행화, 09-Done)
|
||||
> · 구현 파일: `backend-java/src/main/java/com/tasteby/service/VideoRelevanceService.java`(신규), `backend-java/src/main/resources/mybatis/mapper/RestaurantMapper.xml`, `backend-java/src/main/java/com/tasteby/service/RestaurantService.java`, `backend-java/src/main/java/com/tasteby/controller/AdminVideoRelevanceController.java`(신규), DB 마이그레이션 SQL
|
||||
> · 테스트: 본 범위 밖 (테스트 인프라 #343 도입됨, 후속에서 점진 확장)
|
||||
|
||||
## 1. 목적 (Why)
|
||||
|
||||
식당 상세에 연결된 영상 중 식당과 **본격적으로 관련 없는 약한 언급**(비교 대상, 일반 토픽 중 잠깐 언급, 식당 입점 전 영상 등)이 노이즈로 표시. 실제 케이스 — 파이브가이즈 강남의 영상 7개 중 3건이 약한 매칭(쉐이크쉑 비교 / 미국 비만율 일반 토픽 / 한국 입점 전 미국 여행). LLM 평가로 약한 매칭 자동 숨김.
|
||||
|
||||
## 2. 범위 (Scope)
|
||||
|
||||
- **포함**
|
||||
- `video_restaurants` 테이블에 `relevance`, `relevance_reason`, `relevance_evaluated_at` 컬럼 추가.
|
||||
- `VideoRelevanceService` 신규 — LLM 판정 + DB 반영 (`#322` 패턴 모방).
|
||||
- `PipelineService.processExtract` 완료 후 `verifyAsync(linkId)` 호출 — 신규 등록 자동 평가.
|
||||
- `GET /api/restaurants/{id}/videos`: 기본 `relevance = 'strong'`만 응답. `?include_weak=true` 시 모두 포함.
|
||||
- 어드민 API: 단건 재평가 / 일괄 백필 / 수동 토글.
|
||||
- **제외 (별도 후속)**
|
||||
- 어드민 UI(검증 칼럼 / 토글) — `#322`의 RestaurantsPanel UI와 같은 패턴으로 별도 후속.
|
||||
- 프론트 사용자 옵션 UI("약한 매칭도 보기" 토글) — 별도 후속.
|
||||
- LLM 비용 모니터링/메트릭 — 별도.
|
||||
|
||||
## 3. 인수조건
|
||||
|
||||
- [ ] `video_restaurants` 테이블에 `relevance VARCHAR2(16) DEFAULT 'unknown'`, `relevance_reason VARCHAR2(120)`, `relevance_evaluated_at TIMESTAMP` 컬럼 + `idx_vr_relevance` 인덱스.
|
||||
- [ ] 가능한 값: `strong | weak | incidental | unknown` (unknown = 미평가).
|
||||
- [ ] 신규 등록 시 60초 안에 `relevance_evaluated_at` 설정.
|
||||
- [ ] `GET /api/restaurants/{id}/videos` 기본 응답: `relevance IN ('strong','unknown')` (안전한 기본값 = 평가 실패 시 표시).
|
||||
- [ ] `?include_weak=true`: 모두 포함 + `relevance`, `relevance_reason` 필드 동봉.
|
||||
- [ ] 어드민 API:
|
||||
- `GET /api/admin/video-relevance/pending` → 미평가(unknown) 카운트
|
||||
- `POST /api/admin/video-relevance/all?batchSize=10` → 백필
|
||||
- `POST /api/admin/video-relevance/{linkId}/evaluate` → 단건 재평가
|
||||
- `PATCH /api/admin/video-relevance/{linkId}` → 수동 강제 토글 `{relevance, reason}`
|
||||
- [ ] LLM 호출 실패 시 `unknown` 유지 + 로그 (`#322`와 같은 안전 기본값).
|
||||
- [ ] 빌드/배포 회귀 없음.
|
||||
|
||||
## 4. 컨텍스트 & 제약
|
||||
|
||||
- 기존 `OciGenAiService.chat(prompt, maxTokens)` 재사용.
|
||||
- LLM 비용: 영상-식당 페어당 1회 단발. 현재 1,244건 → 백필 시 약 1,244 호출.
|
||||
- `video_restaurants`는 한 영상에 여러 식당, 한 식당에 여러 영상이 m:n 관계.
|
||||
- 같은 페어는 `relevance_evaluated_at`이 NULL 아니면 재평가 안 함 (캐시).
|
||||
|
||||
## 5. 아키텍처 개요
|
||||
|
||||
```
|
||||
PipelineService.processExtract (기존)
|
||||
│
|
||||
▼
|
||||
RestaurantService.linkVideoRestaurant (video_restaurants INSERT)
|
||||
│
|
||||
▼
|
||||
VideoRelevanceService.verifyAsync(linkId) ← #356 신규
|
||||
│ (비동기)
|
||||
▼
|
||||
OciGenAiService.chat(prompt, 120)
|
||||
│
|
||||
▼
|
||||
parseRelevance → { relevance: strong|weak|incidental, reason: string }
|
||||
│
|
||||
▼
|
||||
RestaurantMapper.updateRelevance(linkId, relevance, reason)
|
||||
│
|
||||
▼ (조회 시)
|
||||
RestaurantMapper.findVideoLinks(restaurantId, includeWeak)
|
||||
├ includeWeak=false (기본): WHERE relevance IN ('strong','unknown')
|
||||
└ includeWeak=true: 모두 + relevance/reason 필드 노출
|
||||
```
|
||||
|
||||
## 6. 데이터 모델
|
||||
|
||||
### DB 마이그레이션
|
||||
```sql
|
||||
ALTER TABLE video_restaurants ADD (
|
||||
relevance VARCHAR2(16) DEFAULT 'unknown' NOT NULL,
|
||||
relevance_reason VARCHAR2(120),
|
||||
relevance_evaluated_at TIMESTAMP
|
||||
);
|
||||
CREATE INDEX idx_vr_relevance ON video_restaurants(relevance);
|
||||
```
|
||||
|
||||
### 도메인 (`VideoRestaurantLink` 확장은 본 범위 밖 — findVideoLinks는 `resultType="map"`)
|
||||
응답 Map에 키 추가:
|
||||
- `relevance`: `"strong" | "weak" | "incidental" | "unknown"`
|
||||
- `relevance_reason`: `string | null`
|
||||
|
||||
### LLM 응답 스키마
|
||||
```json
|
||||
{
|
||||
"relevance": "strong" | "weak" | "incidental",
|
||||
"reason": "20자 이내"
|
||||
}
|
||||
```
|
||||
|
||||
## 7. 함수 명세
|
||||
|
||||
| 함수 | 책임 | 비고 |
|
||||
|---|---|---|
|
||||
| `VideoRelevanceService.verifyAsync(linkId)` | 비동기 트리거 | `#322`의 `RestaurantVerifyService.verifyAsync` 유사 |
|
||||
| `VideoRelevanceService.verify(linkId)` | 단건 검증 + DB 반영 | LLM 실패 시 unknown 유지 |
|
||||
| `VideoRelevanceService.verifyAll(batchSize)` | 백필 (식당당 200ms sleep) | |
|
||||
| `VideoRelevanceService.buildPrompt(...)` | 프롬프트 생성 | 식당명·주소·음식·영상 제목·평가 |
|
||||
| `VideoRelevanceService.parseRelevance(raw)` | LLM 응답 → DTO | 파싱 실패 시 unknown 안전 기본값 |
|
||||
| `RestaurantMapper.updateRelevance(linkId, rel, reason)` | DB 갱신 | |
|
||||
| `RestaurantMapper.findVideoLinks(restaurantId, includeWeak)` | 기존 SQL에 WHERE 조건 추가 | |
|
||||
| `AdminVideoRelevanceController` 신규 | 4개 admin endpoint | requireAdmin |
|
||||
|
||||
## 8. 흐름
|
||||
|
||||
### 신규 등록 자동 평가
|
||||
1. `PipelineService.processExtract` → `linkVideoRestaurant` → linkId 획득.
|
||||
2. `VideoRelevanceService.verifyAsync(linkId)` 호출(@Async).
|
||||
3. 별도 스레드: 영상/식당/평가 데이터 조회 → buildPrompt → LLM → parse → DB.
|
||||
|
||||
### 백필
|
||||
1. 어드민 `POST /api/admin/video-relevance/all` 호출.
|
||||
2. `WHERE relevance_evaluated_at IS NULL` 인 link 10개씩 조회 → 순차 검증.
|
||||
3. 식당당 200ms sleep (LLM rate 보호).
|
||||
|
||||
### 프롬프트 예시
|
||||
```
|
||||
다음 YouTube 영상이 이 식당을 어떻게 다루는지 판정하라.
|
||||
|
||||
식당명: {restaurantName}
|
||||
주소: {address}
|
||||
음식: {foodsMentioned}
|
||||
|
||||
영상 제목: {videoTitle}
|
||||
영상 채널: {channelName}
|
||||
영상에 등장한 평가 내용: {evaluation}
|
||||
|
||||
응답 형식(JSON만, 다른 텍스트 없이):
|
||||
{"relevance": "strong"|"weak"|"incidental", "reason": "20자 이내 한국어"}
|
||||
|
||||
가이드:
|
||||
- strong: 영상 본편이 이 식당을 본격 다룸. 방문 리뷰, 메뉴 평가 등.
|
||||
- weak: 영상에서 잠깐 언급, 비교 대상으로만 등장, 다른 식당의 일부로.
|
||||
- incidental: 식당 입점 전 영상에서 단순 언급, 일반 토픽(미국 비만, 환율 등)에서 잠깐.
|
||||
- 판단 모호 시 strong (보수적 — 사용자에게 표시 유지).
|
||||
```
|
||||
|
||||
## 9. 엣지케이스
|
||||
|
||||
- **LLM 응답 비-JSON**: parseRelevance → unknown 기본값.
|
||||
- **LLM 호출 실패**: unknown 유지 → 다음 백필 재시도.
|
||||
- **영상 데이터 누락(transcript 없음, evaluation 비어있음)**: 프롬프트에 "(미상)" 표기. LLM이 판정 어려우면 strong 보수적.
|
||||
- **동시성**: 같은 linkId verifyAsync 두 번 호출 → idempotent.
|
||||
- **삭제된 영상**: linkId 조회 결과 없으면 no-op.
|
||||
|
||||
## 10. 테스트 (수동)
|
||||
|
||||
- 파이브가이즈 강남 케이스 백필 → 7건 중 3건이 weak/incidental로 마킹되는지 확인.
|
||||
- 공개 API `/api/restaurants/{id}/videos` → 약한 매칭 제외 확인.
|
||||
- `?include_weak=true` → 모두 포함 확인.
|
||||
|
||||
## 11. 리스크 & 대안
|
||||
|
||||
- **선택**: `#322` 동일 패턴 + DB 마이그레이션.
|
||||
- **대안 A**: 사용자가 직접 "약한 매칭도 보기" 토글 → 사용자 결정 부담.
|
||||
- **대안 B**: 추출 단계에서 한 번에 판정 → 비용 ↓이지만 ExtractorService 비대.
|
||||
- **트레이드오프**: 단발 LLM 평가는 비용 합리적. false positive는 어드민 수동 토글 + `unknown` 안전 기본값으로 보완.
|
||||
|
||||
## 12. 미해결 질문
|
||||
|
||||
- 임계값(weak/incidental 둘 다 숨김 vs incidental만 숨김) — 현재는 둘 다 숨김.
|
||||
- 영상 자막 전체를 LLM에 보낼지 vs 평가 텍스트만 → 비용/정확도 트레이드오프. 현재는 evaluation만(짧음).
|
||||
- 사용자에게 "약한 매칭도 보기" UI → 별도 후속.
|
||||
- 어드민 UI — 별도 후속 (#322 패턴 모방).
|
||||
@@ -1,5 +1,5 @@
|
||||
"use client";
|
||||
import { getAdminToken } from "@/lib/admin-utils";
|
||||
import { getAdminToken, consumeSseStream } from "@/lib/admin-utils";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { api } from "@/lib/api";
|
||||
@@ -209,30 +209,19 @@ export function RestaurantsPanel({ isAdmin }: { isAdmin: boolean }) {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${getAdminToken()}` },
|
||||
});
|
||||
const reader = res.body!.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buf = "";
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buf += decoder.decode(value, { stream: true });
|
||||
const lines = buf.split("\n");
|
||||
buf = lines.pop() || "";
|
||||
for (const line of lines) {
|
||||
const m = line.match(/^data:(.+)$/);
|
||||
if (!m) continue;
|
||||
const evt = JSON.parse(m[1]);
|
||||
// #351 — consumeSseStream으로 통일
|
||||
await consumeSseStream(res, (raw) => {
|
||||
const evt = raw as { type: string; [k: string]: unknown };
|
||||
if (evt.type === "processing" || evt.type === "done" || evt.type === "notfound" || evt.type === "error") {
|
||||
setBulkTablingProgress(p => ({
|
||||
...p, current: evt.current, total: evt.total || p.total, name: evt.name,
|
||||
...p, current: evt.current as number, total: (evt.total as number) || p.total, name: evt.name as string,
|
||||
linked: evt.type === "done" ? p.linked + 1 : p.linked,
|
||||
notFound: (evt.type === "notfound" || evt.type === "error") ? p.notFound + 1 : p.notFound,
|
||||
}));
|
||||
} else if (evt.type === "complete") {
|
||||
alert(`완료! 연결: ${evt.linked}개, 미발견: ${evt.notFound}개`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (e) { alert("벌크 테이블링 실패: " + (e instanceof Error ? e.message : String(e))); }
|
||||
finally { setBulkTabling(false); load(); }
|
||||
}}
|
||||
@@ -287,30 +276,19 @@ export function RestaurantsPanel({ isAdmin }: { isAdmin: boolean }) {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${getAdminToken()}` },
|
||||
});
|
||||
const reader = res.body!.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buf = "";
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buf += decoder.decode(value, { stream: true });
|
||||
const lines = buf.split("\n");
|
||||
buf = lines.pop() || "";
|
||||
for (const line of lines) {
|
||||
const m = line.match(/^data:(.+)$/);
|
||||
if (!m) continue;
|
||||
const evt = JSON.parse(m[1]);
|
||||
// #351 — consumeSseStream으로 통일
|
||||
await consumeSseStream(res, (raw) => {
|
||||
const evt = raw as { type: string; [k: string]: unknown };
|
||||
if (evt.type === "processing" || evt.type === "done" || evt.type === "notfound" || evt.type === "error") {
|
||||
setBulkCatchtableProgress(p => ({
|
||||
...p, current: evt.current, total: evt.total || p.total, name: evt.name,
|
||||
...p, current: evt.current as number, total: (evt.total as number) || p.total, name: evt.name as string,
|
||||
linked: evt.type === "done" ? p.linked + 1 : p.linked,
|
||||
notFound: (evt.type === "notfound" || evt.type === "error") ? p.notFound + 1 : p.notFound,
|
||||
}));
|
||||
} else if (evt.type === "complete") {
|
||||
alert(`완료! 연결: ${evt.linked}개, 미발견: ${evt.notFound}개`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (e) { alert("벌크 캐치테이블 실패: " + (e instanceof Error ? e.message : String(e))); }
|
||||
finally { setBulkCatchtable(false); load(); }
|
||||
}}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"use client";
|
||||
import { getAdminToken } from "@/lib/admin-utils";
|
||||
import { getAdminToken, consumeSseStream } from "@/lib/admin-utils";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { api } from "@/lib/api";
|
||||
@@ -209,39 +209,25 @@ export function VideosPanel({ isAdmin }: { isAdmin: boolean }) {
|
||||
setBulkProgress(null);
|
||||
return;
|
||||
}
|
||||
const reader = resp.body?.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
if (!reader) { setRunning(false); return; }
|
||||
|
||||
let buf = "";
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buf += decoder.decode(value, { stream: true });
|
||||
const lines = buf.split("\n");
|
||||
buf = lines.pop() || "";
|
||||
for (const line of lines) {
|
||||
if (!line.startsWith("data: ")) continue;
|
||||
try {
|
||||
const ev = JSON.parse(line.slice(6));
|
||||
// #351 — consumeSseStream으로 통일
|
||||
await consumeSseStream(resp, (raw) => {
|
||||
const ev = raw as { type: string; [k: string]: unknown };
|
||||
if (ev.type === "processing") {
|
||||
setBulkProgress((p) => p ? { ...p, current: ev.index + 1, currentTitle: ev.title, waiting: undefined } : p);
|
||||
setBulkProgress((p) => p ? { ...p, current: (ev.index as number) + 1, currentTitle: ev.title as string, waiting: undefined } : p);
|
||||
} else if (ev.type === "wait") {
|
||||
setBulkProgress((p) => p ? { ...p, waiting: ev.delay } : p);
|
||||
setBulkProgress((p) => p ? { ...p, waiting: ev.delay as number } : p);
|
||||
} else if (ev.type === "done") {
|
||||
const detail = isTranscript
|
||||
? `${ev.source} / ${ev.length?.toLocaleString()}자`
|
||||
? `${ev.source} / ${(ev.length as number)?.toLocaleString()}자`
|
||||
: `${ev.restaurants}개 식당`;
|
||||
setBulkProgress((p) => p ? { ...p, results: [...p.results, { title: ev.title, detail }] } : p);
|
||||
setBulkProgress((p) => p ? { ...p, results: [...p.results, { title: ev.title as string, detail }] } : p);
|
||||
} else if (ev.type === "error") {
|
||||
setBulkProgress((p) => p ? { ...p, results: [...p.results, { title: ev.title, detail: ev.message, error: true }] } : p);
|
||||
setBulkProgress((p) => p ? { ...p, results: [...p.results, { title: ev.title as string, detail: ev.message as string, error: true }] } : p);
|
||||
} else if (ev.type === "complete") {
|
||||
setRunning(false);
|
||||
load();
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
});
|
||||
setRunning(false);
|
||||
load();
|
||||
} catch {
|
||||
@@ -264,30 +250,17 @@ export function VideosPanel({ isAdmin }: { isAdmin: boolean }) {
|
||||
setRebuildingVectors(false);
|
||||
return;
|
||||
}
|
||||
const reader = resp.body?.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
if (!reader) { setRebuildingVectors(false); return; }
|
||||
let buf = "";
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buf += decoder.decode(value, { stream: true });
|
||||
const lines = buf.split("\n");
|
||||
buf = lines.pop() || "";
|
||||
for (const line of lines) {
|
||||
if (!line.startsWith("data: ")) continue;
|
||||
try {
|
||||
const ev = JSON.parse(line.slice(6));
|
||||
// #351 — consumeSseStream으로 통일
|
||||
await consumeSseStream(resp, (raw) => {
|
||||
const ev = raw as { status?: string; type?: string; [k: string]: unknown };
|
||||
if (ev.status === "progress" || ev.type === "progress") {
|
||||
setVectorProgress({ phase: ev.phase, current: ev.current, total: ev.total, name: ev.name });
|
||||
setVectorProgress({ phase: ev.phase as string, current: ev.current as number, total: ev.total as number, name: ev.name as string });
|
||||
} else if (ev.status === "done" || ev.type === "done") {
|
||||
setVectorProgress({ phase: "done", current: ev.total, total: ev.total });
|
||||
setVectorProgress({ phase: "done", current: ev.total as number, total: ev.total as number });
|
||||
} else if (ev.type === "error") {
|
||||
alert(`벡터 재생성 오류: ${ev.message}`);
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
});
|
||||
setRebuildingVectors(false);
|
||||
} catch {
|
||||
setRebuildingVectors(false);
|
||||
@@ -309,30 +282,17 @@ export function VideosPanel({ isAdmin }: { isAdmin: boolean }) {
|
||||
setRemappingCuisine(false);
|
||||
return;
|
||||
}
|
||||
const reader = resp.body?.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
if (!reader) { setRemappingCuisine(false); return; }
|
||||
let buf = "";
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buf += decoder.decode(value, { stream: true });
|
||||
const lines = buf.split("\n");
|
||||
buf = lines.pop() || "";
|
||||
for (const line of lines) {
|
||||
if (!line.startsWith("data: ")) continue;
|
||||
try {
|
||||
const ev = JSON.parse(line.slice(6));
|
||||
// #351 — consumeSseStream으로 통일
|
||||
await consumeSseStream(resp, (raw) => {
|
||||
const ev = raw as { type: string; [k: string]: unknown };
|
||||
if (ev.type === "processing" || ev.type === "batch_done") {
|
||||
setRemapProgress({ current: ev.current, total: ev.total, updated: ev.updated || 0 });
|
||||
setRemapProgress({ current: ev.current as number, total: ev.total as number, updated: (ev.updated as number) || 0 });
|
||||
} else if (ev.type === "complete") {
|
||||
setRemapProgress({ current: ev.total, total: ev.total, updated: ev.updated });
|
||||
setRemapProgress({ current: ev.total as number, total: ev.total as number, updated: ev.updated as number });
|
||||
} else if (ev.type === "error") {
|
||||
alert(`재분류 오류: ${ev.message}`);
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
});
|
||||
setRemappingCuisine(false);
|
||||
} catch {
|
||||
setRemappingCuisine(false);
|
||||
@@ -354,30 +314,17 @@ export function VideosPanel({ isAdmin }: { isAdmin: boolean }) {
|
||||
setRemappingFoods(false);
|
||||
return;
|
||||
}
|
||||
const reader = resp.body?.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
if (!reader) { setRemappingFoods(false); return; }
|
||||
let buf = "";
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buf += decoder.decode(value, { stream: true });
|
||||
const lines = buf.split("\n");
|
||||
buf = lines.pop() || "";
|
||||
for (const line of lines) {
|
||||
if (!line.startsWith("data: ")) continue;
|
||||
try {
|
||||
const ev = JSON.parse(line.slice(6));
|
||||
// #351 — consumeSseStream으로 통일
|
||||
await consumeSseStream(resp, (raw) => {
|
||||
const ev = raw as { type: string; [k: string]: unknown };
|
||||
if (ev.type === "processing" || ev.type === "batch_done") {
|
||||
setFoodsProgress({ current: ev.current, total: ev.total, updated: ev.updated || 0 });
|
||||
setFoodsProgress({ current: ev.current as number, total: ev.total as number, updated: (ev.updated as number) || 0 });
|
||||
} else if (ev.type === "complete") {
|
||||
setFoodsProgress({ current: ev.total, total: ev.total, updated: ev.updated });
|
||||
setFoodsProgress({ current: ev.total as number, total: ev.total as number, updated: ev.updated as number });
|
||||
} else if (ev.type === "error") {
|
||||
alert(`메뉴 태그 재생성 오류: ${ev.message}`);
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
});
|
||||
setRemappingFoods(false);
|
||||
} catch {
|
||||
setRemappingFoods(false);
|
||||
|
||||
Reference in New Issue
Block a user