Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
47020fd649 | ||
|
|
88bbf3ca25 | ||
|
|
8152b71119 | ||
|
|
d6ee62230e | ||
|
|
cf1055bdf9 | ||
|
|
2580414790 | ||
|
|
730727a7a6 | ||
|
|
9ba905aad8 | ||
|
|
8c4b0c3e9a |
37
CHANGELOG.md
37
CHANGELOG.md
@@ -6,6 +6,43 @@
|
|||||||
|
|
||||||
## 2026-06-15
|
## 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)
|
||||||
|
- npm scripts: test, test:watch
|
||||||
|
- 샘플 테스트 3개 13/13 통과: i18n/config(5), Stars(5), admin-utils(4)
|
||||||
|
- MyReviewsList: role=tablist/tab/aria-selected/aria-controls/tabIndex + tabpanel
|
||||||
|
- next.config.ts remotePatterns: Google avatar + YouTube thumbnail/avatar
|
||||||
|
- 후속: 전체 컴포넌트 테스트 확장, 백엔드 JUnit, E2E(Playwright), CI 통합
|
||||||
|
- 설계서: docs/design/343-frontend-test-infra/README.md
|
||||||
|
- Refs: #343 (close)
|
||||||
|
|
||||||
|
### 🔤 #348 isNameSimilar 한국어 자모 + Sørensen-Dice (v0.1.38)
|
||||||
|
- HangulSimilarity 유틸 신규 (Unicode NFD 분해 + bigram Sørensen-Dice)
|
||||||
|
- RestaurantController.isNameSimilar 교체, 임계값 0.45
|
||||||
|
- 짧은 한국어 이름 매칭 정확도 향상 (예: "스타벅스 강남" vs "스타벅스 강남점")
|
||||||
|
- 후속 분리: #357(DDG→정식 API), #358(DTO+@Valid), #359(UNIQUE+데이터 정리)
|
||||||
|
- 설계서: docs/design/348-name-similarity/README.md
|
||||||
|
- Refs: #348 (close)
|
||||||
|
|
||||||
### 🌐 #352 i18n 뼈대 ko/en/ja/es (v0.1.37)
|
### 🌐 #352 i18n 뼈대 ko/en/ja/es (v0.1.37)
|
||||||
- next-intl 5.x 도입
|
- next-intl 5.x 도입
|
||||||
- src/i18n/{config,LocaleProvider} + src/messages/{ko,en,ja,es}.json (30 키)
|
- src/i18n/{config,LocaleProvider} + src/messages/{ko,en,ja,es}.json (30 키)
|
||||||
|
|||||||
@@ -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")
|
@GetMapping("/{id}/videos")
|
||||||
public List<Map<String, Object>> videos(@PathVariable String id) {
|
public List<Map<String, Object>> videos(
|
||||||
String key = cache.makeKey("restaurant_videos", id);
|
@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);
|
String cached = cache.getRaw(key);
|
||||||
if (cached != null) {
|
if (cached != null) {
|
||||||
try {
|
try {
|
||||||
@@ -423,7 +425,7 @@ public class RestaurantController {
|
|||||||
}
|
}
|
||||||
var r = restaurantService.findById(id);
|
var r = restaurantService.findById(id);
|
||||||
if (r == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Restaurant not found");
|
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);
|
cache.set(key, result);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,9 +28,21 @@ public interface RestaurantMapper {
|
|||||||
|
|
||||||
int countUnverified();
|
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);
|
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);
|
void insertRestaurant(Restaurant r);
|
||||||
|
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ public class PipelineService {
|
|||||||
private final VectorService vectorService;
|
private final VectorService vectorService;
|
||||||
private final CacheService cacheService;
|
private final CacheService cacheService;
|
||||||
private final RestaurantVerifyService verifyService;
|
private final RestaurantVerifyService verifyService;
|
||||||
|
private final VideoRelevanceService relevanceService;
|
||||||
|
|
||||||
public PipelineService(YouTubeService youTubeService,
|
public PipelineService(YouTubeService youTubeService,
|
||||||
ExtractorService extractorService,
|
ExtractorService extractorService,
|
||||||
@@ -37,7 +38,8 @@ public class PipelineService {
|
|||||||
VideoService videoService,
|
VideoService videoService,
|
||||||
VectorService vectorService,
|
VectorService vectorService,
|
||||||
CacheService cacheService,
|
CacheService cacheService,
|
||||||
RestaurantVerifyService verifyService) {
|
RestaurantVerifyService verifyService,
|
||||||
|
VideoRelevanceService relevanceService) {
|
||||||
this.youTubeService = youTubeService;
|
this.youTubeService = youTubeService;
|
||||||
this.extractorService = extractorService;
|
this.extractorService = extractorService;
|
||||||
this.geocodingService = geocodingService;
|
this.geocodingService = geocodingService;
|
||||||
@@ -46,6 +48,7 @@ public class PipelineService {
|
|||||||
this.vectorService = vectorService;
|
this.vectorService = vectorService;
|
||||||
this.cacheService = cacheService;
|
this.cacheService = cacheService;
|
||||||
this.verifyService = verifyService;
|
this.verifyService = verifyService;
|
||||||
|
this.relevanceService = relevanceService;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -145,13 +148,16 @@ public class PipelineService {
|
|||||||
evaluationJson = JsonUtil.toJson(s);
|
evaluationJson = JsonUtil.toJson(s);
|
||||||
}
|
}
|
||||||
|
|
||||||
restaurantService.linkVideoRestaurant(
|
String linkId = restaurantService.linkVideoRestaurant(
|
||||||
videoDbId, restId,
|
videoDbId, restId,
|
||||||
foods instanceof List<?> ? (List<String>) foods : null,
|
foods instanceof List<?> ? (List<String>) foods : null,
|
||||||
evaluationJson,
|
evaluationJson,
|
||||||
guests instanceof List<?> ? (List<String>) guests : null
|
guests instanceof List<?> ? (List<String>) guests : null
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// #356 — 신규 등록 직후 비동기 관련도 평가
|
||||||
|
relevanceService.verifyAsync(linkId);
|
||||||
|
|
||||||
// Vector embeddings
|
// Vector embeddings
|
||||||
var chunks = VectorService.buildChunks(name, restData, title);
|
var chunks = VectorService.buildChunks(name, restData, title);
|
||||||
if (!chunks.isEmpty()) {
|
if (!chunks.isEmpty()) {
|
||||||
|
|||||||
@@ -77,7 +77,11 @@ public class RestaurantService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public List<Map<String, Object>> findVideoLinks(String restaurantId) {
|
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 -> {
|
return rows.stream().map(row -> {
|
||||||
var m = JsonUtil.lowerKeys(row);
|
var m = JsonUtil.lowerKeys(row);
|
||||||
m.put("foods_mentioned", JsonUtil.parseStringList(m.get("foods_mentioned")));
|
m.put("foods_mentioned", JsonUtil.parseStringList(m.get("foods_mentioned")));
|
||||||
@@ -87,6 +91,26 @@ public class RestaurantService {
|
|||||||
}).toList();
|
}).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) {
|
public void update(String id, Map<String, Object> fields) {
|
||||||
mapper.updateFields(id, 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 id = IdGenerator.newId();
|
||||||
String foodsJson = foods != null ? JsonUtil.toJson(foods) : null;
|
String foodsJson = foods != null ? JsonUtil.toJson(foods) : null;
|
||||||
String guestsJson = guests != null ? JsonUtil.toJson(guests) : null;
|
String guestsJson = guests != null ? JsonUtil.toJson(guests) : null;
|
||||||
String evalJson = JsonUtil.normalizeEvaluation(evaluation);
|
String evalJson = JsonUtil.normalizeEvaluation(evaluation);
|
||||||
mapper.linkVideoRestaurant(id, videoId, restaurantId, foodsJson, evalJson, guestsJson);
|
mapper.linkVideoRestaurant(id, videoId, restaurantId, foodsJson, evalJson, guestsJson);
|
||||||
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void updateCuisineType(String id, String cuisineType) {
|
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>
|
||||||
|
|
||||||
<select id="findVideoLinks" resultType="map">
|
<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,
|
TO_CHAR(v.published_at, 'YYYY-MM-DD"T"HH24:MI:SS') AS published_at,
|
||||||
vr.foods_mentioned, vr.evaluation, vr.guests,
|
vr.foods_mentioned, vr.evaluation, vr.guests,
|
||||||
|
vr.relevance, vr.relevance_reason,
|
||||||
c.channel_name, c.channel_id
|
c.channel_name, c.channel_id
|
||||||
FROM video_restaurants vr
|
FROM video_restaurants vr
|
||||||
JOIN videos v ON v.id = vr.video_id
|
JOIN videos v ON v.id = vr.video_id
|
||||||
JOIN channels c ON c.id = v.channel_id
|
JOIN channels c ON c.id = v.channel_id
|
||||||
WHERE vr.restaurant_id = #{restaurantId}
|
WHERE vr.restaurant_id = #{restaurantId}
|
||||||
|
<if test="includeWeak == null or !includeWeak">
|
||||||
|
AND vr.relevance IN ('strong', 'unknown')
|
||||||
|
</if>
|
||||||
ORDER BY v.published_at DESC
|
ORDER BY v.published_at DESC
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
@@ -315,4 +321,36 @@
|
|||||||
SELECT COUNT(*) FROM restaurants WHERE verified_at IS NULL
|
SELECT COUNT(*) FROM restaurants WHERE verified_at IS NULL
|
||||||
</select>
|
</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>
|
</mapper>
|
||||||
|
|||||||
117
docs/design/343-frontend-test-infra/README.md
Normal file
117
docs/design/343-frontend-test-infra/README.md
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
# 설계서: RTL/Jest 인프라 + next/image + ARIA Tabs (#343)
|
||||||
|
|
||||||
|
> **상태**: Approved
|
||||||
|
> **작성**: [AI] Architect · **최종수정**: 2026-06-15
|
||||||
|
> **추적성** — Redmine: #343 · 부모: #281 (현행화 frontend-review-memo, 09-Done)
|
||||||
|
> · 구현 파일: `frontend/package.json`, `frontend/jest.config.ts` (신규), `frontend/jest.setup.ts` (신규), `frontend/next.config.ts`, `frontend/__tests__/*` (신규), `frontend/src/components/MyReviewsList.tsx`, `frontend/src/components/ReviewSection.tsx`
|
||||||
|
> · 테스트: 본 이슈가 테스트 인프라 자체를 도입
|
||||||
|
|
||||||
|
## 1. 목적 (Why)
|
||||||
|
|
||||||
|
본 프로젝트는 지금까지 자동화된 단위 테스트가 0건. 누적된 "후속 테스트" 항목이 12+개(StatsService/CacheService/SearchService/Stars/HangulSimilarity 등)이며, 그동안 분리된 후속 이슈를 처리할 인프라가 없어 모두 보류 상태. 본 이슈에서 Jest + RTL 인프라 도입 + next/image 적용 + ARIA Tabs 보강.
|
||||||
|
|
||||||
|
## 2. 범위 (Scope)
|
||||||
|
|
||||||
|
- **포함**
|
||||||
|
- Jest 30 + `next/jest` 자동 설정 + `@testing-library/react` + `@testing-library/jest-dom`.
|
||||||
|
- `jest.config.ts`, `jest.setup.ts`, `package.json scripts: test, test:watch`.
|
||||||
|
- 샘플 테스트 3개 — 가장 안전한 순수 함수/단순 컴포넌트로 인프라 검증:
|
||||||
|
- `Stars` 컴포넌트 렌더 + 별점 표시
|
||||||
|
- 기존 `HangulSimilarity` (#348) — 자모/유사도
|
||||||
|
- `BotDetector` (#337) — 봇 UA 패턴
|
||||||
|
- `next.config.ts` `images.remotePatterns`에 Google avatar 도메인(`lh3.googleusercontent.com`) + YouTube thumbnail(`i.ytimg.com`).
|
||||||
|
- `ReviewSection`/`MyReviewsList`의 `<img>` 일부를 `next/image` 또는 명시적 eslint-disable로 정리.
|
||||||
|
- `MyReviewsList` 탭에 WAI-ARIA Tabs 패턴(role=tablist/tab/aria-selected/aria-controls).
|
||||||
|
- **제외 (후속)**
|
||||||
|
- 백엔드 JUnit 테스트 인프라 (별도 큰 작업).
|
||||||
|
- E2E (Playwright) 도입.
|
||||||
|
- CI 통합 (GitHub Actions 또는 OCI DevOps).
|
||||||
|
- 모든 컴포넌트 테스트 — 점진적으로 추가.
|
||||||
|
- 모든 `<img>` → `next/image` 전수 교체 — 점진적.
|
||||||
|
|
||||||
|
## 3. 인수조건
|
||||||
|
|
||||||
|
- [ ] `npm test`가 단일 명령으로 동작 (0건 → 샘플 3개 통과).
|
||||||
|
- [ ] `npm run build`가 회귀 없이 통과.
|
||||||
|
- [ ] `next.config.ts`에 `remotePatterns` 설정.
|
||||||
|
- [ ] `ReviewSection`의 user_avatar_url `<img>`에 `next/image` 또는 eslint-disable 주석.
|
||||||
|
- [ ] `MyReviewsList` 탭이 `role="tablist"`/`role="tab"`/`aria-selected`/`aria-controls`/`tabIndex` 설정.
|
||||||
|
|
||||||
|
## 4. 컨텍스트 & 제약
|
||||||
|
|
||||||
|
- Next.js 16.1.6 + Turbopack.
|
||||||
|
- `next/jest`는 SWC/Babel 자동 통합. Turbopack 빌드와는 분리(테스트만 Jest 별도).
|
||||||
|
- Pretendard/Geist 폰트는 `next/font/local` 사용 → 테스트에선 mock 불필요.
|
||||||
|
- 패널 분리(#329)로 admin 영역은 단위 테스트 도입 더 쉬워짐.
|
||||||
|
|
||||||
|
## 5. 아키텍처 개요
|
||||||
|
|
||||||
|
```
|
||||||
|
frontend/
|
||||||
|
├── package.json
|
||||||
|
│ └── scripts: test, test:watch
|
||||||
|
├── jest.config.ts (next/jest createNextJestConfig 사용)
|
||||||
|
├── jest.setup.ts (@testing-library/jest-dom 확장 matchers)
|
||||||
|
├── __tests__/
|
||||||
|
│ ├── Stars.test.tsx
|
||||||
|
│ ├── HangulSimilarity.test.ts (자체 구현은 backend Java, TS 포팅은 미적용 → 다른 순수 함수로 대체)
|
||||||
|
│ └── BotDetector.test.ts (마찬가지 — backend → TS 동등 포팅 불가)
|
||||||
|
└── (대안) 프론트 측 순수 함수:
|
||||||
|
├── lib/cuisine-icons.ts 의 getPhosphorCuisineIcon
|
||||||
|
├── components/Stars 의 0.5 단위 렌더
|
||||||
|
└── i18n/config.ts 의 isLocale/detectBrowserLocale
|
||||||
|
```
|
||||||
|
|
||||||
|
→ 백엔드 Java 코드는 TS 테스트로 검증 불가. 프론트 측 순수 함수 3개로 대체:
|
||||||
|
- `Stars` 렌더 (RTL component test)
|
||||||
|
- `i18n/config.ts` `isLocale` (pure)
|
||||||
|
- `i18n/config.ts` `detectBrowserLocale` (navigator mock)
|
||||||
|
|
||||||
|
## 6. 데이터 모델
|
||||||
|
|
||||||
|
`__tests__/*.test.{tsx,ts}` — Jest 표준 컨벤션.
|
||||||
|
|
||||||
|
## 7. 함수 명세
|
||||||
|
|
||||||
|
| 단위 | 책임 | 비고 |
|
||||||
|
|------|------|------|
|
||||||
|
| `jest.config.ts` | `createJestConfig(customConfig)` + moduleNameMapper `@/*` | next/jest |
|
||||||
|
| `jest.setup.ts` | `import "@testing-library/jest-dom"` | 확장 matchers |
|
||||||
|
| `Stars.test.tsx` | 별점 0/2.5/5 렌더, aria-label 확인 | RTL |
|
||||||
|
| `i18n/config.test.ts` | isLocale/detectBrowserLocale | navigator mock |
|
||||||
|
| `MyReviewsList` Tabs 패치 | tablist/tab/aria-selected | role + aria |
|
||||||
|
| `ReviewSection` img → eslint-disable | 최소 변경 | next/image는 후속 |
|
||||||
|
|
||||||
|
## 8. 흐름
|
||||||
|
|
||||||
|
1. `npm i -D jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom @testing-library/user-event @types/jest`.
|
||||||
|
2. `jest.config.ts` + `jest.setup.ts` 작성.
|
||||||
|
3. `package.json`에 `"test": "jest"` + `"test:watch": "jest --watch"` 추가.
|
||||||
|
4. `__tests__/`에 3개 샘플 테스트.
|
||||||
|
5. `next.config.ts`에 `remotePatterns` 추가.
|
||||||
|
6. `MyReviewsList` Tabs ARIA 보강.
|
||||||
|
7. `ReviewSection`의 `<img>` 라인에 `// eslint-disable-next-line @next/next/no-img-element` (next/image 전환은 후속).
|
||||||
|
8. `npm test` 통과 → `npm run build` 통과.
|
||||||
|
|
||||||
|
## 9. 엣지케이스
|
||||||
|
|
||||||
|
- **Turbopack vs Jest**: 무관 (테스트는 별도 SWC 컴파일).
|
||||||
|
- **CSS modules / globals.css import**: jest.config.ts의 moduleNameMapper로 `\\.(css|scss)$` → `identity-obj-proxy` 대신 next/jest가 자동 처리.
|
||||||
|
- **Next.js Server Components**: 본 프로젝트는 모두 `"use client"` 컴포넌트라 RTL이 통상 동작.
|
||||||
|
|
||||||
|
## 10. 테스트
|
||||||
|
|
||||||
|
자기 자신 — `npm test`가 통과해야 본 이슈 완료.
|
||||||
|
|
||||||
|
## 11. 리스크 & 대안
|
||||||
|
|
||||||
|
- **선택**: `next/jest` + RTL. Next.js 공식 권장.
|
||||||
|
- **대안 A**: Vitest — 더 빠르지만 Next.js 공식 가이드 부재, 본 프로젝트 규모에서 차이 작음.
|
||||||
|
- **대안 B**: Playwright Component Testing — 더 무겁고 E2E 통합 안 됨.
|
||||||
|
- **트레이드오프**: Jest 30 + RTL은 React 19에 호환. 의존성 부담은 dev-only.
|
||||||
|
|
||||||
|
## 12. 미해결 질문
|
||||||
|
|
||||||
|
- CI(테스트 자동 실행) — 본 이슈 범위 밖. OCI DevOps Build Pipeline은 ARM64 미지원 → GitHub Actions 또는 Gitea Actions 후속.
|
||||||
|
- 백엔드 JUnit 테스트 인프라 — 별도 큰 이슈.
|
||||||
|
- E2E (Playwright) — 별도.
|
||||||
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 패턴 모방).
|
||||||
36
frontend/__tests__/Stars.test.tsx
Normal file
36
frontend/__tests__/Stars.test.tsx
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
/**
|
||||||
|
* #343 — Stars 컴포넌트 렌더 테스트.
|
||||||
|
*/
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import Stars from "@/components/Stars";
|
||||||
|
|
||||||
|
describe("Stars", () => {
|
||||||
|
it("renders 5 star slots", () => {
|
||||||
|
const { container } = render(<Stars rating={3} />);
|
||||||
|
// 빈 별 5개 (text-gray-300 클래스 갖는 span)
|
||||||
|
const emptyStars = container.querySelectorAll("span.text-gray-300");
|
||||||
|
expect(emptyStars.length).toBe(5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows aria-label with rating", () => {
|
||||||
|
render(<Stars rating={4.5} />);
|
||||||
|
expect(screen.getByLabelText("4.5점")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("clamps rating to 0~5", () => {
|
||||||
|
render(<Stars rating={-1} />);
|
||||||
|
expect(screen.getByLabelText("0점")).toBeInTheDocument();
|
||||||
|
render(<Stars rating={10} />);
|
||||||
|
expect(screen.getByLabelText("5점")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows number when showNumber + rating > 0", () => {
|
||||||
|
const { container } = render(<Stars rating={3.5} showNumber />);
|
||||||
|
expect(container.textContent).toContain("3.5");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not show number when rating is 0 even with showNumber", () => {
|
||||||
|
const { container } = render(<Stars rating={0} showNumber />);
|
||||||
|
expect(container.textContent).not.toContain("0");
|
||||||
|
});
|
||||||
|
});
|
||||||
28
frontend/__tests__/admin-utils.test.ts
Normal file
28
frontend/__tests__/admin-utils.test.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
/**
|
||||||
|
* #343 — admin-utils 순수 함수 단위 테스트.
|
||||||
|
*/
|
||||||
|
import { getAdminToken, authHeaders } from "@/lib/admin-utils";
|
||||||
|
|
||||||
|
describe("admin-utils", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
localStorage.clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("getAdminToken returns null when not set", () => {
|
||||||
|
expect(getAdminToken()).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("getAdminToken returns stored token", () => {
|
||||||
|
localStorage.setItem("tasteby_token", "abc123");
|
||||||
|
expect(getAdminToken()).toBe("abc123");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("authHeaders is empty when no token", () => {
|
||||||
|
expect(authHeaders()).toEqual({});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("authHeaders includes Bearer when token set", () => {
|
||||||
|
localStorage.setItem("tasteby_token", "xyz");
|
||||||
|
expect(authHeaders()).toEqual({ Authorization: "Bearer xyz" });
|
||||||
|
});
|
||||||
|
});
|
||||||
42
frontend/__tests__/i18n-config.test.ts
Normal file
42
frontend/__tests__/i18n-config.test.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
/**
|
||||||
|
* #343 — i18n/config 순수 함수 단위 테스트.
|
||||||
|
*/
|
||||||
|
import { isLocale, detectBrowserLocale, DEFAULT_LOCALE } from "@/i18n/config";
|
||||||
|
|
||||||
|
describe("i18n/config.isLocale", () => {
|
||||||
|
it("returns true for supported locales", () => {
|
||||||
|
expect(isLocale("ko")).toBe(true);
|
||||||
|
expect(isLocale("en")).toBe(true);
|
||||||
|
expect(isLocale("ja")).toBe(true);
|
||||||
|
expect(isLocale("es")).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns false for unsupported / null / undefined", () => {
|
||||||
|
expect(isLocale("fr")).toBe(false);
|
||||||
|
expect(isLocale("zh")).toBe(false);
|
||||||
|
expect(isLocale(null)).toBe(false);
|
||||||
|
expect(isLocale(undefined)).toBe(false);
|
||||||
|
expect(isLocale("")).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("i18n/config.detectBrowserLocale", () => {
|
||||||
|
// jsdom의 navigator.language는 기본 'en-US'
|
||||||
|
it("returns supported locale from navigator.language", () => {
|
||||||
|
Object.defineProperty(navigator, "language", { value: "en-US", configurable: true });
|
||||||
|
expect(detectBrowserLocale()).toBe("en");
|
||||||
|
Object.defineProperty(navigator, "language", { value: "ko-KR", configurable: true });
|
||||||
|
expect(detectBrowserLocale()).toBe("ko");
|
||||||
|
Object.defineProperty(navigator, "language", { value: "ja", configurable: true });
|
||||||
|
expect(detectBrowserLocale()).toBe("ja");
|
||||||
|
Object.defineProperty(navigator, "language", { value: "es-MX", configurable: true });
|
||||||
|
expect(detectBrowserLocale()).toBe("es");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to DEFAULT_LOCALE for unsupported", () => {
|
||||||
|
Object.defineProperty(navigator, "language", { value: "fr-FR", configurable: true });
|
||||||
|
expect(detectBrowserLocale()).toBe(DEFAULT_LOCALE);
|
||||||
|
Object.defineProperty(navigator, "language", { value: "zh-CN", configurable: true });
|
||||||
|
expect(detectBrowserLocale()).toBe(DEFAULT_LOCALE);
|
||||||
|
});
|
||||||
|
});
|
||||||
21
frontend/jest.config.ts
Normal file
21
frontend/jest.config.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
// #343 — Jest 설정. next/jest로 SWC 자동 통합.
|
||||||
|
|
||||||
|
import type { Config } from "jest";
|
||||||
|
import nextJest from "next/jest.js";
|
||||||
|
|
||||||
|
const createJestConfig = nextJest({
|
||||||
|
// 테스트 환경의 Next.js 앱 루트
|
||||||
|
dir: "./",
|
||||||
|
});
|
||||||
|
|
||||||
|
const customConfig: Config = {
|
||||||
|
// jest-dom matchers는 setupFilesAfterEnv로 등록 (Jest framework 로드 후)
|
||||||
|
setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
|
||||||
|
testEnvironment: "jsdom",
|
||||||
|
moduleNameMapper: {
|
||||||
|
"^@/(.*)$": "<rootDir>/src/$1",
|
||||||
|
},
|
||||||
|
testPathIgnorePatterns: ["<rootDir>/.next/", "<rootDir>/node_modules/"],
|
||||||
|
};
|
||||||
|
|
||||||
|
export default createJestConfig(customConfig);
|
||||||
2
frontend/jest.setup.ts
Normal file
2
frontend/jest.setup.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
// #343 — Jest setup. @testing-library/jest-dom matchers 확장.
|
||||||
|
import "@testing-library/jest-dom";
|
||||||
@@ -2,6 +2,14 @@ import type { NextConfig } from "next";
|
|||||||
|
|
||||||
const nextConfig: NextConfig = {
|
const nextConfig: NextConfig = {
|
||||||
output: "standalone",
|
output: "standalone",
|
||||||
|
// #343 — 외부 이미지 도메인 허용 (next/image)
|
||||||
|
images: {
|
||||||
|
remotePatterns: [
|
||||||
|
{ protocol: "https", hostname: "lh3.googleusercontent.com" }, // Google avatar
|
||||||
|
{ protocol: "https", hostname: "i.ytimg.com" }, // YouTube thumbnail
|
||||||
|
{ protocol: "https", hostname: "yt3.ggpht.com" }, // YouTube channel avatar
|
||||||
|
],
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export default nextConfig;
|
export default nextConfig;
|
||||||
|
|||||||
4349
frontend/package-lock.json
generated
4349
frontend/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -6,7 +6,9 @@
|
|||||||
"dev": "next dev",
|
"dev": "next dev",
|
||||||
"build": "next build",
|
"build": "next build",
|
||||||
"start": "next start",
|
"start": "next start",
|
||||||
"lint": "eslint"
|
"lint": "eslint",
|
||||||
|
"test": "jest",
|
||||||
|
"test:watch": "jest --watch"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@phosphor-icons/react": "^2.1.10",
|
"@phosphor-icons/react": "^2.1.10",
|
||||||
@@ -22,11 +24,17 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@tailwindcss/postcss": "^4",
|
"@tailwindcss/postcss": "^4",
|
||||||
|
"@testing-library/jest-dom": "^6.9.1",
|
||||||
|
"@testing-library/react": "^16.3.2",
|
||||||
|
"@testing-library/user-event": "^14.6.1",
|
||||||
|
"@types/jest": "^30.0.0",
|
||||||
"@types/node": "^20",
|
"@types/node": "^20",
|
||||||
"@types/react": "^19",
|
"@types/react": "^19",
|
||||||
"@types/react-dom": "^19",
|
"@types/react-dom": "^19",
|
||||||
"eslint": "^9",
|
"eslint": "^9",
|
||||||
"eslint-config-next": "16.1.6",
|
"eslint-config-next": "16.1.6",
|
||||||
|
"jest": "^30.4.2",
|
||||||
|
"jest-environment-jsdom": "^30.4.1",
|
||||||
"tailwindcss": "^4",
|
"tailwindcss": "^4",
|
||||||
"typescript": "^5"
|
"typescript": "^5"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
"use client";
|
"use client";
|
||||||
import { getAdminToken } from "@/lib/admin-utils";
|
import { getAdminToken, consumeSseStream } from "@/lib/admin-utils";
|
||||||
|
|
||||||
import { useCallback, useEffect, useState } from "react";
|
import { useCallback, useEffect, useState } from "react";
|
||||||
import { api } from "@/lib/api";
|
import { api } from "@/lib/api";
|
||||||
@@ -209,30 +209,19 @@ export function RestaurantsPanel({ isAdmin }: { isAdmin: boolean }) {
|
|||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { Authorization: `Bearer ${getAdminToken()}` },
|
headers: { Authorization: `Bearer ${getAdminToken()}` },
|
||||||
});
|
});
|
||||||
const reader = res.body!.getReader();
|
// #351 — consumeSseStream으로 통일
|
||||||
const decoder = new TextDecoder();
|
await consumeSseStream(res, (raw) => {
|
||||||
let buf = "";
|
const evt = raw as { type: string; [k: string]: unknown };
|
||||||
while (true) {
|
if (evt.type === "processing" || evt.type === "done" || evt.type === "notfound" || evt.type === "error") {
|
||||||
const { done, value } = await reader.read();
|
setBulkTablingProgress(p => ({
|
||||||
if (done) break;
|
...p, current: evt.current as number, total: (evt.total as number) || p.total, name: evt.name as string,
|
||||||
buf += decoder.decode(value, { stream: true });
|
linked: evt.type === "done" ? p.linked + 1 : p.linked,
|
||||||
const lines = buf.split("\n");
|
notFound: (evt.type === "notfound" || evt.type === "error") ? p.notFound + 1 : p.notFound,
|
||||||
buf = lines.pop() || "";
|
}));
|
||||||
for (const line of lines) {
|
} else if (evt.type === "complete") {
|
||||||
const m = line.match(/^data:(.+)$/);
|
alert(`완료! 연결: ${evt.linked}개, 미발견: ${evt.notFound}개`);
|
||||||
if (!m) continue;
|
|
||||||
const evt = JSON.parse(m[1]);
|
|
||||||
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,
|
|
||||||
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))); }
|
} catch (e) { alert("벌크 테이블링 실패: " + (e instanceof Error ? e.message : String(e))); }
|
||||||
finally { setBulkTabling(false); load(); }
|
finally { setBulkTabling(false); load(); }
|
||||||
}}
|
}}
|
||||||
@@ -287,30 +276,19 @@ export function RestaurantsPanel({ isAdmin }: { isAdmin: boolean }) {
|
|||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { Authorization: `Bearer ${getAdminToken()}` },
|
headers: { Authorization: `Bearer ${getAdminToken()}` },
|
||||||
});
|
});
|
||||||
const reader = res.body!.getReader();
|
// #351 — consumeSseStream으로 통일
|
||||||
const decoder = new TextDecoder();
|
await consumeSseStream(res, (raw) => {
|
||||||
let buf = "";
|
const evt = raw as { type: string; [k: string]: unknown };
|
||||||
while (true) {
|
if (evt.type === "processing" || evt.type === "done" || evt.type === "notfound" || evt.type === "error") {
|
||||||
const { done, value } = await reader.read();
|
setBulkCatchtableProgress(p => ({
|
||||||
if (done) break;
|
...p, current: evt.current as number, total: (evt.total as number) || p.total, name: evt.name as string,
|
||||||
buf += decoder.decode(value, { stream: true });
|
linked: evt.type === "done" ? p.linked + 1 : p.linked,
|
||||||
const lines = buf.split("\n");
|
notFound: (evt.type === "notfound" || evt.type === "error") ? p.notFound + 1 : p.notFound,
|
||||||
buf = lines.pop() || "";
|
}));
|
||||||
for (const line of lines) {
|
} else if (evt.type === "complete") {
|
||||||
const m = line.match(/^data:(.+)$/);
|
alert(`완료! 연결: ${evt.linked}개, 미발견: ${evt.notFound}개`);
|
||||||
if (!m) continue;
|
|
||||||
const evt = JSON.parse(m[1]);
|
|
||||||
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,
|
|
||||||
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))); }
|
} catch (e) { alert("벌크 캐치테이블 실패: " + (e instanceof Error ? e.message : String(e))); }
|
||||||
finally { setBulkCatchtable(false); load(); }
|
finally { setBulkCatchtable(false); load(); }
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
"use client";
|
"use client";
|
||||||
import { getAdminToken } from "@/lib/admin-utils";
|
import { getAdminToken, consumeSseStream } from "@/lib/admin-utils";
|
||||||
|
|
||||||
import { useCallback, useEffect, useState } from "react";
|
import { useCallback, useEffect, useState } from "react";
|
||||||
import { api } from "@/lib/api";
|
import { api } from "@/lib/api";
|
||||||
@@ -209,39 +209,25 @@ export function VideosPanel({ isAdmin }: { isAdmin: boolean }) {
|
|||||||
setBulkProgress(null);
|
setBulkProgress(null);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const reader = resp.body?.getReader();
|
// #351 — consumeSseStream으로 통일
|
||||||
const decoder = new TextDecoder();
|
await consumeSseStream(resp, (raw) => {
|
||||||
if (!reader) { setRunning(false); return; }
|
const ev = raw as { type: string; [k: string]: unknown };
|
||||||
|
if (ev.type === "processing") {
|
||||||
let buf = "";
|
setBulkProgress((p) => p ? { ...p, current: (ev.index as number) + 1, currentTitle: ev.title as string, waiting: undefined } : p);
|
||||||
while (true) {
|
} else if (ev.type === "wait") {
|
||||||
const { done, value } = await reader.read();
|
setBulkProgress((p) => p ? { ...p, waiting: ev.delay as number } : p);
|
||||||
if (done) break;
|
} else if (ev.type === "done") {
|
||||||
buf += decoder.decode(value, { stream: true });
|
const detail = isTranscript
|
||||||
const lines = buf.split("\n");
|
? `${ev.source} / ${(ev.length as number)?.toLocaleString()}자`
|
||||||
buf = lines.pop() || "";
|
: `${ev.restaurants}개 식당`;
|
||||||
for (const line of lines) {
|
setBulkProgress((p) => p ? { ...p, results: [...p.results, { title: ev.title as string, detail }] } : p);
|
||||||
if (!line.startsWith("data: ")) continue;
|
} else if (ev.type === "error") {
|
||||||
try {
|
setBulkProgress((p) => p ? { ...p, results: [...p.results, { title: ev.title as string, detail: ev.message as string, error: true }] } : p);
|
||||||
const ev = JSON.parse(line.slice(6));
|
} else if (ev.type === "complete") {
|
||||||
if (ev.type === "processing") {
|
setRunning(false);
|
||||||
setBulkProgress((p) => p ? { ...p, current: ev.index + 1, currentTitle: ev.title, waiting: undefined } : p);
|
load();
|
||||||
} else if (ev.type === "wait") {
|
|
||||||
setBulkProgress((p) => p ? { ...p, waiting: ev.delay } : p);
|
|
||||||
} else if (ev.type === "done") {
|
|
||||||
const detail = isTranscript
|
|
||||||
? `${ev.source} / ${ev.length?.toLocaleString()}자`
|
|
||||||
: `${ev.restaurants}개 식당`;
|
|
||||||
setBulkProgress((p) => p ? { ...p, results: [...p.results, { title: ev.title, detail }] } : p);
|
|
||||||
} else if (ev.type === "error") {
|
|
||||||
setBulkProgress((p) => p ? { ...p, results: [...p.results, { title: ev.title, detail: ev.message, error: true }] } : p);
|
|
||||||
} else if (ev.type === "complete") {
|
|
||||||
setRunning(false);
|
|
||||||
load();
|
|
||||||
}
|
|
||||||
} catch { /* ignore */ }
|
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
setRunning(false);
|
setRunning(false);
|
||||||
load();
|
load();
|
||||||
} catch {
|
} catch {
|
||||||
@@ -264,30 +250,17 @@ export function VideosPanel({ isAdmin }: { isAdmin: boolean }) {
|
|||||||
setRebuildingVectors(false);
|
setRebuildingVectors(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const reader = resp.body?.getReader();
|
// #351 — consumeSseStream으로 통일
|
||||||
const decoder = new TextDecoder();
|
await consumeSseStream(resp, (raw) => {
|
||||||
if (!reader) { setRebuildingVectors(false); return; }
|
const ev = raw as { status?: string; type?: string; [k: string]: unknown };
|
||||||
let buf = "";
|
if (ev.status === "progress" || ev.type === "progress") {
|
||||||
while (true) {
|
setVectorProgress({ phase: ev.phase as string, current: ev.current as number, total: ev.total as number, name: ev.name as string });
|
||||||
const { done, value } = await reader.read();
|
} else if (ev.status === "done" || ev.type === "done") {
|
||||||
if (done) break;
|
setVectorProgress({ phase: "done", current: ev.total as number, total: ev.total as number });
|
||||||
buf += decoder.decode(value, { stream: true });
|
} else if (ev.type === "error") {
|
||||||
const lines = buf.split("\n");
|
alert(`벡터 재생성 오류: ${ev.message}`);
|
||||||
buf = lines.pop() || "";
|
|
||||||
for (const line of lines) {
|
|
||||||
if (!line.startsWith("data: ")) continue;
|
|
||||||
try {
|
|
||||||
const ev = JSON.parse(line.slice(6));
|
|
||||||
if (ev.status === "progress" || ev.type === "progress") {
|
|
||||||
setVectorProgress({ phase: ev.phase, current: ev.current, total: ev.total, name: ev.name });
|
|
||||||
} else if (ev.status === "done" || ev.type === "done") {
|
|
||||||
setVectorProgress({ phase: "done", current: ev.total, total: ev.total });
|
|
||||||
} else if (ev.type === "error") {
|
|
||||||
alert(`벡터 재생성 오류: ${ev.message}`);
|
|
||||||
}
|
|
||||||
} catch { /* ignore */ }
|
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
setRebuildingVectors(false);
|
setRebuildingVectors(false);
|
||||||
} catch {
|
} catch {
|
||||||
setRebuildingVectors(false);
|
setRebuildingVectors(false);
|
||||||
@@ -309,30 +282,17 @@ export function VideosPanel({ isAdmin }: { isAdmin: boolean }) {
|
|||||||
setRemappingCuisine(false);
|
setRemappingCuisine(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const reader = resp.body?.getReader();
|
// #351 — consumeSseStream으로 통일
|
||||||
const decoder = new TextDecoder();
|
await consumeSseStream(resp, (raw) => {
|
||||||
if (!reader) { setRemappingCuisine(false); return; }
|
const ev = raw as { type: string; [k: string]: unknown };
|
||||||
let buf = "";
|
if (ev.type === "processing" || ev.type === "batch_done") {
|
||||||
while (true) {
|
setRemapProgress({ current: ev.current as number, total: ev.total as number, updated: (ev.updated as number) || 0 });
|
||||||
const { done, value } = await reader.read();
|
} else if (ev.type === "complete") {
|
||||||
if (done) break;
|
setRemapProgress({ current: ev.total as number, total: ev.total as number, updated: ev.updated as number });
|
||||||
buf += decoder.decode(value, { stream: true });
|
} else if (ev.type === "error") {
|
||||||
const lines = buf.split("\n");
|
alert(`재분류 오류: ${ev.message}`);
|
||||||
buf = lines.pop() || "";
|
|
||||||
for (const line of lines) {
|
|
||||||
if (!line.startsWith("data: ")) continue;
|
|
||||||
try {
|
|
||||||
const ev = JSON.parse(line.slice(6));
|
|
||||||
if (ev.type === "processing" || ev.type === "batch_done") {
|
|
||||||
setRemapProgress({ current: ev.current, total: ev.total, updated: ev.updated || 0 });
|
|
||||||
} else if (ev.type === "complete") {
|
|
||||||
setRemapProgress({ current: ev.total, total: ev.total, updated: ev.updated });
|
|
||||||
} else if (ev.type === "error") {
|
|
||||||
alert(`재분류 오류: ${ev.message}`);
|
|
||||||
}
|
|
||||||
} catch { /* ignore */ }
|
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
setRemappingCuisine(false);
|
setRemappingCuisine(false);
|
||||||
} catch {
|
} catch {
|
||||||
setRemappingCuisine(false);
|
setRemappingCuisine(false);
|
||||||
@@ -354,30 +314,17 @@ export function VideosPanel({ isAdmin }: { isAdmin: boolean }) {
|
|||||||
setRemappingFoods(false);
|
setRemappingFoods(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const reader = resp.body?.getReader();
|
// #351 — consumeSseStream으로 통일
|
||||||
const decoder = new TextDecoder();
|
await consumeSseStream(resp, (raw) => {
|
||||||
if (!reader) { setRemappingFoods(false); return; }
|
const ev = raw as { type: string; [k: string]: unknown };
|
||||||
let buf = "";
|
if (ev.type === "processing" || ev.type === "batch_done") {
|
||||||
while (true) {
|
setFoodsProgress({ current: ev.current as number, total: ev.total as number, updated: (ev.updated as number) || 0 });
|
||||||
const { done, value } = await reader.read();
|
} else if (ev.type === "complete") {
|
||||||
if (done) break;
|
setFoodsProgress({ current: ev.total as number, total: ev.total as number, updated: ev.updated as number });
|
||||||
buf += decoder.decode(value, { stream: true });
|
} else if (ev.type === "error") {
|
||||||
const lines = buf.split("\n");
|
alert(`메뉴 태그 재생성 오류: ${ev.message}`);
|
||||||
buf = lines.pop() || "";
|
|
||||||
for (const line of lines) {
|
|
||||||
if (!line.startsWith("data: ")) continue;
|
|
||||||
try {
|
|
||||||
const ev = JSON.parse(line.slice(6));
|
|
||||||
if (ev.type === "processing" || ev.type === "batch_done") {
|
|
||||||
setFoodsProgress({ current: ev.current, total: ev.total, updated: ev.updated || 0 });
|
|
||||||
} else if (ev.type === "complete") {
|
|
||||||
setFoodsProgress({ current: ev.total, total: ev.total, updated: ev.updated });
|
|
||||||
} else if (ev.type === "error") {
|
|
||||||
alert(`메뉴 태그 재생성 오류: ${ev.message}`);
|
|
||||||
}
|
|
||||||
} catch { /* ignore */ }
|
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
setRemappingFoods(false);
|
setRemappingFoods(false);
|
||||||
} catch {
|
} catch {
|
||||||
setRemappingFoods(false);
|
setRemappingFoods(false);
|
||||||
|
|||||||
@@ -41,8 +41,14 @@ export default function MyReviewsList({
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex gap-1 border-b">
|
{/* #343 — WAI-ARIA Tabs 패턴 */}
|
||||||
|
<div role="tablist" aria-label="내 활동" className="flex gap-1 border-b">
|
||||||
<button
|
<button
|
||||||
|
role="tab"
|
||||||
|
id="tab-reviews"
|
||||||
|
aria-selected={tab === "reviews"}
|
||||||
|
aria-controls="panel-reviews"
|
||||||
|
tabIndex={tab === "reviews" ? 0 : -1}
|
||||||
onClick={() => setTab("reviews")}
|
onClick={() => setTab("reviews")}
|
||||||
className={`px-3 py-1.5 text-sm font-medium border-b-2 transition-colors ${
|
className={`px-3 py-1.5 text-sm font-medium border-b-2 transition-colors ${
|
||||||
tab === "reviews"
|
tab === "reviews"
|
||||||
@@ -54,6 +60,11 @@ export default function MyReviewsList({
|
|||||||
리뷰 ({reviews.length})
|
리뷰 ({reviews.length})
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
|
role="tab"
|
||||||
|
id="tab-memos"
|
||||||
|
aria-selected={tab === "memos"}
|
||||||
|
aria-controls="panel-memos"
|
||||||
|
tabIndex={tab === "memos" ? 0 : -1}
|
||||||
onClick={() => setTab("memos")}
|
onClick={() => setTab("memos")}
|
||||||
className={`px-3 py-1.5 text-sm font-medium border-b-2 transition-colors ${
|
className={`px-3 py-1.5 text-sm font-medium border-b-2 transition-colors ${
|
||||||
tab === "memos"
|
tab === "memos"
|
||||||
@@ -67,7 +78,8 @@ export default function MyReviewsList({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{tab === "reviews" ? (
|
{tab === "reviews" ? (
|
||||||
reviews.length === 0 ? (
|
<div role="tabpanel" id="panel-reviews" aria-labelledby="tab-reviews">
|
||||||
|
{reviews.length === 0 ? (
|
||||||
<p className="text-sm text-gray-500 py-8 text-center">
|
<p className="text-sm text-gray-500 py-8 text-center">
|
||||||
아직 작성한 리뷰가 없습니다.
|
아직 작성한 리뷰가 없습니다.
|
||||||
</p>
|
</p>
|
||||||
@@ -100,9 +112,11 @@ export default function MyReviewsList({
|
|||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)
|
)}
|
||||||
|
</div>
|
||||||
) : (
|
) : (
|
||||||
memos.length === 0 ? (
|
<div role="tabpanel" id="panel-memos" aria-labelledby="tab-memos">
|
||||||
|
{memos.length === 0 ? (
|
||||||
<p className="text-sm text-gray-500 py-8 text-center">
|
<p className="text-sm text-gray-500 py-8 text-center">
|
||||||
아직 작성한 메모가 없습니다.
|
아직 작성한 메모가 없습니다.
|
||||||
</p>
|
</p>
|
||||||
@@ -137,7 +151,8 @@ export default function MyReviewsList({
|
|||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)
|
)}
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -257,6 +257,9 @@ export default function ReviewSection({ restaurantId }: ReviewSectionProps) {
|
|||||||
<>
|
<>
|
||||||
<div className="flex items-center gap-2 mb-1">
|
<div className="flex items-center gap-2 mb-1">
|
||||||
{review.user_avatar_url && (
|
{review.user_avatar_url && (
|
||||||
|
// eslint-disable-next-line @next/next/no-img-element
|
||||||
|
// #343 — Google avatar URL은 remotePatterns에 추가됨.
|
||||||
|
// next/image 전환은 SSR/lazy 효과 미미한 5x5 아바타라 후속에서 일괄 적용.
|
||||||
<img
|
<img
|
||||||
src={review.user_avatar_url}
|
src={review.user_avatar_url}
|
||||||
alt=""
|
alt=""
|
||||||
|
|||||||
Reference in New Issue
Block a user