Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions docs/recommendation-photo-length.md
Original file line number Diff line number Diff line change
@@ -1,19 +1,28 @@
# 사진과 추천 길이 연결
# 사진·시술기록과 추천 연결

최신 시술의 AFTER 사진을 서버 내부 ONNX 모델로 분할하고, 얼굴 대비 머리 영역의 끝 위치를 이용해 보수적으로 길이를 추정한다. 사용자 사진을 외부 AI로 보내지 않으며 성별을 추론하지 않는다. 기존 색상 균일도·대칭·볼륨·거칠기 분석과는 별도 기능이다. 그 4개 지표의 분석 엔진을 이 모델로 대체하지 않는다.

- 직접 입력한 머리 길이보다 긴 길이로 자동 변경하지 않는다. 사진 업로드 후 갱신한 프로필은 우선한다.
- 시술 날짜가 같으면 기록 생성 시각으로 최신 기록을 정하며, 그 기록에서 가장 최근 업로드한 AFTER 파일을 사용한다. 기존 사진을 남겨둔 추가 업로드도 새 입력으로 반영한다.
- 최신 시술에 AFTER 사진이 없으면 예전 시술 사진으로 대체하지 않는다. BEFORE/OTHER는 현재 길이 판단에 사용하지 않는다.
- 최신 시술에 AFTER 사진이 없으면 해당 기록의 OTHER 사진을 사용한다. 둘 다 없으면 과거 기록 사진으로 대체하지 않는다. BEFORE는 사용하지 않는다.
- 파일 소유자·READY·TREATMENT_PHOTO를 확인한다. 분석은 파일별 캐시 최대 256개로 제한하며 이미지 바이트는 보관하지 않는다.
- 사진·모델·분석 상태·적용 길이가 추천 입력 해시에 포함된다. latest 재조회는 달라진 입력을 재계산하고 같은 입력이면 재사용한다.
- 사진·모델·분석 상태·적용 길이·윤곽 비교 점수와 커트 길이/형태·펌 종류가 추천 입력 해시에 포함된다. latest 재조회는 달라진 입력을 재계산하고 같은 입력이면 재사용한다.
- 길이 입력도 없고 사진 길이도 판정할 수 없으면 `422 RECOMMENDATION_HAIR_LENGTH_REQUIRED`를 반환한다. 임의의 장발 기본 추천은 제공하지 않는다.
- `recommendation_basis.photo_analysis`는 `file_id`, `model_version`, `status`, `observed_length`, `applied`를 반환한다. `current_hair.hair_length`는 실제 점수/필터에 사용한 길이다. 프로필 DB 자체는 바꾸지 않는다.
- `recommendation_basis.photo_analysis`는 `file_id`, `model_version`, `status`, `observed_length`, `applied`, `compared_style_count`를 반환한다. `applied`는 길이 적용 여부, `compared_style_count`는 실제 윤곽 비교를 수행한 후보 수다. `current_hair.hair_length`는 실제 점수/필터에 사용한 길이다. 프로필 DB 자체는 바꾸지 않는다.
- 상태: `ASSESSED`, `UNCERTAIN`, `UNREADABLE`, `UNAVAILABLE`, `DISABLED`, `NEWER_PROFILE`, `NO_RECENT_PHOTO`. 판정됐어도 입력 길이보다 길면 applied=false다.

## 사진 윤곽과 시술 상세 점수

- 기존 로컬 분할 모델로 얻은 머리 영역을 얼굴 위치/크기로 정규화한 8×12 점유율 격자로 비교한다. 얼굴 식별 임베딩이나 성별은 사용하지 않는다. 후보는 먼저 길이·금기 조건을 통과해야 하며 READY 상태의 SYSTEM 카탈로그 썸네일만 비교한다.
- 윤곽 비교는 최대 30점이다. 두 사진의 머리 영역 교집합/합집합 비율을 사용하며 0.60 이상일 때만 `PHOTO_SHAPE_MATCH` 근거를 반환한다. 이 수치는 경험적 규칙이며 검증된 정확도/만족 확률이 아니다.
- 최신 프로필이 길이 판단을 우선하더라도 시술 사진의 윤곽 비교는 수행한다. 판정 불가 사진에는 윤곽 일치 근거를 만들지 않는다.
- 시술 종류만 같으면 이력 점수는 최대 10점이며 `HISTORY_SERVICE_MATCH`로 한계를 설명한다. 커트 형태·길이·펌 종류가 카탈로그 이름/태그/분류와 일치하면 최대 30점을 추가한다. 알려진 영문/한글 표현을 정규화하며 모르는 표현은 정확히 일치할 때만 인정한다.
- 만족도 4~5점만 긍정 이력으로 사용한다. 3점은 중립, 1~2점의 구체적 스타일 일치는 감점한다. 긍정 근거에는 실제 일치 항목과 만족도를 표시한다.
- V35는 추천 참고기록의 시술일/만족도를 생성 당시 값으로 저장한다. 과거 원본 값은 복구할 수 없어 기존 행은 마이그레이션 시점 값으로 고정한다. 새 알고리즘 입력 버전으로 `/latest` 조회 시 이전 결과를 재계산한다.

## 제약

길이 전용 학습 분류기가 아니라 머리/얼굴 분할 결과에 기반한 규칙이다. 뒷모습, 작은 얼굴, 여러 사람, 잘린 머리, 측면 등에서 판정을 보류한다. 묶은 머리나 가려진 머리끝은 짧게 보일 수 있으므로 사용자가 입력한 길이와 비교해 확인할 필요가 있다. JPEG/PNG만 읽을 수 있고 HEIC는 UNREADABLE이다. 어깨 아래를 가슴 아래로 세분화하지 않는다. 제공 모델의 픽셀 확률을 길이 분류의 정확도라고 표시하지 않는다.
길이·스타일 전용 학습 분류기가 아니라 머리/얼굴 분할 결과에 기반한 규칙이다. 윤곽은 머리 모양의 대략적인 유사성만 반영하며 앞머리 종류·질감·컬·색상을 완전히 인식하지 않는다. 카탈로그에 가까운 스타일이 부족하면 후보 자체는 여전히 겹칠 수 있다. 뒷모습, 작은 얼굴, 여러 사람, 잘린 머리, 측면 등에서 판정을 보류한다. 묶은 머리나 가려진 머리끝은 짧게 보일 수 있으므로 사용자가 입력한 길이와 비교해 확인할 필요가 있다. JPEG/PNG만 읽을 수 있고 HEIC는 UNREADABLE이다. 어깨 아래를 가슴 아래로 세분화하지 않는다. 제공 모델의 픽셀 확률을 길이 분류의 정확도라고 표시하지 않는다.

모델은 Docker 빌드에서 고정 커밋과 SHA256으로 받으며 라이선스를 동봉한다. 운영 compose의 `HAIR_PHOTO_LENGTH_ENABLED` 기본값은 true, 테스트/로컬 기본값은 false다. 기존 `HAIR_ANALYSIS_ENABLED`는 별도 설정이다. 롤백/비활성화 역시 GitHub/Actions 경로로 수행한다.

Expand All @@ -28,10 +37,10 @@
```sh
docker exec heddy-v2-app java -Djava.awt.headless=true -Xmx256m \
-Dloader.main=com.heddy.diagnostics.RecommendationReadOnlyAudit \
-cp /app/app.jar org.springframework.boot.loader.launch.PropertiesLauncher
-cp /app/app.jar org.springframework.boot.loader.launch.PropertiesLauncher --latest-account
```

Spring 서버나 마이그레이션을 새로 실행하지 않는다. DB 읽기 전용 트랜잭션, 기존 S3 내부 읽기, 실제 배포된 resolver/scorer만 사용한다. 최대 100개 활성 계정을 검사하며 계정 해시, 입력·적용 길이, 분석 상태와 추천 이름/점수만 출력한다. 사진·연락처·기록 원문·키를 출력하거나 추천/프로필을 저장하지 않는다.
Spring 서버나 마이그레이션을 새로 실행하지 않는다. DB 읽기 전용 트랜잭션, 기존 S3 내부 읽기, 실제 배포된 resolver/scorer만 사용한다. `--latest-account`는 가장 최근 추천을 생성한 활성 계정 1개만 검사하며 (생략 시 최대 100개), 계정 해시, 입력·적용 길이, 분석 상태와 추천 이름/점수만 출력한다. 사진·연락처·기록 원문·키를 출력하거나 추천/프로필을 저장하지 않는다.

V33은 실제 SYSTEM 썸네일을 검수해 확인된 길이 오분류를 교정하고 그룹/묶은머리/불명확한 옛 사진 7개를 추천에서 제외한다. 사용자 기록이나 파일은 삭제하지 않는다.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,12 @@ static Basis from(RecommendationBasis basis) {

public record PhotoAnalysis(@JsonProperty("file_id") UUID fileId,
@JsonProperty("model_version") String modelVersion, String status,
@JsonProperty("observed_length") String observedLength, boolean applied) {
@JsonProperty("observed_length") String observedLength, boolean applied,
@JsonProperty("compared_style_count") int comparedStyleCount) {
static PhotoAnalysis from(com.heddy.domain.recommendation.model.PhotoHairEvidence evidence) {
return evidence == null ? null : new PhotoAnalysis(evidence.fileId(), evidence.modelVersion(),
evidence.status(), evidence.observedLength() == null ? null : evidence.observedLength().name(),
evidence.applied());
evidence.applied(), evidence.comparedStyleCount());
}
}

Expand Down Expand Up @@ -124,9 +125,28 @@ static Reason from(RecommendationReason reason) {
return new Reason(reason.code().name(), message(reason), reason.params());
}

private static String serviceNames(String types) {
return java.util.Arrays.stream(types.split(", ")).map(type -> switch (type) {
case "CUT" -> "커트";
case "PERM" -> "펌";
case "COLOR" -> "염색";
case "BLEACH" -> "탈색";
case "CLINIC" -> "클리닉";
case "STYLING" -> "스타일링";
default -> "기타";
}).collect(java.util.stream.Collectors.joining(", "));
}

private static String message(RecommendationReason reason) {
return switch (reason.code()) {
case SIMILAR_HIGH_SATISFACTION_HISTORY -> "이전에 만족한 시술과 유사합니다.";
case PHOTO_SHAPE_MATCH -> "최근 시술 사진의 머리 윤곽이 ‘"
+ reason.params().getOrDefault("style_name", "이 스타일") + "’의 참고 사진과 유사합니다.";
case SIMILAR_HIGH_SATISFACTION_HISTORY -> reason.params().getOrDefault("style_name", "이 스타일")
+ "은 만족도 " + reason.params().getOrDefault("satisfaction", "4")
+ "점 기록의 " + reason.params().getOrDefault("matched_details", "시술 특성") + "와 일치합니다.";
case HISTORY_SERVICE_MATCH -> "만족도 " + reason.params().getOrDefault("satisfaction", "4")
+ "점 기록과 시술 종류(" + serviceNames(reason.params().getOrDefault("service_types", ""))
+ ")가 같습니다. 세부 스타일의 유사성은 확인되지 않았습니다.";
case SAVED_STYLE_MATCH -> "이전에 저장한 스타일입니다.";
case PREFERRED_TAG_MATCH -> "선호하는 ‘"
+ reason.params().getOrDefault("tag_name", "스타일") + "’ 태그와 일치합니다.";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
@Component
@ConditionalOnProperty(name = "app.photo-length.enabled", havingValue = "true")
public class OnnxPhotoHairLengthAdapter implements PhotoHairLengthPort {
public static final String MODEL_VERSION = "selfie-multiclass-v1-length-v1";
public static final String MODEL_VERSION = "selfie-multiclass-v1-shape-v2";
private static final String MODEL_SHA256 = "35ec1ecd9ee7f85073c99c00020b7f6751b69506eeacf683bc8665f6117f85b0";
private static final Logger log = LoggerFactory.getLogger(OnnxPhotoHairLengthAdapter.class);
private final OrtEnvironment environment = OrtEnvironment.getEnvironment();
Expand Down Expand Up @@ -78,7 +78,9 @@ public synchronized PhotoHairEvidence analyze(StoredFile file) {
var result = session.run(Map.of("input_29", tensor))) {
float[][][] logits = ((float[][][][]) result.get(0).getValue())[0];
var length = estimator.estimate(logits);
var observation = evidence(file, length == null ? "UNCERTAIN" : "ASSESSED", length);
var observation = new PhotoHairEvidence(file.fileId(), MODEL_VERSION,
length == null ? "UNCERTAIN" : "ASSESSED", length, false,
length == null ? java.util.List.of() : estimator.shape(logits), 0);
cache.put(key, observation);
return observation;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,47 @@ HairLength estimate(float[][][] logits) {
return HairLength.BELOW_SHOULDER;
}

/** Face-relative hair occupancy; rejects profiles and incomplete framing before comparing silhouettes. */
List<Double> shape(float[][][] logits) {
if (estimate(logits) == null) return List.of();
int h = logits.length, w = logits[0].length;
List<Integer> faceX = new ArrayList<>(), faceY = new ArrayList<>();
boolean[][] hair = new boolean[h][w];
for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) {
float[] scores = logits[y][x];
int best = 0;
for (int c = 1; c < scores.length; c++) if (scores[c] > scores[best]) best = c;
double sum = 0;
for (float score : scores) sum += Math.exp(score - scores[best]);
if (1 / sum < .80) continue;
if (best == 3) { faceX.add(x); faceY.add(y); }
hair[y][x] = best == 1;
}
if (faceX.size() < 500) return List.of();
int[] fx = faceX.stream().mapToInt(Integer::intValue).sorted().toArray();
int[] fy = faceY.stream().mapToInt(Integer::intValue).sorted().toArray();
double left = percentile(fx, .05), right = percentile(fx, .95);
double top = percentile(fy, .05), bottom = percentile(fy, .95);
double fw = right - left, fh = bottom - top, cx = (left + right) / 2;
if (fw / fh < .55 || fw / fh > 1.25) return List.of();
// A fixed grid in face coordinates makes scale/background independent comparisons possible.
int columns = 8, rows = 12;
double x0 = cx - fw * 1.25, y0 = top - fh * .9;
double cellW = fw * 2.5 / columns, cellH = fh * 3.4 / rows;
List<Double> shape = new ArrayList<>(columns * rows);
for (int gy = 0; gy < rows; gy++) for (int gx = 0; gx < columns; gx++) {
int seen = 0, occupied = 0;
for (int y = (int)Math.floor(y0 + gy * cellH); y < y0 + (gy + 1) * cellH; y++) {
for (int x = (int)Math.floor(x0 + gx * cellW); x < x0 + (gx + 1) * cellW; x++) {
seen++;
if (y >= 0 && y < h && x >= 0 && x < w && hair[y][x]) occupied++;
}
}
shape.add(seen == 0 ? 0.0 : Math.round(occupied * 1000.0 / seen) / 1000.0);
}
return List.copyOf(shape);
}

private static int percentile(int[] sorted, double quantile) {
return sorted[Math.min(sorted.length - 1, (int) (sorted.length * quantile))];
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ score, toBreakdown(), reasons.stream().map(RecommendationItemEntity::toReason).t

private static Map<String, Double> breakdownMap(ScoreBreakdown value) {
Map<String, Double> result = new LinkedHashMap<>();
result.put("photo_similarity", value.photoSimilarityScore());
result.put("history", value.historyScore());
result.put("saved_style", value.savedStyleScore());
result.put("preferred_tag", value.preferredTagScore());
Expand All @@ -84,7 +85,7 @@ private static Map<String, Double> breakdownMap(ScoreBreakdown value) {
private ScoreBreakdown toBreakdown() {
return new ScoreBreakdown(value("history"), value("saved_style"), value("preferred_tag"),
value("hair_compatibility"), value("care_time"), value("raw"),
value("available_maximum"), value("final"));
value("available_maximum"), value("final"), value("photo_similarity"));
}

private double value(String key) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public RecommendationRun insert(RecommendationRun run, String canonicalInputSnap
List<RecommendationReferenceEntity> references = run.items().stream()
.filter(item -> item.referenceRecord() != null)
.map(item -> new RecommendationReferenceEntity(item.recommendationItemId(),
item.referenceRecord().recordId(), item.referenceRecord().reasonCode()))
item.referenceRecord()))
.toList();
if (!references.isEmpty()) {
referenceRepository.saveAllAndFlush(references);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,19 @@ class RecommendationReferenceEntity {
@Column(name = "reference_reason", nullable = false, length = 255, updatable = false)
private String referenceReasonCode;

@Column(name = "performed_at_snapshot", nullable = false, updatable = false)
private java.time.Instant performedAtSnapshot;
@Column(name = "satisfaction_snapshot", updatable = false)
private Integer satisfactionSnapshot;

protected RecommendationReferenceEntity() { }

RecommendationReferenceEntity(UUID recommendationItemId, UUID recordId, String reasonCode) {
RecommendationReferenceEntity(UUID recommendationItemId, com.heddy.domain.recommendation.model.RecommendationReference reference) {
this.recommendationItemId = recommendationItemId;
this.recordId = recordId;
this.referenceReasonCode = reasonCode;
this.recordId = reference.recordId();
this.referenceReasonCode = reference.reasonCode();
this.performedAtSnapshot = reference.performedAt();
this.satisfactionSnapshot = reference.satisfaction();
}

static class Key implements Serializable {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ Map<UUID, RecommendationReference> findByItemIds(Collection<UUID> itemIds) {
Map<UUID, RecommendationReference> result = new LinkedHashMap<>();
jdbcTemplate.query("""
SELECT reference.recommendation_item_id, reference.record_id,
reference.reference_reason, record.performed_at, record.satisfaction
reference.reference_reason, reference.performed_at_snapshot AS performed_at,
reference.satisfaction_snapshot AS satisfaction
FROM recommendation_reference_records reference
JOIN treatment_records record ON record.record_id = reference.record_id
WHERE reference.recommendation_item_id IN (:ids)
ORDER BY reference.recommendation_item_id, reference.record_id
""", Map.of("ids", itemIds), (org.springframework.jdbc.core.RowCallbackHandler) rows -> result.put(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ private static Map<String, Object> basisMap(RecommendationBasis basis) {
photo.put("status", evidence.status());
putEnum(photo, "observed_length", evidence.observedLength());
photo.put("applied", evidence.applied());
photo.put("compared_style_count", evidence.comparedStyleCount());
value.put("photo_analysis", photo);
}
return value;
Expand Down Expand Up @@ -144,7 +145,8 @@ private static com.heddy.domain.recommendation.model.PhotoHairEvidence photoEvid
return new com.heddy.domain.recommendation.model.PhotoHairEvidence(
value.get("file_id") == null ? null : UUID.fromString(value.get("file_id").toString()),
(String) value.get("model_version"), (String) value.get("status"),
enumValue(value, "observed_length", HairLength.class), Boolean.TRUE.equals(value.get("applied")));
enumValue(value, "observed_length", HairLength.class), Boolean.TRUE.equals(value.get("applied")),
List.of(), integer(value, "compared_style_count", 0));
}

private static void putEnum(Map<String, Object> target, String key, Enum<?> value) {
Expand Down
Loading
Loading