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
9 changes: 8 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,16 @@ RUN apt-get update \
&& groupadd --system spring \
&& useradd --system --gid spring spring

RUN mkdir -p /opt/heddy/photo-models \
&& curl --fail --location --retry 3 --max-time 180 \
'https://huggingface.co/senty-au/selfie_multiclass_256x256-ONNX/resolve/6db8421a7150ac20558f2c24675078eb3a1a04d0/onnx/model.onnx' \
-o /opt/heddy/photo-models/selfie.onnx \
&& echo '35ec1ecd9ee7f85073c99c00020b7f6751b69506eeacf683bc8665f6117f85b0 /opt/heddy/photo-models/selfie.onnx' | sha256sum -c -
COPY docs/photo-length-model-LICENSE.txt /opt/heddy/photo-models/LICENSE.txt
COPY docs/photo-length-model-NOTICE.txt /opt/heddy/photo-models/NOTICE.txt
COPY --from=build /app/build/libs/*.jar app.jar

USER spring
EXPOSE 8080

ENTRYPOINT ["java", "-jar", "/app/app.jar"]
ENTRYPOINT ["java", "-Djava.awt.headless=true", "-jar", "/app/app.jar"]
2 changes: 2 additions & 0 deletions docker-compose.prod.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ services:
# 화면 체류 시간보다 짧으면 이미지가 403 으로 깨진다.
DOWNLOAD_URL_TTL_SECONDS: ${DOWNLOAD_URL_TTL_SECONDS:-300}
# 로컬 ONNX 얼굴 파싱 모델. 호스트의 읽기 전용 파일을 컨테이너에 마운트한다.
HAIR_PHOTO_LENGTH_ENABLED: ${HAIR_PHOTO_LENGTH_ENABLED:-true}
HAIR_PHOTO_LENGTH_MODEL_PATH: /opt/heddy/photo-models/selfie.onnx
HAIR_ANALYSIS_ENABLED: ${HAIR_ANALYSIS_ENABLED:-false}
HAIR_ANALYSIS_MODEL_PATH: ${HAIR_ANALYSIS_MODEL_PATH:-/opt/heddy/models/face-parsing.onnx}
HAIR_ANALYSIS_MODEL_VERSION: ${HAIR_ANALYSIS_MODEL_VERSION:-segformer-face-parsing-cv-v1}
Expand Down
202 changes: 202 additions & 0 deletions docs/photo-length-model-LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@

Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.

"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.

"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.

"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.

"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.

"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.

"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).

"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.

"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."

"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:

(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and

(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and

(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and

(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.

You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.

5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.

6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

APPENDIX: How to apply the Apache License to your work.

To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.

Copyright [yyyy] [name of copyright owner]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
9 changes: 9 additions & 0 deletions docs/photo-length-model-NOTICE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
MediaPipe Selfie Multiclass (256 x 256), Google, Apache License 2.0.
Upstream: https://developers.google.com/edge/mediapipe/solutions/vision/image_segmenter
Source model: https://storage.googleapis.com/mediapipe-models/image_segmenter/selfie_multiclass_256x256/float32/1/selfie_multiclass_256x256.tflite
ONNX conversion by senty-au (Apache-2.0 model card):
https://huggingface.co/senty-au/selfie_multiclass_256x256-ONNX/tree/6db8421a7150ac20558f2c24675078eb3a1a04d0
Pinned model SHA256: 35ec1ecd9ee7f85073c99c00020b7f6751b69506eeacf683bc8665f6117f85b0
The unmodified ONNX conversion is distributed with this container.
License: https://www.apache.org/licenses/LICENSE-2.0
Heddy adds a conservative visible hair-length heuristic; this is not a trained hair-length or gender classifier.
36 changes: 36 additions & 0 deletions docs/recommendation-photo-length.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# 사진과 추천 길이 연결

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

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

## 제약

길이 전용 학습 분류기가 아니라 머리/얼굴 분할 결과에 기반한 규칙이다. 뒷모습, 작은 얼굴, 여러 사람, 잘린 머리, 측면 등에서 판정을 보류한다. 묶은 머리나 가려진 머리끝은 짧게 보일 수 있으므로 사용자가 입력한 길이와 비교해 확인할 필요가 있다. JPEG/PNG만 읽을 수 있고 HEIC는 UNREADABLE이다. 어깨 아래를 가슴 아래로 세분화하지 않는다. 제공 모델의 픽셀 확률을 길이 분류의 정확도라고 표시하지 않는다.

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

## 검증

단위 테스트는 길이 경계, 불확실/잘림/복수 얼굴, 계정 소유권, BEFORE 배제, 최신 프로필 우선, 짧은 입력 보호를 검증한다. API/실제 PostgreSQL 테스트는 업로드 변경에 따른 latest 재생성과 분석 근거 저장/재사용 및 길이 누락 오류를 검증한다.

실제 모델 smoke test는 `PHOTO_LENGTH_TEST_MODEL`에 고정 ONNX 경로, `PHOTO_LENGTH_TEST_IMAGES`에 검수한 SYSTEM 카탈로그 사진 0~5.jpg 경로를 설정해 실행한다. 사용자 사진은 테스트 fixture로 복사하지 않는다. 측면 장발/뒷모습 보브/손·안경에 가린 얼굴은 UNCERTAIN, 정면 숏 2개는 SHORT를 기대한다.

배포 후 운영 컨테이너에서 읽기 전용 감사:

```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
```

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

V33은 실제 SYSTEM 썸네일을 검수해 확인된 길이 오분류를 교정하고 그룹/묶은머리/불명확한 옛 사진 7개를 추천에서 제외한다. 사용자 기록이나 파일은 삭제하지 않는다.
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ public record Basis(
@JsonProperty("ar_candidate_style_count") int arCandidateStyleCount,
@JsonProperty("style_preferences") StylePreferences stylePreferences,
@JsonProperty("current_hair") CurrentHair currentHair,
@JsonProperty("available_care_time_minutes") Integer availableCareTimeMinutes
@JsonProperty("available_care_time_minutes") Integer availableCareTimeMinutes,
@JsonProperty("photo_analysis") PhotoAnalysis photoAnalysis
) {
static Basis from(RecommendationBasis basis) {
if (basis == null) {
Expand All @@ -45,7 +46,18 @@ static Basis from(RecommendationBasis basis) {
basis.arCandidateStyleCount(),
new StylePreferences(basis.stylePreferences().preferredCount(),
basis.stylePreferences().excludedCount()),
CurrentHair.from(basis.currentHair()), basis.availableCareTimeMinutes());
CurrentHair.from(basis.currentHair()), basis.availableCareTimeMinutes(),
PhotoAnalysis.from(basis.photoAnalysis()));
}
}

public record PhotoAnalysis(@JsonProperty("file_id") UUID fileId,
@JsonProperty("model_version") String modelVersion, String status,
@JsonProperty("observed_length") String observedLength, boolean applied) {
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());
}
}

Expand Down
Loading
Loading