휴대폰 등록: 사진→내용→항목→발행 화면(m.html), 사진 인박스·VLM 판독·발행 API, 테일스케일 접속 열쇠, launchd 상시 실행
This commit is contained in:
1 parent
4ce660b740
commit
e502c32542
8 files changed
+1066
-5
No files matched your search
@@ -2,3 +2,5 @@ dist/
|
||||
.DS_Store
|
||||
*.log
|
||||
.claude/settings.local.json
|
||||
studio/_inbox/
|
||||
__pycache__/
|
||||
@@ -6,7 +6,9 @@
|
||||
## 0. 절대 규칙
|
||||
|
||||
1. **DB·서버·CMS 를 만들지 않는다.** 정적 HTML/CSS/JS 만. Node/npm/pip 패키지 금지.
|
||||
- 예외: `studio/` 는 사이트가 아니라 **아이맥 로컬 편집 도구**다(표준 라이브러리만, 127.0.0.1 전용, `dist/` 에 포함되지 않음). 이 예외를 근거로 사이트에 서버 기능을 붙이지 않는다.
|
||||
- 예외: `studio/` 는 사이트가 아니라 **관리 도구**다(표준 라이브러리만, `dist/` 에 포함되지 않음).
|
||||
아이맥 127.0.0.1 에서만 돌고, 폰은 테일스케일(`tailscale serve`, 127.0.0.1 로 프록시)로 접속한다. 열쇠는 `~/.config/teamat-studio/token`.
|
||||
이 예외를 근거로 사이트에 서버 기능을 붙이지 않는다.
|
||||
2. **빌드는 `python3 build.py` 하나.** 표준 라이브러리만 사용.
|
||||
- AI(DeepSeek) 호출은 `studio/server.py` 안에서만. 빌드·사이트 코드에 AI 를 넣지 않는다.
|
||||
- AI 제안은 사람이 적용·저장해야 파일이 바뀐다(자동 저장 금지). AI 가 쓴 수치는 저장 전에 확인한다.
|
||||
|
||||
@@ -73,6 +73,21 @@ bash scripts/studio.sh # http://localhost:8081
|
||||
- 단축키: `/` 검색, `↑↓` 이동, `⌘S` 저장, 프롬프트에서 `⌘Enter` 실행
|
||||
- 서버는 `127.0.0.1` 에만 붙는다. 외부에서 접근되지 않는다
|
||||
|
||||
## 폰에서 등록 (휴대폰 관리 화면)
|
||||
|
||||
사진을 찍고 내용을 쓰면 상세 페이지 한 장이 만들어지는 화면. 아이맥에서 도는 서버를 테일스케일로 폰에서 연다.
|
||||
|
||||
- 주소: `https://imac.taild8883.ts.net/m` — 테일스케일 안에서만 열린다. **처음 한 번** `?t=<토큰>` 을 붙여야 하고, 그 뒤로는 쿠키에 남는다.
|
||||
- 토큰: `cat ~/.config/teamat-studio/token` (아이맥). 홈 화면에 추가하면 앱처럼 열린다(PWA).
|
||||
- 흐름: ① 사진 찍기(여러 장, 첫 장이 대표) → ② 내용 작성(사진을 읽어 초안) → ③ 규격·소재·세탁 칩 + 가격 → ④ 확인 후 저장
|
||||
- 저장 = `사진 변환 → content/products/<slug>.md → build.py → git commit`(경로만 지정해 커밋). `사이트에 올리기` 를 누르면 `scripts/deploy.sh` 까지 실행한다.
|
||||
- 사진은 `studio/_inbox/` 에 잠시 쌓였다가 저장할 때 `assets/img/<slug>/cover.jpg`, `detail-NN.jpg` 로 옮긴다(인박스는 커밋하지 않는다).
|
||||
- 커밋되지 않은 **다른 초안**이 있으면 배포를 건너뛰고 알려준다. 그 초안까지 올리려면 화면의 `다른 초안도 함께 올리기` 를 켠다.
|
||||
- 서버 상시 실행: `bash scripts/studio-service.sh install` (launchd `io.lala.teamat-studio`, 로그 `~/Library/Logs/teamat-studio.log`). `status` / `stop` 도 같은 스크립트.
|
||||
- 아이맥이 잠자기면 접속되지 않는다. 아이맥을 깨우면 다시 붙는다.
|
||||
- 키: `~/.config/teamat-studio/ai.json`(DeepSeek, 문장), `vision.json`(NVIDIA VLM, 사진 판독). 둘 다 `chmod 600`, 저장소에는 넣지 않는다.
|
||||
- 폰에서 사진 판독이나 AI 를 못 쓰면 메모만으로 초안을 쓴다(사진 없이도 저장은 되지만 사진 1장은 필수).
|
||||
|
||||
## 대화로 고치기
|
||||
|
||||
Claude Code 에 말로 지시하면 위 파일들을 알아서 고친다. 예:
|
||||
@@ -105,5 +120,5 @@ Claude Code 에 말로 지시하면 위 파일들을 알아서 고친다. 예:
|
||||
## 아직 없는 것 (의도적으로)
|
||||
|
||||
결제·회원·장바구니·**재고 개수 관리**(작품은 유일품이라 판매중/판매완료 두 상태로 충분), 게시판·리뷰, 다국어, 사이트 내 검색, 분석 스크립트.
|
||||
관리자 화면도 없다 — 대신 아이맥 로컬 편집 도구 `studio/` 가 있다(위 항목).
|
||||
관리자 화면은 사이트에 없다 — 대신 별도 도구 `studio/` 가 있다(아이맥 로컬 + 테일스케일로 폰 접속).
|
||||
구매는 네이버 스마트스토어로 넘긴다.
|
||||
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env bash
|
||||
# 한땀 작업실 서버를 macOS 로그인 항목(launchd)으로 등록한다.
|
||||
# bash scripts/studio-service.sh install # 설치 + 시작
|
||||
# bash scripts/studio-service.sh status # 상태
|
||||
# bash scripts/studio-service.sh stop # 중지 + 등록 해제
|
||||
set -euo pipefail
|
||||
|
||||
LABEL="io.lala.teamat-studio"
|
||||
PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"
|
||||
REPO="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
PORT="${PORT:-8081}"
|
||||
PY="$(command -v python3)"
|
||||
|
||||
case "${1:-install}" in
|
||||
install)
|
||||
mkdir -p "$HOME/Library/LaunchAgents" "$HOME/Library/Logs"
|
||||
cat > "$PLIST" <<PLISTEOF
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key><string>$LABEL</string>
|
||||
<key>ProgramArguments</key>
|
||||
<array>
|
||||
<string>$PY</string><string>$REPO/studio/server.py</string>
|
||||
<string>--port</string><string>$PORT</string>
|
||||
</array>
|
||||
<key>WorkingDirectory</key><string>$REPO</string>
|
||||
<key>RunAtLoad</key><true/>
|
||||
<key>KeepAlive</key><true/>
|
||||
<key>StandardOutPath</key><string>$HOME/Library/Logs/teamat-studio.log</string>
|
||||
<key>StandardErrorPath</key><string>$HOME/Library/Logs/teamat-studio.err.log</string>
|
||||
</dict>
|
||||
</plist>
|
||||
PLISTEOF
|
||||
# 손으로 띄운 서버가 있으면 먼저 정리(포트 충돌 방지)
|
||||
pkill -f "[s]tudio/server.py" 2>/dev/null || true
|
||||
launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || true
|
||||
launchctl bootstrap "gui/$(id -u)" "$PLIST"
|
||||
launchctl kickstart -k "gui/$(id -u)/$LABEL" 2>/dev/null || true
|
||||
sleep 1
|
||||
echo "설치 완료: $LABEL (포트 $PORT)"
|
||||
curl -s -o /dev/null -w "로컬 응답: HTTP %{http_code}\n" "http://127.0.0.1:$PORT/m" || true
|
||||
;;
|
||||
status)
|
||||
launchctl print "gui/$(id -u)/$LABEL" 2>/dev/null | sed -n '1,10p' || echo "실행 중 아님"
|
||||
curl -s -o /dev/null -w "로컬 응답: HTTP %{http_code}\n" "http://127.0.0.1:$PORT/m" || true
|
||||
;;
|
||||
stop)
|
||||
launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || true
|
||||
rm -f "$PLIST"
|
||||
echo "중지 및 등록 해제"
|
||||
;;
|
||||
*)
|
||||
echo "사용법: bash scripts/studio-service.sh [install|status|stop]" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
+437
@@ -0,0 +1,437 @@
|
||||
<!doctype html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="theme-color" content="#F6F2EA">
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="default">
|
||||
<title>한땀 작업실 — 상품 등록</title>
|
||||
<link rel="manifest" href="manifest.json">
|
||||
<link rel="apple-touch-icon" href="../assets/img/process/stitch.jpg">
|
||||
<style>
|
||||
:root{
|
||||
--paper:#F6F2EA; --ink:#26241F; --muted:#6B6357; --sage:#6C7A63;
|
||||
--clay:#A2705A; --line:#DCD3C4; --white:#FFFDF8;
|
||||
--serif:"Noto Serif KR","Apple SD Gothic Neo",serif;
|
||||
--sans:-apple-system,BlinkMacSystemFont,"Apple SD Gothic Neo","Noto Sans KR",system-ui,sans-serif;
|
||||
--safe-b:env(safe-area-inset-bottom,0px);
|
||||
}
|
||||
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
|
||||
html,body{margin:0;background:var(--paper);color:var(--ink);font-family:var(--sans);
|
||||
font-size:16px;line-height:1.65;overscroll-behavior-y:contain}
|
||||
body{padding-bottom:calc(96px + var(--safe-b))}
|
||||
header{position:sticky;top:0;z-index:20;background:rgba(246,242,234,.94);
|
||||
backdrop-filter:blur(8px);border-bottom:1px solid var(--line)}
|
||||
.head-in{display:flex;align-items:center;gap:10px;padding:12px 18px}
|
||||
.brand{font-family:var(--serif);font-size:17px;letter-spacing:.02em}
|
||||
.brand small{font-family:var(--sans);font-size:11px;letter-spacing:.18em;color:var(--muted);margin-left:8px}
|
||||
.steps{margin-left:auto;font-size:12px;color:var(--muted);letter-spacing:.08em}
|
||||
main{padding:18px}
|
||||
section[hidden]{display:none}
|
||||
h1{font-family:var(--serif);font-weight:400;font-size:24px;margin:6px 0 14px}
|
||||
h2{font-family:var(--serif);font-weight:400;font-size:19px;margin:0 0 6px}
|
||||
.label{font-size:11px;letter-spacing:.18em;color:var(--muted);text-transform:uppercase;margin:0 0 10px}
|
||||
.note{color:var(--muted);font-size:14px;margin:0 0 18px}
|
||||
.btn{display:flex;align-items:center;justify-content:center;gap:8px;width:100%;
|
||||
padding:16px;border:1px solid var(--ink);background:var(--ink);color:var(--paper);
|
||||
font-family:var(--sans);font-size:16px;border-radius:0;cursor:pointer}
|
||||
.btn:active{opacity:.82}
|
||||
.btn.ghost{background:transparent;color:var(--ink);border-color:var(--line)}
|
||||
.btn.sage{background:var(--sage);border-color:var(--sage)}
|
||||
.btn:disabled{opacity:.45}
|
||||
.btn-sm{padding:10px 14px;font-size:14px;width:auto}
|
||||
.stack{display:grid;gap:10px}
|
||||
.row2{display:grid;grid-template-columns:1fr 1fr;gap:10px}
|
||||
.card{background:var(--white);border:1px solid var(--line);padding:14px;margin-bottom:10px}
|
||||
.thumbs{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:14px}
|
||||
.thumb{position:relative;background:var(--line);aspect-ratio:4/5;overflow:hidden}
|
||||
.thumb img{width:100%;height:100%;object-fit:cover;display:block}
|
||||
.thumb .badge{position:absolute;left:0;top:0;background:var(--ink);color:var(--paper);
|
||||
font-size:11px;letter-spacing:.1em;padding:3px 7px}
|
||||
.thumb .tools{position:absolute;right:0;bottom:0;display:flex;gap:4px;padding:6px}
|
||||
.thumb .tools button{width:34px;height:34px;border:none;background:rgba(38,36,31,.82);
|
||||
color:#fff;font-size:15px;line-height:1;cursor:pointer}
|
||||
.thumb .tools button.del{background:rgba(162,112,90,.92)}
|
||||
label.field{display:block;margin-bottom:14px}
|
||||
label.field span{display:block;font-size:12px;letter-spacing:.1em;color:var(--muted);margin-bottom:6px}
|
||||
input[type=text],input[type=number],input[type=url],input[type=date],textarea{
|
||||
width:100%;padding:13px 12px;border:1px solid var(--line);background:var(--white);
|
||||
font-family:var(--sans);font-size:16px;color:var(--ink);border-radius:0}
|
||||
textarea{min-height:150px;line-height:1.7;resize:vertical}
|
||||
.chips{display:flex;flex-wrap:wrap;gap:8px;margin:0 0 10px}
|
||||
.chip{padding:9px 12px;border:1px solid var(--line);background:var(--white);
|
||||
font-size:13px;cursor:pointer;color:var(--muted)}
|
||||
.chip[aria-pressed=true]{border-color:var(--sage);background:#EEF0E9;color:var(--ink)}
|
||||
.bar{position:fixed;left:0;right:0;bottom:0;z-index:30;background:rgba(246,242,234,.97);
|
||||
border-top:1px solid var(--line);padding:12px 18px calc(12px + var(--safe-b));
|
||||
display:grid;grid-template-columns:auto 1fr;gap:10px;align-items:center}
|
||||
.bar .hint{font-size:12px;color:var(--muted);line-height:1.4}
|
||||
.facts{white-space:pre-wrap;font-size:13px;color:var(--muted);background:#EFEBE1;
|
||||
border-left:2px solid var(--sage);padding:12px;margin:0 0 16px}
|
||||
.voice{background:var(--white);border:1px solid var(--line);color:var(--ink);
|
||||
padding:10px 12px;font-size:14px;cursor:pointer}
|
||||
.voice.rec{background:var(--clay);color:#fff;border-color:var(--clay)}
|
||||
.list-item{display:flex;justify-content:space-between;align-items:baseline;gap:10px;
|
||||
padding:13px 2px;border-bottom:1px solid var(--line);text-decoration:none;color:var(--ink)}
|
||||
.list-item small{color:var(--muted)}
|
||||
.status{font-size:13px;color:var(--muted);margin-top:10px;min-height:20px}
|
||||
.status.err{color:#9B3B2A}
|
||||
.toast{position:fixed;left:50%;bottom:calc(110px + var(--safe-b));transform:translateX(-50%);
|
||||
background:var(--ink);color:var(--paper);padding:11px 16px;font-size:14px;z-index:50;
|
||||
opacity:0;pointer-events:none;transition:opacity .2s;max-width:88vw;text-align:center}
|
||||
.toast.on{opacity:1}
|
||||
.spin{display:inline-block;width:14px;height:14px;border:2px solid var(--line);
|
||||
border-top-color:var(--ink);border-radius:50%;animation:sp .8s linear infinite;vertical-align:-2px}
|
||||
@keyframes sp{to{transform:rotate(360deg)}}
|
||||
.summary{font-size:14px;color:var(--muted);margin-bottom:14px}
|
||||
.summary b{color:var(--ink);font-weight:500}
|
||||
a.live{color:var(--sage)}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<div class="head-in">
|
||||
<span class="brand">한땀<small>WORKSPACE</small></span>
|
||||
<span class="steps" id="steps">등록</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<!-- ① 홈 -->
|
||||
<section id="s-home">
|
||||
<p class="label">ADD PRODUCT</p>
|
||||
<h1>새 작품을 등록합니다</h1>
|
||||
<p class="note">사진을 찍고, 내용을 쓰고, 항목을 고르면 상세 페이지 한 장이 만들어집니다.</p>
|
||||
<button class="btn" id="start">신규 상품 등록</button>
|
||||
<div style="margin-top:26px">
|
||||
<p class="label">최근 작품</p>
|
||||
<div id="home-list"><span class="status"><span class="spin"></span> 불러오는 중</span></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ② 사진 -->
|
||||
<section id="s-photos" hidden>
|
||||
<p class="label">STEP 1 · 사진</p>
|
||||
<h1>사진을 찍으세요</h1>
|
||||
<p class="note">여러 장이면 계속 찍으세요. 첫 장이 대표 사진이 됩니다.</p>
|
||||
<div class="row2">
|
||||
<button class="btn" id="shoot">사진 찍기</button>
|
||||
<button class="btn ghost" id="pick">앨범에서</button>
|
||||
</div>
|
||||
<input type="file" id="cam" accept="image/*" capture="environment" hidden>
|
||||
<input type="file" id="album" accept="image/*" multiple hidden>
|
||||
<div class="thumbs" id="thumbs" style="margin-top:16px"></div>
|
||||
<div class="status" id="up-status"></div>
|
||||
</section>
|
||||
|
||||
<!-- ③ 내용 -->
|
||||
<section id="s-write" hidden>
|
||||
<p class="label">STEP 2 · 내용</p>
|
||||
<h1>내용 작성</h1>
|
||||
<p class="note">사진을 읽어 초안을 씁니다. 말로 덧붙이면 그 내용이 반영됩니다.</p>
|
||||
<label class="field">
|
||||
<span>메모 (선택) — 말로 넣어도 됩니다</span>
|
||||
<textarea id="note" style="min-height:84px" placeholder="예: 와인색 코튼린넨, 네 장, 사시코 실 포함"></textarea>
|
||||
</label>
|
||||
<div class="chips"><button class="voice" id="voice">🎙 말로 적기</button></div>
|
||||
<button class="btn sage" id="cap">내용 작성</button>
|
||||
<div class="status" id="cap-status"></div>
|
||||
<div id="cap-out" hidden style="margin-top:18px">
|
||||
<p class="label">사진에서 읽은 것</p>
|
||||
<pre class="facts" id="facts"></pre>
|
||||
<label class="field"><span>제목</span><input type="text" id="f-title"></label>
|
||||
<label class="field"><span>부제</span><input type="text" id="f-subtitle"></label>
|
||||
<label class="field"><span>본문</span><textarea id="f-body" style="min-height:230px"></textarea></label>
|
||||
<label class="field"><span>사진 설명(alt)</span><input type="text" id="f-alt"></label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ④ 항목 -->
|
||||
<section id="s-specs" hidden>
|
||||
<p class="label">STEP 3 · 항목</p>
|
||||
<h1>규격과 가격</h1>
|
||||
<p class="note">표준값을 누르면 채워집니다. 다르면 직접 고쳐 쓰세요.</p>
|
||||
|
||||
<label class="field"><span>규격</span><input type="text" id="f-size"></label>
|
||||
<div class="chips" data-for="f-size"></div>
|
||||
|
||||
<label class="field"><span>소재</span><input type="text" id="f-material"></label>
|
||||
<div class="chips" data-for="f-material"></div>
|
||||
|
||||
<label class="field"><span>세탁</span><input type="text" id="f-care"></label>
|
||||
<div class="chips" data-for="f-care"></div>
|
||||
|
||||
<div class="row2">
|
||||
<label class="field"><span>가격(원) · 비우면 "문의"</span><input type="number" id="f-price" inputmode="numeric"></label>
|
||||
<label class="field"><span>날짜</span><input type="date" id="f-date"></label>
|
||||
</div>
|
||||
<label class="field"><span>가격 옵션 안내 (선택)</span><input type="text" id="f-pricenote" placeholder="예: 네 장 세트 50,000원"></label>
|
||||
<label class="field"><span>네이버 링크 (선택)</span><input type="url" id="f-naver" placeholder="https://smartstore.naver.com/..."></label>
|
||||
<label class="field" style="display:flex;gap:10px;align-items:center">
|
||||
<input type="checkbox" id="f-featured" style="width:20px;height:20px">
|
||||
<span style="margin:0">첫 페이지 대표작으로</span>
|
||||
</label>
|
||||
<label class="field" style="display:flex;gap:10px;align-items:center">
|
||||
<input type="checkbox" id="f-soldout" style="width:20px;height:20px">
|
||||
<span style="margin:0">품절 표시</span>
|
||||
</label>
|
||||
</section>
|
||||
|
||||
<!-- ⑤ 확인 -->
|
||||
<section id="s-done" hidden>
|
||||
<p class="label">STEP 4 · 저장</p>
|
||||
<h1>이대로 만들까요?</h1>
|
||||
<div class="card" id="summary"></div>
|
||||
<button class="btn" id="pub-deploy">저장하고 사이트에 올리기</button>
|
||||
<div style="height:10px"></div>
|
||||
<button class="btn ghost" id="pub-only">저장만 (배포는 나중에)</button>
|
||||
<label class="field" style="display:flex;gap:10px;align-items:center;margin-top:16px">
|
||||
<input type="checkbox" id="force" style="width:20px;height:20px">
|
||||
<span style="margin:0">다른 초안도 함께 올리기</span>
|
||||
</label>
|
||||
<div class="status" id="pub-status"></div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<div class="bar" id="bar">
|
||||
<button class="btn ghost btn-sm" id="back">이전</button>
|
||||
<button class="btn" id="next">다음</button>
|
||||
</div>
|
||||
<div class="toast" id="toast"></div>
|
||||
|
||||
<script>
|
||||
const S = { step:'home', photos:[], facts:'', draft:{}, busy:false, presets:null };
|
||||
|
||||
const $ = s => document.querySelector(s);
|
||||
const toast = (m, ms=2200) => { const t=$('#toast'); t.textContent=m; t.classList.add('on');
|
||||
clearTimeout(t._h); t._h=setTimeout(()=>t.classList.remove('on'), ms); };
|
||||
|
||||
async function api(path, body){
|
||||
const res = await fetch(path, body===undefined ? {} : {
|
||||
method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(body)
|
||||
});
|
||||
if (res.status === 401){ location.href = '/?t=' ; throw new Error('인증이 풀렸습니다'); }
|
||||
const data = await res.json().catch(()=>({ok:false,error:'응답을 읽지 못했습니다'}));
|
||||
if (!res.ok || data.ok === false) throw new Error(data.error || ('오류 '+res.status));
|
||||
return data;
|
||||
}
|
||||
|
||||
/* ---------- 단계 이동 ---------- */
|
||||
const STEPS = {
|
||||
home:{el:'#s-home', n:'등록', prev:null, next:null},
|
||||
photos:{el:'#s-photos', n:'1/4 사진', prev:'home', next:'write'},
|
||||
write:{el:'#s-write', n:'2/4 내용', prev:'photos', next:'specs'},
|
||||
specs:{el:'#s-specs', n:'3/4 항목', prev:'write', next:'done'},
|
||||
done:{el:'#s-done', n:'4/4 저장', prev:'specs', next:null},
|
||||
};
|
||||
function go(step){
|
||||
S.step = step;
|
||||
Object.values(STEPS).forEach(v => $(v.el).hidden = true);
|
||||
$(STEPS[step].el).hidden = false;
|
||||
$('#steps').textContent = STEPS[step].n;
|
||||
const cfg = STEPS[step];
|
||||
$('#bar').style.display = step==='home' ? 'none' : 'grid';
|
||||
$('#back').style.visibility = cfg.prev ? 'visible' : 'hidden';
|
||||
const next = $('#next');
|
||||
next.textContent = step==='specs' ? '확인' : '다음';
|
||||
next.style.display = cfg.next ? '' : 'none';
|
||||
if (step==='done') renderSummary();
|
||||
window.scrollTo({top:0});
|
||||
}
|
||||
$('#back').onclick = () => { const p = STEPS[S.step].prev; if (p) go(p); };
|
||||
$('#next').onclick = () => {
|
||||
if (S.step==='photos' && !S.photos.length){ toast('사진을 한 장 이상 올려 주세요'); return; }
|
||||
if (S.step==='write'){
|
||||
if (!$('#f-title').value.trim() || !$('#f-body').value.trim()){
|
||||
toast('먼저 "내용 작성"을 눌러 초안을 만들어 주세요'); return; }
|
||||
}
|
||||
go(STEPS[S.step].next);
|
||||
};
|
||||
|
||||
/* ---------- 홈 ---------- */
|
||||
async function loadHome(){
|
||||
try{
|
||||
const d = await api('/api/state');
|
||||
const rows = d.products.slice(0,8).map(p =>
|
||||
`<a class="list-item" href="/p/${p.slug}.html" target="_blank">
|
||||
<span>${p.title}</span><small>${p.price_text||''}</small></a>`).join('');
|
||||
$('#home-list').innerHTML = rows || '<span class="status">아직 등록된 작품이 없습니다</span>';
|
||||
if (d.presets || (d.vision)) {}
|
||||
}catch(e){ $('#home-list').innerHTML = `<span class="status err">${e.message}</span>`; }
|
||||
}
|
||||
|
||||
$('#start').onclick = () => {
|
||||
S.photos = []; S.facts=''; S.draft={};
|
||||
['#f-title','#f-subtitle','#f-body','#f-alt','#f-size','#f-material','#f-care','#f-price',
|
||||
'#f-pricenote','#f-naver','#note'].forEach(s=>{ if($(s)) $(s).value=''; });
|
||||
$('#f-date').value = new Date().toISOString().slice(0,10);
|
||||
$('#f-featured').checked = false; $('#f-soldout').checked = false;
|
||||
$('#cap-out').hidden = true; $('#cap-status').textContent = '';
|
||||
renderPhotos(); go('photos');
|
||||
};
|
||||
|
||||
/* ---------- 사진 ---------- */
|
||||
$('#shoot').onclick = () => $('#cam').click();
|
||||
$('#pick').onclick = () => $('#album').click();
|
||||
$('#cam').onchange = e => uploadFiles(e.target.files, true);
|
||||
$('#album').onchange = e => uploadFiles(e.target.files, false);
|
||||
|
||||
async function uploadFiles(files, single){
|
||||
const list = Array.from(files || []);
|
||||
if (!list.length) return;
|
||||
for (let i=0;i<list.length;i++){
|
||||
$('#up-status').innerHTML = `<span class="spin"></span> 사진 올리는 중 ${i+1}/${list.length}`;
|
||||
try{
|
||||
const res = await fetch('/api/photo?name=' + encodeURIComponent(list[i].name || 'photo.jpg'),
|
||||
{method:'POST', headers:{'Content-Type':'application/octet-stream'}, body:list[i]});
|
||||
const d = await res.json();
|
||||
if (!res.ok || d.ok===false) throw new Error(d.error || '업로드 실패');
|
||||
S.photos.push({uid:d.uid, name:list[i].name});
|
||||
}catch(e){ $('#up-status').innerHTML = `<span class="status err">${e.message}</span>`; return; }
|
||||
}
|
||||
$('#up-status').textContent = '';
|
||||
$('#cam').value=''; $('#album').value='';
|
||||
renderPhotos();
|
||||
}
|
||||
|
||||
function renderPhotos(){
|
||||
const box = $('#thumbs');
|
||||
if (!S.photos.length){ box.innerHTML = `<p class="note" style="grid-column:1/-1">아직 사진이 없습니다.</p>`; return; }
|
||||
box.innerHTML = S.photos.map((p,i)=>`
|
||||
<div class="thumb">
|
||||
<img src="/media-inbox/${p.uid}.jpg" alt="">
|
||||
${i===0?'<span class="badge">대표</span>':''}
|
||||
<div class="tools">
|
||||
${i>0?`<button data-mv="${i}:-1" aria-label="앞으로">←</button>`:''}
|
||||
${i<S.photos.length-1?`<button data-mv="${i}:1" aria-label="뒤로">→</button>`:''}
|
||||
<button class="del" data-del="${i}" aria-label="삭제">×</button>
|
||||
</div>
|
||||
</div>`).join('');
|
||||
box.querySelectorAll('[data-del]').forEach(b=>b.onclick=()=>{
|
||||
S.photos.splice(+b.dataset.del,1); renderPhotos();
|
||||
});
|
||||
box.querySelectorAll('[data-mv]').forEach(b=>b.onclick=()=>{
|
||||
const [i,d] = b.dataset.mv.split(':').map(Number);
|
||||
const j = i+d; if (j<0||j>=S.photos.length) return;
|
||||
[S.photos[i],S.photos[j]] = [S.photos[j],S.photos[i]]; renderPhotos();
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------- 내용 작성 ---------- */
|
||||
$('#cap').onclick = async () => {
|
||||
if (!S.photos.length){ toast('사진을 먼저 올려 주세요'); return; }
|
||||
$('#cap').disabled = true;
|
||||
$('#cap-status').innerHTML = '<span class="spin"></span> 사진을 읽고 문장을 쓰는 중… (10~30초)';
|
||||
try{
|
||||
const d = await api('/api/caption', {
|
||||
photos: S.photos.map(p=>p.uid),
|
||||
note: $('#note').value.trim(),
|
||||
known: { size:$('#f-size').value.trim(), material:$('#f-material').value.trim(),
|
||||
care:$('#f-care').value.trim(), price:$('#f-price').value }
|
||||
});
|
||||
S.facts = d.facts; S.draft = d.draft;
|
||||
$('#facts').textContent = d.facts;
|
||||
$('#f-title').value = d.draft.title || '';
|
||||
$('#f-subtitle').value = d.draft.subtitle || '';
|
||||
$('#f-body').value = d.draft.body || '';
|
||||
$('#f-alt').value = d.draft.image_alt || '';
|
||||
$('#cap-out').hidden = false;
|
||||
$('#cap-status').textContent = d.warning ? ('사진 판독 대신 메모로 썼습니다: ' + d.warning) : '';
|
||||
}catch(e){ $('#cap-status').innerHTML = `<span class="status err">${e.message}</span>`; }
|
||||
finally{ $('#cap').disabled = false; }
|
||||
};
|
||||
|
||||
/* ---------- 음성 입력 ---------- */
|
||||
const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
|
||||
(() => {
|
||||
const btn = $('#voice');
|
||||
if (!SR || !window.isSecureContext){ btn.textContent = '🎙 키보드의 마이크 버튼으로도 말할 수 있습니다'; btn.disabled = true; return; }
|
||||
const rec = new SR(); rec.lang='ko-KR'; rec.interimResults=false; rec.continuous=false;
|
||||
let on = false;
|
||||
rec.onresult = ev => {
|
||||
const text = Array.from(ev.results).map(r=>r[0].transcript).join(' ');
|
||||
const t = $('#note'); t.value = (t.value ? t.value + ' ' : '') + text; t.focus();
|
||||
};
|
||||
rec.onend = () => { on=false; btn.classList.remove('rec'); btn.textContent='🎙 말로 적기'; };
|
||||
rec.onerror = () => toast('음성 인식을 쓰지 못했습니다. 키보드 마이크를 써보세요');
|
||||
btn.onclick = () => { if (on){ rec.stop(); return; } rec.start(); on=true;
|
||||
btn.classList.add('rec'); btn.textContent='● 말하는 중… (눌러서 끝내기)'; };
|
||||
})();
|
||||
|
||||
/* ---------- 항목 프리셋 ---------- */
|
||||
async function loadPresets(){
|
||||
try{
|
||||
const d = await api('/api/presets');
|
||||
S.presets = d.presets;
|
||||
document.querySelectorAll('.chips[data-for]').forEach(box=>{
|
||||
const key = box.dataset.for === 'f-size' ? 'size'
|
||||
: box.dataset.for === 'f-material' ? 'material' : 'care';
|
||||
box.innerHTML = (d.presets[key]||[]).map(v=>`<button class="chip">${v}</button>`).join('');
|
||||
box.querySelectorAll('.chip').forEach(ch=>ch.onclick=()=>{
|
||||
box.querySelectorAll('.chip').forEach(c=>c.setAttribute('aria-pressed','false'));
|
||||
ch.setAttribute('aria-pressed','true');
|
||||
$('#'+box.dataset.for).value = ch.textContent;
|
||||
});
|
||||
});
|
||||
}catch(e){ toast(e.message); }
|
||||
}
|
||||
|
||||
/* ---------- 확인·저장 ---------- */
|
||||
function payload(){
|
||||
return {
|
||||
photos: S.photos.map(p=>p.uid),
|
||||
slug: (S.draft && S.draft.slug) || '',
|
||||
title: $('#f-title').value.trim(),
|
||||
subtitle: $('#f-subtitle').value.trim(),
|
||||
body: $('#f-body').value.trim(),
|
||||
image_alt: $('#f-alt').value.trim(),
|
||||
size: $('#f-size').value.trim(),
|
||||
material: $('#f-material').value.trim(),
|
||||
care: $('#f-care').value.trim(),
|
||||
price: $('#f-price').value.trim(),
|
||||
price_note: $('#f-pricenote').value.trim(),
|
||||
date: $('#f-date').value || new Date().toISOString().slice(0,10),
|
||||
naver_url: $('#f-naver').value.trim(),
|
||||
featured: $('#f-featured').checked,
|
||||
sold_out: $('#f-soldout').checked,
|
||||
force_deploy: $('#force').checked
|
||||
};
|
||||
}
|
||||
function renderSummary(){
|
||||
const p = payload();
|
||||
const price = p.price ? Number(p.price).toLocaleString('ko-KR') + '원' : '가격 문의';
|
||||
$('#summary').innerHTML = `
|
||||
<div class="summary">
|
||||
<b>${p.title || '(제목 없음)'}</b><br>${p.subtitle || ''}<br>
|
||||
사진 ${p.photos.length}장 · ${price}<br>
|
||||
${p.size ? '규격 ' + p.size + '<br>' : ''}
|
||||
${p.material ? '소재 ' + p.material + '<br>' : ''}
|
||||
${p.date}
|
||||
</div>`;
|
||||
}
|
||||
async function doPublish(deploy){
|
||||
if (S.busy) return; S.busy = true;
|
||||
['#pub-deploy','#pub-only'].forEach(s=>$(s).disabled=true);
|
||||
$('#pub-status').innerHTML = '<span class="spin"></span> 저장 중… (사진 변환 → 빌드 → 커밋' + (deploy?' → 배포':'') + ')';
|
||||
try{
|
||||
const d = await api('/api/publish', Object.assign(payload(), {deploy}));
|
||||
const tail = d.deployed ? '사이트에 올렸습니다. '
|
||||
: (deploy ? '저장은 했지만 배포하지 못했습니다.<br><span class="err">' + (d.deploy_log||'') + '</span>'
|
||||
: '배포는 하지 않았습니다. ');
|
||||
$('#pub-status').innerHTML =
|
||||
`저장했습니다 — <b>${d.slug}</b> · 커밋 ${String(d.commit).slice(0,40)}<br>` + tail +
|
||||
`<a class="live" href="${d.url}" target="_blank">상세 페이지 열기</a>`;
|
||||
toast('등록 완료');
|
||||
loadHome();
|
||||
}catch(e){ $('#pub-status').innerHTML = `<span class="status err">${e.message}</span>`; }
|
||||
finally{ S.busy=false; ['#pub-deploy','#pub-only'].forEach(s=>$(s).disabled=false); }
|
||||
}
|
||||
$('#pub-deploy').onclick = () => doPublish(true);
|
||||
$('#pub-only').onclick = () => doPublish(false);
|
||||
|
||||
/* ---------- 시작 ---------- */
|
||||
loadHome(); loadPresets();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "한땀 작업실 — 상품 등록",
|
||||
"short_name": "한땀 등록",
|
||||
"description": "사진을 찍고 내용을 쓰면 작품 상세 페이지가 만들어집니다.",
|
||||
"start_url": "/m",
|
||||
"scope": "/",
|
||||
"display": "standalone",
|
||||
"orientation": "portrait",
|
||||
"background_color": "#F6F2EA",
|
||||
"theme_color": "#F6F2EA",
|
||||
"lang": "ko",
|
||||
"icons": [
|
||||
{"src": "../assets/img/process/stitch.jpg", "sizes": "512x512", "type": "image/jpeg", "purpose": "any"}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
"""휴대폰에서 상품을 등록하는 흐름을 받쳐 주는 모듈.
|
||||
|
||||
studio/server.py 가 import 해서 쓴다. 표준 라이브러리 + macOS 기본 도구(sips)만 쓴다.
|
||||
|
||||
흐름:
|
||||
1) /api/photo 사진을 _inbox 에 임시 저장 -> uid
|
||||
2) /api/caption 사진을 읽어(VLM) 사실을 뽑고 문장을 씀 -> draft
|
||||
3) /api/publish 사진을 assets/img/<slug>/ 로 옮기고 md·빌드·커밋(+배포)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Tuple
|
||||
|
||||
BASE = Path(__file__).resolve().parent
|
||||
ROOT = BASE.parent
|
||||
PRODUCTS = ROOT / "content" / "products"
|
||||
ASSETS = ROOT / "assets"
|
||||
INBOX = BASE / "_inbox"
|
||||
|
||||
CONFIG_DIR = Path.home() / ".config" / "teamat-studio"
|
||||
AI_CONFIG = CONFIG_DIR / "ai.json"
|
||||
VISION_CONFIG = CONFIG_DIR / "vision.json"
|
||||
AI_BASE_URL = "https://api.deepseek.com/v1"
|
||||
AI_MODEL = "deepseek-flash"
|
||||
VISION_URL = "https://integrate.api.nvidia.com/v1/chat/completions"
|
||||
VISION_MODEL = os.environ.get("TEAMAT_VISION_MODEL", "nvidia/nemotron-3.5-super-vl-120b-a12b")
|
||||
MAX_VISION_IMAGES = 3
|
||||
EXTS = (".jpg", ".jpeg")
|
||||
|
||||
# 화면에 칩으로 보여줄 표준값. 자유 입력도 함께 받는다.
|
||||
PRESETS: Dict[str, List[str]] = {
|
||||
"size": [
|
||||
"10 × 10 cm × 4장",
|
||||
"10 × 10 cm (한 장)",
|
||||
"30 × 45 cm",
|
||||
"32 × 48 cm",
|
||||
"20 × 20 cm",
|
||||
],
|
||||
"material": [
|
||||
"린넨 100%, 면사 자수",
|
||||
"면 100% · 사시코 실(면)",
|
||||
"11수 코튼린넨(국내산) · 사시코 전용실",
|
||||
"무명 100%, 면사 자수",
|
||||
],
|
||||
"care": [
|
||||
"미지근한 물에 중성세제로 단독 손세탁",
|
||||
"자수 완성 전 다림질 금지 · 물세탁은 30분 담갔다 그늘 건조",
|
||||
"물세탁하지 않고 그늘에서 털어 말리기",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ inbox (사진)
|
||||
|
||||
|
||||
def inbox_save(name: str, data: bytes) -> Dict[str, Any]:
|
||||
if not data:
|
||||
return {"ok": False, "error": "사진 데이터가 비었습니다"}
|
||||
ext = Path(name or "photo.jpg").suffix.lower()
|
||||
if ext not in EXTS:
|
||||
return {"ok": False, "error": "JPG 사진만 올릴 수 있습니다"}
|
||||
INBOX.mkdir(parents=True, exist_ok=True)
|
||||
uid = secrets.token_hex(6)
|
||||
(INBOX / f"{uid}.jpg").write_bytes(data)
|
||||
return {"ok": True, "uid": uid, "bytes": len(data)}
|
||||
|
||||
|
||||
def inbox_path(uid: str) -> Path:
|
||||
if not re.fullmatch(r"[0-9a-f]{12}", uid or ""):
|
||||
raise ValueError("사진 식별자가 올바르지 않습니다")
|
||||
path = INBOX / f"{uid}.jpg"
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError("사진이 없습니다(다시 찍어 주세요)")
|
||||
return path
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- AI 호출
|
||||
|
||||
|
||||
def _ai_cfg() -> Dict[str, str]:
|
||||
if os.environ.get("DEEPSEEK_API_KEY", "").strip():
|
||||
return {"api_key": os.environ["DEEPSEEK_API_KEY"].strip(), "base_url": AI_BASE_URL,
|
||||
"model": os.environ.get("DEEPSEEK_MODEL", AI_MODEL)}
|
||||
if AI_CONFIG.is_file():
|
||||
data = json.loads(AI_CONFIG.read_text(encoding="utf-8"))
|
||||
if data.get("api_key"):
|
||||
return {"api_key": str(data["api_key"]), "base_url": str(data.get("base_url") or AI_BASE_URL),
|
||||
"model": str(data.get("model") or AI_MODEL)}
|
||||
raise RuntimeError("DeepSeek API 키가 없습니다 (~/.config/teamat-studio/ai.json)")
|
||||
|
||||
|
||||
def _vision_key() -> str:
|
||||
if os.environ.get("NVIDIA_API_KEY", "").strip():
|
||||
return os.environ["NVIDIA_API_KEY"].strip()
|
||||
if VISION_CONFIG.is_file():
|
||||
data = json.loads(VISION_CONFIG.read_text(encoding="utf-8"))
|
||||
if data.get("api_key"):
|
||||
return str(data["api_key"])
|
||||
raise RuntimeError("사진 판독(VLM) 키가 없습니다 (~/.config/teamat-studio/vision.json 의 api_key)")
|
||||
|
||||
|
||||
def vision_status() -> Dict[str, Any]:
|
||||
try:
|
||||
_vision_key()
|
||||
except RuntimeError as error:
|
||||
return {"ok": True, "configured": False, "error": str(error), "model": VISION_MODEL}
|
||||
return {"ok": True, "configured": True, "model": VISION_MODEL}
|
||||
|
||||
|
||||
def _shrink(path: Path, limit: int = 900) -> bytes:
|
||||
"""VLM 에 보낼 용량 줄이기. sips 는 macOS 기본 도구."""
|
||||
tmp = INBOX / (path.stem + f"-v{limit}.jpg")
|
||||
ok = subprocess.run(["sips", "-Z", str(limit), "-s", "format", "jpeg",
|
||||
"-s", "formatOptions", "75", str(path), "--out", str(tmp)],
|
||||
capture_output=True).returncode == 0
|
||||
data = tmp.read_bytes() if ok and tmp.is_file() else path.read_bytes()
|
||||
tmp.unlink(missing_ok=True)
|
||||
return data
|
||||
|
||||
|
||||
VISION_PROMPT = """이 사진들만 보고, 한국 공방의 상품 설명에 쓸 사실만 뽑아라.
|
||||
지어내지 말고 사진에서 확인되는 것만 적는다. 추측하면 "추정"이라고 표시한다.
|
||||
다음 다섯 줄 형식으로만 답한다(설명·인사말 없이).
|
||||
① 사물:
|
||||
② 색:
|
||||
③ 무늬/패턴:
|
||||
④ 재질 추정:
|
||||
⑤ 개수:
|
||||
사진이 여러 장이면 장마다 무엇이 다른지도 한 줄 덧붙인다."""
|
||||
|
||||
|
||||
def photo_facts(uids: List[str]) -> Dict[str, Any]:
|
||||
"""사진에서 사실을 뽑는다(비전 모델). 실패해도 등록은 계속되도록 예외를 돌려준다."""
|
||||
key = _vision_key()
|
||||
chosen = uids[:MAX_VISION_IMAGES]
|
||||
parts: List[Dict[str, Any]] = [{"type": "text", "text": VISION_PROMPT}]
|
||||
for uid in chosen:
|
||||
path = inbox_path(uid)
|
||||
b64 = base64.b64encode(_shrink(path)).decode("ascii")
|
||||
parts.append({"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + b64}})
|
||||
payload = {"model": VISION_MODEL, "max_tokens": 1800, "temperature": 0.2,
|
||||
"messages": [{"role": "user", "content": parts}]}
|
||||
request = urllib.request.Request(
|
||||
VISION_URL, data=json.dumps(payload).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json", "Authorization": "Bearer " + key}, method="POST")
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=180) as response:
|
||||
body = json.loads(response.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as error:
|
||||
detail = error.read().decode("utf-8", "replace")[:300]
|
||||
raise RuntimeError(f"사진 판독 오류 {error.code}: {detail}") from error
|
||||
except urllib.error.URLError as error:
|
||||
raise RuntimeError(f"사진 판독 연결 실패: {error.reason}") from error
|
||||
|
||||
message = (body.get("choices") or [{}])[0].get("message", {})
|
||||
text = (message.get("content") or "").strip()
|
||||
if not text:
|
||||
raise RuntimeError("사진 판독 결과가 비었습니다(다시 시도해 주세요)")
|
||||
return {"ok": True, "model": body.get("model") or VISION_MODEL, "facts": text[:1200],
|
||||
"images": len(chosen), "tokens": (body.get("usage") or {}).get("total_tokens")}
|
||||
|
||||
|
||||
WRITE_SYSTEM = """너는 한국의 핸드메이드 자수 브랜드 "한땀"의 카피라이터다.
|
||||
|
||||
브랜드: 아이보리 린넨·무명 위에 면사로 그림을 놓는 작은 작업실. 타깃은 40~50대 여성.
|
||||
톤: 담백하고 구체적. 재료와 시간을 숫자로 말한다("린넨 100%", "30 × 45 cm", "열흘 남짓").
|
||||
|
||||
규칙:
|
||||
1. 주어진 사실(사진에서 읽은 것, 입력된 값) 밖의 내용을 만들지 않는다.
|
||||
후기·별점·판매량·수상·재고·할인·배송 약속 금지.
|
||||
2. 이모지 금지, 느낌표 남용 금지, "최고급/완벽한/특별한/럭셔리" 금지.
|
||||
3. 본문은 2~4문단, 문단당 2~3문장. 줄바꿈은 빈 줄로 문단을 나눈다.
|
||||
4. 사진에서 읽은 것과 사용자가 적은 메모를 우선한다. 확인되지 않은 규격·가격은 쓰지 않는다.
|
||||
사진 해석과 메모가 어긋나면 **메모를 따른다**.
|
||||
5. 사진을 어떻게 읽었는지 설명하는 문장을 본문에 쓰지 않는다.
|
||||
("사진에서는 …로 보입니다", "메모에는 …로 적혀 있습니다" 같은 문장 금지)
|
||||
6. 같은 내용을 두 문단에 반복하지 않는다.
|
||||
7. 한국어로만 쓴다.
|
||||
|
||||
응답은 설명 없이 JSON 하나만:
|
||||
{"title": "제목(20자 안쪽)", "subtitle": "부제(15자 안쪽)", "image_alt": "대표 사진 설명 1문장",
|
||||
"slug": "영문-소문자-하이픈", "body": "본문 전문"}
|
||||
"""
|
||||
|
||||
|
||||
def _ai_json(system: str, user: str, max_tokens: int = 2600) -> Dict[str, Any]:
|
||||
cfg = _ai_cfg()
|
||||
payload = {"model": cfg["model"],
|
||||
"messages": [{"role": "system", "content": system}, {"role": "user", "content": user}],
|
||||
"temperature": 0.4, "max_tokens": max_tokens,
|
||||
"response_format": {"type": "json_object"}}
|
||||
request = urllib.request.Request(
|
||||
cfg["base_url"].rstrip("/") + "/chat/completions",
|
||||
data=json.dumps(payload).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json", "Authorization": "Bearer " + cfg["api_key"]},
|
||||
method="POST")
|
||||
last = "빈 응답"
|
||||
for attempt in range(3):
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=240) as response:
|
||||
body = json.loads(response.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as error:
|
||||
detail = error.read().decode("utf-8", "replace")[:300]
|
||||
raise RuntimeError(f"AI 오류 {error.code}: {detail}") from error
|
||||
except urllib.error.URLError as error:
|
||||
raise RuntimeError(f"AI 연결 실패: {error.reason}") from error
|
||||
choice = (body.get("choices") or [{}])[0]
|
||||
text = (choice.get("message", {}).get("content") or "").strip()
|
||||
if text:
|
||||
match = re.search(r"\{.*\}", text, re.S)
|
||||
try:
|
||||
return {"data": json.loads(text if text.startswith("{") else match.group(0)),
|
||||
"model": body.get("model"), "tokens": (body.get("usage") or {}).get("total_tokens")}
|
||||
except (json.JSONDecodeError, AttributeError):
|
||||
last = f"JSON 아님(finish={choice.get('finish_reason')}): {text[:120]}"
|
||||
else:
|
||||
last = f"빈 응답(finish={choice.get('finish_reason')})"
|
||||
time.sleep(1.5)
|
||||
raise RuntimeError(f"AI가 문장을 만들지 못했습니다 — {last}. 다시 눌러 주세요")
|
||||
|
||||
|
||||
def caption(payload: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""사진 → 사실 → 원고. 사진 판독이 실패해도 메모만으로 원고를 쓴다."""
|
||||
uids = [str(u) for u in (payload.get("photos") or [])][:12]
|
||||
note = str(payload.get("note") or "").strip()
|
||||
known = payload.get("known") or {}
|
||||
facts = ""
|
||||
warning = ""
|
||||
if uids:
|
||||
try:
|
||||
facts = photo_facts(uids)["facts"]
|
||||
except (RuntimeError, ValueError, FileNotFoundError) as error:
|
||||
warning = str(error)
|
||||
facts = "(사진 판독 실패 — 메모와 입력값만 사용)"
|
||||
|
||||
user = json.dumps({
|
||||
"사진에서_읽은_것": facts,
|
||||
"사용자_메모": note or "(없음)",
|
||||
"이미_정해진_값": known,
|
||||
"요청": "이 작품의 제목·부제·이미지 설명·본문을 쓴다. 값이 정해진 항목은 그대로 따른다.",
|
||||
}, ensure_ascii=False, indent=2)
|
||||
result = _ai_json(WRITE_SYSTEM, user)
|
||||
data = result["data"] or {}
|
||||
slug = re.sub(r"[^a-z0-9-]+", "-", str(data.get("slug") or "").lower()).strip("-")
|
||||
draft = {
|
||||
"title": str(data.get("title") or "").strip()[:40],
|
||||
"subtitle": str(data.get("subtitle") or "").strip()[:40],
|
||||
"image_alt": str(data.get("image_alt") or "").strip(),
|
||||
"slug": slug,
|
||||
"body": str(data.get("body") or "").strip(),
|
||||
}
|
||||
return {"ok": True, "facts": facts, "warning": warning, "draft": draft,
|
||||
"model": result["model"], "tokens": result["tokens"]}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ publish
|
||||
|
||||
|
||||
DEFAULT_ORDER = ["slug", "title", "subtitle", "date", "price", "price_note", "sold_out", "featured",
|
||||
"image", "image_alt", "gallery", "material", "size", "care", "naver_url"]
|
||||
|
||||
|
||||
def _value(text: Any) -> str:
|
||||
if isinstance(text, bool):
|
||||
return "true" if text else "false"
|
||||
if isinstance(text, int):
|
||||
return str(text)
|
||||
raw = str(text if text is not None else "")
|
||||
if raw == "" or re.search(r"[:#\"'\n]|^\s|\s$", raw):
|
||||
return '"' + raw.replace('"', '\\"') + '"'
|
||||
return raw
|
||||
|
||||
|
||||
def _normalize_slug(raw: str, title: str, date: str) -> str:
|
||||
slug = re.sub(r"[^a-z0-9-]+", "-", (raw or "").lower()).strip("-")
|
||||
if not re.fullmatch(r"\d{4}-\d{2}-[a-z0-9-]+", slug or ""):
|
||||
base = slug or "work"
|
||||
slug = f"{date[:7]}-{base}"
|
||||
slug = slug[:60].strip("-")
|
||||
candidate, index = slug, 2
|
||||
while (PRODUCTS / f"{candidate}.md").exists() or (ASSETS / "img" / candidate).exists():
|
||||
candidate = f"{slug}-{index}"
|
||||
index += 1
|
||||
return candidate
|
||||
|
||||
|
||||
def _orient(path: Path) -> None:
|
||||
"""EXIF 회전 정보를 픽셀에 반영한다(빌드가 JPEG 크기를 직접 읽으므로 가로/세로가 뒤집히면 안 된다)."""
|
||||
try:
|
||||
info = subprocess.run(["sips", "-g", "orientation", str(path)],
|
||||
capture_output=True, text=True, timeout=30).stdout
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return
|
||||
match = re.search(r"orientation:\s*(\d+)", info or "")
|
||||
if not match:
|
||||
return
|
||||
degrees = {"6": "90", "8": "270", "3": "180"}.get(match.group(1))
|
||||
if degrees:
|
||||
subprocess.run(["sips", "-r", degrees, str(path)], capture_output=True, timeout=60)
|
||||
|
||||
|
||||
def _to_jpeg(source: Path, target: Path, limit: int = 1400) -> None:
|
||||
ok = subprocess.run(["sips", "-Z", str(limit), "-s", "format", "jpeg",
|
||||
"-s", "formatOptions", "80", str(source), "--out", str(target)],
|
||||
capture_output=True, timeout=120).returncode == 0
|
||||
if not ok or not target.is_file():
|
||||
shutil.copyfile(source, target)
|
||||
_orient(target)
|
||||
|
||||
|
||||
def _other_drafts(slug: str) -> List[str]:
|
||||
"""커밋되지 않은 다른 작품 초안. 배포하면 함께 올라가므로 미리 알린다."""
|
||||
proc = subprocess.run(["git", "status", "--porcelain", "--", "content/products"],
|
||||
cwd=str(ROOT), capture_output=True, text=True, timeout=30)
|
||||
names: List[str] = []
|
||||
for line in (proc.stdout or "").splitlines():
|
||||
path = line[3:].strip()
|
||||
if path.endswith(".md") and not path.endswith(f"/{slug}.md"):
|
||||
names.append(Path(path).stem)
|
||||
return names
|
||||
|
||||
|
||||
def publish(payload: Dict[str, Any], helpers: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""사진 + 값 -> md 한 개. 빌드 실패하면 원상 복구한다.
|
||||
|
||||
helpers: build(), git_commit(message, paths), deploy() 를 넘겨받아 쓴다(순환 import 회피).
|
||||
"""
|
||||
photos = [str(u) for u in (payload.get("photos") or [])]
|
||||
title = str(payload.get("title") or "").strip()
|
||||
body = str(payload.get("body") or "").strip()
|
||||
if not title:
|
||||
raise ValueError("제목을 넣어 주세요")
|
||||
if not body:
|
||||
raise ValueError("본문을 넣어 주세요")
|
||||
if not photos:
|
||||
raise ValueError("사진을 한 장 이상 올려 주세요")
|
||||
|
||||
date = str(payload.get("date") or datetime.now().strftime("%Y-%m-%d"))[:10]
|
||||
if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", date):
|
||||
date = datetime.now().strftime("%Y-%m-%d")
|
||||
slug = _normalize_slug(str(payload.get("slug") or ""), title, date)
|
||||
|
||||
price_raw = payload.get("price")
|
||||
price: Any = ""
|
||||
if str(price_raw or "").strip() not in ("", "0"):
|
||||
digits = re.sub(r"[^0-9]", "", str(price_raw))
|
||||
price = int(digits) if digits else ""
|
||||
|
||||
image_dir = ASSETS / "img" / slug
|
||||
image_dir.mkdir(parents=True, exist_ok=True)
|
||||
sources = [inbox_path(uid) for uid in photos]
|
||||
cover = f"assets/img/{slug}/cover.jpg"
|
||||
_to_jpeg(sources[0], ROOT / cover)
|
||||
gallery: List[str] = []
|
||||
for index, source in enumerate(sources[1:], start=1):
|
||||
name = f"detail-{index:02d}.jpg"
|
||||
_to_jpeg(source, image_dir / name)
|
||||
gallery.append(f"assets/img/{slug}/{name}")
|
||||
|
||||
data: Dict[str, Any] = {
|
||||
"slug": slug,
|
||||
"title": title,
|
||||
"subtitle": str(payload.get("subtitle") or "").strip(),
|
||||
"date": date,
|
||||
"price": price,
|
||||
"price_note": str(payload.get("price_note") or "").strip(),
|
||||
"sold_out": bool(payload.get("sold_out")),
|
||||
"featured": bool(payload.get("featured")),
|
||||
"image": cover,
|
||||
"image_alt": str(payload.get("image_alt") or title).strip(),
|
||||
"gallery": gallery,
|
||||
"material": str(payload.get("material") or "").strip(),
|
||||
"size": str(payload.get("size") or "").strip(),
|
||||
"care": str(payload.get("care") or "").strip(),
|
||||
"naver_url": str(payload.get("naver_url") or "").strip(),
|
||||
}
|
||||
|
||||
lines: List[str] = ["---"]
|
||||
for key in DEFAULT_ORDER:
|
||||
value = data.get(key, "")
|
||||
if key == "gallery":
|
||||
if value:
|
||||
lines.append("gallery:")
|
||||
lines.extend(f"- {_value(item)}" for item in value)
|
||||
else:
|
||||
lines.append("gallery:")
|
||||
continue
|
||||
lines.append(f"{key}: {_value(value)}")
|
||||
lines.append("---")
|
||||
md_path = PRODUCTS / f"{slug}.md"
|
||||
md_path.write_text("\n".join(lines) + "\n" + body.rstrip() + "\n", encoding="utf-8")
|
||||
|
||||
ok, log = helpers["build"]()
|
||||
if not ok:
|
||||
md_path.unlink(missing_ok=True)
|
||||
shutil.rmtree(image_dir, ignore_errors=True)
|
||||
raise RuntimeError(f"빌드 실패로 저장을 되돌렸습니다: {log[-400:]}")
|
||||
|
||||
commit_ok, commit_log = helpers["git_commit"](
|
||||
f"상품 추가: {title} ({price or '가격 문의'})",
|
||||
[str(md_path.relative_to(ROOT)), str(image_dir.relative_to(ROOT))])
|
||||
if not commit_ok:
|
||||
raise RuntimeError(f"커밋 실패: {commit_log}")
|
||||
|
||||
for source in sources:
|
||||
source.unlink(missing_ok=True)
|
||||
|
||||
drafts = _other_drafts(slug)
|
||||
|
||||
deploy_ok, deploy_log = (True, "배포하지 않음")
|
||||
if payload.get("deploy"):
|
||||
if drafts and not payload.get("force_deploy"):
|
||||
deploy_ok = False
|
||||
deploy_log = ("커밋하지 않은 다른 초안이 있어 배포를 건너뛰었습니다: " + ", ".join(drafts)
|
||||
+ "\n그 초안까지 함께 올리려면 '다른 초안도 올리기'를 켜고 다시 저장하세요.")
|
||||
else:
|
||||
deploy_ok, deploy_log = helpers["deploy"]()
|
||||
|
||||
return {"ok": True, "slug": slug, "title": title, "commit": commit_log,
|
||||
"deployed": bool(payload.get("deploy")) and deploy_ok,
|
||||
"other_drafts": drafts,
|
||||
"build_log": log, "deploy_log": deploy_log[-400:],
|
||||
"url": f"/p/{slug}.html"}
|
||||
+98
-3
@@ -23,13 +23,19 @@ import urllib.request
|
||||
from datetime import datetime
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Tuple
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
BASE = Path(__file__).resolve().parent
|
||||
ROOT = BASE.parent
|
||||
PRODUCTS = ROOT / "content" / "products"
|
||||
ASSETS = ROOT / "assets"
|
||||
APP = BASE / "app.html"
|
||||
MOBILE = BASE / "m.html"
|
||||
MANIFEST = BASE / "manifest.json"
|
||||
TOKEN_FILE = Path.home() / ".config" / "teamat-studio" / "token"
|
||||
|
||||
import register as reg # 휴대폰 등록 흐름(사진 인박스·판독·발행)
|
||||
|
||||
LIST_KEYS = {"gallery"}
|
||||
|
||||
# ---- AI(DeepSeek) 설정 ------------------------------------------------------
|
||||
@@ -574,6 +580,16 @@ def ai_draft(prompt: str) -> Dict[str, Any]:
|
||||
# ------------------------------------------------------------------------ server
|
||||
|
||||
|
||||
def studio_token() -> str:
|
||||
"""휴대폰에서 접속할 때 쓰는 열쇠. 비어 있으면 인증 없이 로컬에서만 쓰는 모드."""
|
||||
token = os.environ.get("STUDIO_TOKEN", "").strip()
|
||||
if token:
|
||||
return token
|
||||
if TOKEN_FILE.is_file():
|
||||
return TOKEN_FILE.read_text(encoding="utf-8").strip()
|
||||
return ""
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "hanttam-studio"
|
||||
protocol_version = "HTTP/1.1"
|
||||
@@ -582,14 +598,36 @@ class Handler(BaseHTTPRequestHandler):
|
||||
pass
|
||||
|
||||
# -- helpers ---------------------------------------------------------
|
||||
def send_body(self, code: int, body: bytes, ctype: str = "application/json; charset=utf-8") -> None:
|
||||
def send_body(self, code: int, body: bytes, ctype: str = "application/json; charset=utf-8",
|
||||
extra: Optional[List[Tuple[str, str]]] = None) -> None:
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
for key, value in (extra or []):
|
||||
self.send_header(key, value)
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def authed(self) -> bool:
|
||||
"""열쇠가 설정돼 있으면 쿠키나 ?t= 로 확인한다(테일스케일 너머 폰 접속용)."""
|
||||
token = studio_token()
|
||||
if not token:
|
||||
return True
|
||||
cookie = self.headers.get("Cookie") or ""
|
||||
if any(part.strip() == "studio_token=" + token for part in cookie.split(";")):
|
||||
return True
|
||||
query = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
|
||||
self._grant = (query.get("t") or [""])[0] == token
|
||||
return self._grant
|
||||
|
||||
def send_page(self, path: Path, ctype: str = "text/html; charset=utf-8") -> None:
|
||||
extra: List[Tuple[str, str]] = []
|
||||
token = studio_token()
|
||||
if token and getattr(self, "_grant", False):
|
||||
extra.append(("Set-Cookie", f"studio_token={token}; Path=/; Max-Age=31536000; HttpOnly; SameSite=Lax"))
|
||||
self.send_body(200, path.read_bytes(), ctype, extra)
|
||||
|
||||
def send_json(self, obj: Any, code: int = 200) -> None:
|
||||
self.send_body(code, json.dumps(obj, ensure_ascii=False).encode("utf-8"))
|
||||
|
||||
@@ -608,8 +646,30 @@ class Handler(BaseHTTPRequestHandler):
|
||||
path = parsed.path
|
||||
query = urllib.parse.parse_qs(parsed.query)
|
||||
|
||||
if not self.authed():
|
||||
self.send_json({"ok": False, "error": "열쇠가 필요합니다 — 주소 뒤에 ?t=<토큰> 을 붙여 한 번만 열어 주세요"}, 401)
|
||||
return
|
||||
|
||||
if path in ("/", "/index.html"):
|
||||
self.send_body(200, APP.read_bytes(), "text/html; charset=utf-8")
|
||||
self.send_page(APP)
|
||||
return
|
||||
if path in ("/m", "/m.html"):
|
||||
self.send_page(MOBILE)
|
||||
return
|
||||
if path == "/manifest.json":
|
||||
self.send_page(MANIFEST, "application/manifest+json; charset=utf-8")
|
||||
return
|
||||
if path.startswith("/media-inbox/"):
|
||||
uid = path[len("/media-inbox/"):].split(".", 1)[0]
|
||||
try:
|
||||
target = reg.inbox_path(uid)
|
||||
except (ValueError, FileNotFoundError) as error:
|
||||
self.send_json({"ok": False, "error": str(error)}, 404)
|
||||
return
|
||||
self.send_body(200, target.read_bytes(), "image/jpeg")
|
||||
return
|
||||
if path == "/api/presets":
|
||||
self.send_json({"ok": True, "presets": reg.PRESETS, "vision": reg.vision_status()})
|
||||
return
|
||||
if path == "/api/state":
|
||||
rows = summaries()
|
||||
@@ -662,6 +722,35 @@ class Handler(BaseHTTPRequestHandler):
|
||||
path = parsed.path
|
||||
query = urllib.parse.parse_qs(parsed.query)
|
||||
|
||||
if not self.authed():
|
||||
self.send_json({"ok": False, "error": "열쇠가 필요합니다 — 주소 뒤에 ?t=<토큰> 을 붙여 다시 열어 주세요"}, 401)
|
||||
return
|
||||
|
||||
if path == "/api/photo":
|
||||
name = (query.get("name") or ["photo.jpg"])[0]
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
data = self.rfile.read(length) if length else b""
|
||||
self.send_json(reg.inbox_save(name, data))
|
||||
return
|
||||
if path == "/api/caption":
|
||||
try:
|
||||
self.send_json(reg.caption(self.read_json()))
|
||||
except FileNotFoundError as error:
|
||||
self.send_json({"ok": False, "error": str(error)}, 404)
|
||||
except ValueError as error:
|
||||
self.send_json({"ok": False, "error": str(error)}, 400)
|
||||
except RuntimeError as error:
|
||||
self.send_json({"ok": False, "error": str(error)}, 502)
|
||||
return
|
||||
if path == "/api/publish":
|
||||
helpers = {"build": build, "git_commit": git_commit, "deploy": deploy}
|
||||
try:
|
||||
self.send_json(reg.publish(self.read_json(), helpers))
|
||||
except ValueError as error:
|
||||
self.send_json({"ok": False, "error": str(error)}, 400)
|
||||
except (RuntimeError, FileNotFoundError) as error:
|
||||
self.send_json({"ok": False, "error": str(error)}, 500)
|
||||
return
|
||||
if path == "/api/product":
|
||||
try:
|
||||
self.send_json(save_product(self.read_json()))
|
||||
@@ -717,6 +806,12 @@ def main() -> None:
|
||||
|
||||
server = ThreadingHTTPServer((args.host, args.port), Handler)
|
||||
print(f"한땀 작업실: http://{args.host}:{args.port} (repo {ROOT})")
|
||||
print(" · 책상 화면: / · 폰 등록 화면: /m")
|
||||
token = studio_token()
|
||||
if token:
|
||||
print(f" · 열쇠 있음({token[:4]}…) — 폰에서 /m?t=<토큰> 으로 한 번 열면 쿠키에 저장됩니다")
|
||||
else:
|
||||
print(" · 열쇠 없음(이 컴퓨터에서만). 폰에서 열려면 ~/.config/teamat-studio/token 파일을 만드세요")
|
||||
try:
|
||||
server.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
|
||||
Reference in new issue
Block a user