Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4dff91b483 | ||
|
|
109bd93bd2 |
No files matched your search
@@ -8,6 +8,8 @@
|
|||||||
1. **DB·서버·CMS 를 만들지 않는다.** 정적 HTML/CSS/JS 만. Node/npm/pip 패키지 금지.
|
1. **DB·서버·CMS 를 만들지 않는다.** 정적 HTML/CSS/JS 만. Node/npm/pip 패키지 금지.
|
||||||
- 예외: `studio/` 는 사이트가 아니라 **아이맥 로컬 편집 도구**다(표준 라이브러리만, 127.0.0.1 전용, `dist/` 에 포함되지 않음). 이 예외를 근거로 사이트에 서버 기능을 붙이지 않는다.
|
- 예외: `studio/` 는 사이트가 아니라 **아이맥 로컬 편집 도구**다(표준 라이브러리만, 127.0.0.1 전용, `dist/` 에 포함되지 않음). 이 예외를 근거로 사이트에 서버 기능을 붙이지 않는다.
|
||||||
2. **빌드는 `python3 build.py` 하나.** 표준 라이브러리만 사용.
|
2. **빌드는 `python3 build.py` 하나.** 표준 라이브러리만 사용.
|
||||||
|
- AI(DeepSeek) 호출은 `studio/server.py` 안에서만. 빌드·사이트 코드에 AI 를 넣지 않는다.
|
||||||
|
- AI 제안은 사람이 적용·저장해야 파일이 바뀐다(자동 저장 금지). AI 가 쓴 수치는 저장 전에 확인한다.
|
||||||
3. **모든 링크·이미지 경로는 상대경로.** 사이트는 `https://home.lala.dedyn.io/teamat/` 서브패스에서 서빙된다.
|
3. **모든 링크·이미지 경로는 상대경로.** 사이트는 `https://home.lala.dedyn.io/teamat/` 서브패스에서 서빙된다.
|
||||||
4. **`dist/` 는 커밋하지 않는다.** 소스에서 언제든 재생성된다. 롤백 단위는 커밋 하나.
|
4. **`dist/` 는 커밋하지 않는다.** 소스에서 언제든 재생성된다. 롤백 단위는 커밋 하나.
|
||||||
5. **`git push --force` 금지.** 되돌리기는 `git revert`.
|
5. **`git push --force` 금지.** 되돌리기는 `git revert`.
|
||||||
|
|||||||
@@ -52,7 +52,12 @@ bash scripts/studio.sh # http://localhost:8081
|
|||||||
- 상단 `이력 / 되돌리기` = 최근 커밋 목록과 `git revert`
|
- 상단 `이력 / 되돌리기` = 최근 커밋 목록과 `git revert`
|
||||||
- 작품 상세 페이지의 `이 작품 고치기` 버튼은 localhost 에서만 보인다 (운영 사이트에서는 hidden)
|
- 작품 상세 페이지의 `이 작품 고치기` 버튼은 localhost 에서만 보인다 (운영 사이트에서는 hidden)
|
||||||
- 이미지: JPG 를 끌어다 놓으면 `assets/img/` 에 저장되고 경로가 자동 입력된다
|
- 이미지: JPG 를 끌어다 놓으면 `assets/img/` 에 저장되고 경로가 자동 입력된다
|
||||||
- 단축키: `/` 검색, `↑↓` 이동, `⌘S` 저장
|
- **AI 프롬프트**: 입력창에 말로 시키면 부제·본문·소재·규격을 고친 제안을 보여준다. 아무것도 자동 저장되지 않고 `폼에 적용` 또는 `적용하고 저장`을 눌러야 반영된다
|
||||||
|
- 모드 `새 작품 초안` = 제목·가격·규격을 주면 원고와 slug 를 만들어 폼에 열어준다(이미지·슬러그 확인 후 저장)
|
||||||
|
- 모델 `deepseek-flash`. 키는 `~/.config/teamat-studio/ai.json`(600) 또는 `DEEPSEEK_API_KEY`
|
||||||
|
- AI 가 쓴 사실(기간·소재 등)은 저장 전에 사람이 확인한다. 근거 없는 수치는 넣지 않도록 프롬프트에 규칙을 넣어 두었지만 보증은 아니다
|
||||||
|
- 바로 실행 딥링크: `/?slug=<slug>&prompt=<내용>&run=1`
|
||||||
|
- 단축키: `/` 검색, `↑↓` 이동, `⌘S` 저장, 프롬프트에서 `⌘Enter` 실행
|
||||||
- 서버는 `127.0.0.1` 에만 붙는다. 외부에서 접근되지 않는다
|
- 서버는 `127.0.0.1` 에만 붙는다. 외부에서 접근되지 않는다
|
||||||
|
|
||||||
## 대화로 고치기
|
## 대화로 고치기
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
slug: whitework-tea-mat
|
slug: whitework-tea-mat
|
||||||
title: 목련 한 땀 티매트
|
title: 목련 한 땀 사시코 티매트
|
||||||
subtitle: 봄볕에 널어둔 천
|
subtitle: 봄볕에 널어둔 천
|
||||||
date: 2026-10-28
|
date: 2026-10-28
|
||||||
price: 58000
|
price: 58000
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""AI 프롬프트 수정/초안 API 스모크 테스트 — 호출만 하고 저장은 하지 않는다."""
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
BASE = "http://127.0.0.1:8081"
|
||||||
|
fails = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, cond, extra=""):
|
||||||
|
print(("OK " if cond else "FAIL ") + name + (f"\n {extra}" if extra else ""))
|
||||||
|
if not cond:
|
||||||
|
fails.append(name)
|
||||||
|
|
||||||
|
|
||||||
|
def post(path, payload):
|
||||||
|
request = urllib.request.Request(
|
||||||
|
BASE + path,
|
||||||
|
data=json.dumps(payload).encode(),
|
||||||
|
headers={"Content-Type": "application/json"},
|
||||||
|
method="POST",
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(request, timeout=300) as res:
|
||||||
|
return res.status, json.loads(res.read().decode())
|
||||||
|
except urllib.error.HTTPError as error:
|
||||||
|
body = error.read().decode()
|
||||||
|
try:
|
||||||
|
return error.code, json.loads(body)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return error.code, {"raw": body}
|
||||||
|
|
||||||
|
|
||||||
|
def git_status():
|
||||||
|
return subprocess.run(["git", "status", "--porcelain"], cwd="/Users/woozooni/Projects/teamat",
|
||||||
|
capture_output=True, text=True).stdout.strip()
|
||||||
|
|
||||||
|
|
||||||
|
before_status = git_status()
|
||||||
|
before_head = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd="/Users/woozooni/Projects/teamat",
|
||||||
|
capture_output=True, text=True).stdout.strip()
|
||||||
|
|
||||||
|
# 1) 작품 수정 제안
|
||||||
|
code, data = post("/api/ai", {"mode": "edit", "slug": "whitework-tea-mat",
|
||||||
|
"prompt": "부제를 더 담백하게, 20자 이내로. 본문은 그대로 둬."})
|
||||||
|
check("edit 200", code == 200 and data.get("ok") is True, json.dumps(data, ensure_ascii=False)[:400])
|
||||||
|
if data.get("ok"):
|
||||||
|
check("note 있음", bool(data.get("note")), str(data.get("note")))
|
||||||
|
check("변경 있음", bool(data.get("changes")), json.dumps({k: v for k, v in data.get("changes", {}).items() if k != "body"}, ensure_ascii=False))
|
||||||
|
check("부제만 바뀜", set(data.get("changes", {}).keys()) <= {"subtitle"}, str(list(data.get("changes", {}).keys())))
|
||||||
|
check("본문 유지", "body" not in data.get("changes", {}))
|
||||||
|
print(" 제안:", data.get("note"))
|
||||||
|
for k, v in data.get("changes", {}).items():
|
||||||
|
print(f" {k}: {str(v)[:120]}")
|
||||||
|
|
||||||
|
# 2) 본문 다시 쓰기
|
||||||
|
code, data2 = post("/api/ai", {"mode": "edit", "slug": "whitework-tea-mat",
|
||||||
|
"prompt": "본문을 3문단으로 다시 써. 재료와 걸린 시간을 숫자로 넣어."})
|
||||||
|
if data2.get("ok"):
|
||||||
|
body = data2.get("changes", {}).get("body", "")
|
||||||
|
check("본문 변경 제안", bool(body), str(list(data2.get("changes", {}).keys())))
|
||||||
|
check("본문 3문단 근사", body.count("\n\n") >= 1, str(body.count("\n\n")))
|
||||||
|
print(" 본문 앞부분:", body[:160].replace("\n", " / "))
|
||||||
|
|
||||||
|
# 3) 새 작품 초안
|
||||||
|
code, draft = post("/api/ai", {"mode": "draft",
|
||||||
|
"prompt": "겨울 매화 티매트, 32×48cm, 린넨 100%, 62000원. 눈 내린 창가 분위기."})
|
||||||
|
check("draft 200", code == 200 and draft.get("ok") is True, json.dumps(draft, ensure_ascii=False)[:400])
|
||||||
|
if draft.get("ok"):
|
||||||
|
fields = draft.get("fields", {})
|
||||||
|
check("draft 제목", bool(str(fields.get("title", "")).strip()), str(fields.get("title")))
|
||||||
|
check("draft slug 형식", bool(fields.get("slug")) and all(c.islower() or c.isdigit() or c == "-" for c in str(fields.get("slug"))), str(fields.get("slug")))
|
||||||
|
check("draft 본문", len(str(draft.get("body", ""))) > 60, str(len(str(draft.get("body", "")))))
|
||||||
|
print(" 초안:", fields.get("slug"), "|", fields.get("title"), "|", fields.get("price"), "|", fields.get("size"))
|
||||||
|
|
||||||
|
# 4) 빈 요청 거부
|
||||||
|
code, bad = post("/api/ai", {"mode": "edit", "slug": "whitework-tea-mat", "prompt": ""})
|
||||||
|
check("빈 요청 거부", code == 400, str(code))
|
||||||
|
|
||||||
|
# 5) AI 호출이 저장소를 건드리지 않아야 한다
|
||||||
|
check("git 상태 불변", git_status() == before_status, git_status())
|
||||||
|
check("HEAD 불변", subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd="/Users/woozooni/Projects/teamat",
|
||||||
|
capture_output=True, text=True).stdout.strip() == before_head)
|
||||||
|
|
||||||
|
print()
|
||||||
|
print("실패 " + str(len(fails)) + "건: " + ", ".join(fails) if fails else "전부 통과")
|
||||||
|
sys.exit(1 if fails else 0)
|
||||||
+280
-11
@@ -146,6 +146,30 @@
|
|||||||
button.ghost { background: none; border-color: transparent; color: var(--muted); }
|
button.ghost { background: none; border-color: transparent; color: var(--muted); }
|
||||||
button.ghost:hover { color: var(--accent); }
|
button.ghost:hover { color: var(--accent); }
|
||||||
|
|
||||||
|
/* ---------- AI 프롬프트 ---------- */
|
||||||
|
.ai-bar { border-bottom: 1px solid var(--line); padding: 10px 20px 12px; background: #fbf8f2; }
|
||||||
|
.ai-row { display: flex; gap: 8px; align-items: flex-start; }
|
||||||
|
.ai-row select { width: auto; font-size: 12.5px; padding: 7px 8px; }
|
||||||
|
.ai-row textarea { flex: 1; min-height: 46px; font-family: inherit; font-size: 13.5px; line-height: 1.5; }
|
||||||
|
.ai-examples { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 7px; }
|
||||||
|
.ai-examples .chip { font-size: 11.5px; }
|
||||||
|
#aiStatus { margin-top: 6px; }
|
||||||
|
.ai-result { margin-top: 10px; border: 1px solid var(--accent); border-radius: 5px; background: #fff; padding: 12px 14px; }
|
||||||
|
.ai-note { font-size: 13px; margin: 0 0 9px; }
|
||||||
|
.ai-note strong { color: var(--accent); }
|
||||||
|
.ai-changes { width: 100%; border-collapse: collapse; font-size: 12.5px; margin-bottom: 10px; }
|
||||||
|
.ai-changes th, .ai-changes td { border-bottom: 1px solid var(--line); padding: 4px 6px; text-align: left; vertical-align: top; }
|
||||||
|
.ai-changes th { color: var(--muted); font-weight: 500; width: 92px; }
|
||||||
|
.ai-changes .old { color: var(--muted); text-decoration: line-through; }
|
||||||
|
.ai-changes .new { color: var(--ok); }
|
||||||
|
.ai-diff { font-family: ui-monospace, Menlo, monospace; font-size: 12px; line-height: 1.55; background: #fffdf9; border: 1px solid var(--line); border-radius: 4px; padding: 8px; max-height: 220px; overflow: auto; white-space: pre-wrap; }
|
||||||
|
.ai-diff .add { color: var(--ok); background: #edf6f0; }
|
||||||
|
.ai-diff .del { color: var(--warn); background: #fbefe9; text-decoration: line-through; }
|
||||||
|
.ai-actions { display: flex; gap: 8px; margin-top: 10px; align-items: center; }
|
||||||
|
.ai-actions .spacer { flex: 1; }
|
||||||
|
.ai-spin { display: inline-block; width: 10px; height: 10px; border: 2px solid var(--line); border-top-color: var(--accent); border-radius: 50%; animation: spin .8s linear infinite; vertical-align: -1px; margin-right: 5px; }
|
||||||
|
@keyframes spin { to { transform: rotate(360deg); } }
|
||||||
|
|
||||||
/* ---------- 이력 서랍 ---------- */
|
/* ---------- 이력 서랍 ---------- */
|
||||||
#drawer {
|
#drawer {
|
||||||
position: fixed; inset: 0; background: rgba(31, 28, 24, .28);
|
position: fixed; inset: 0; background: rgba(31, 28, 24, .28);
|
||||||
@@ -217,6 +241,7 @@
|
|||||||
<option value="title">이름</option>
|
<option value="title">이름</option>
|
||||||
<option value="price">가격</option>
|
<option value="price">가격</option>
|
||||||
</select>
|
</select>
|
||||||
|
<button id="btnNew" class="ghost" style="font-size:12px;padding:4px 8px;">+ 새 작품</button>
|
||||||
<span class="count" id="rowcount"></span>
|
<span class="count" id="rowcount"></span>
|
||||||
</div>
|
</div>
|
||||||
<ul class="rows" id="rows"></ul>
|
<ul class="rows" id="rows"></ul>
|
||||||
@@ -229,6 +254,25 @@
|
|||||||
<span class="spacer"></span>
|
<span class="spacer"></span>
|
||||||
<span class="hint" id="edModified"></span>
|
<span class="hint" id="edModified"></span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="ai-bar" id="aiBar">
|
||||||
|
<div class="ai-row">
|
||||||
|
<select id="aiMode">
|
||||||
|
<option value="edit">이 작품 고치기</option>
|
||||||
|
<option value="draft">새 작품 초안</option>
|
||||||
|
</select>
|
||||||
|
<textarea id="aiPrompt" rows="2" placeholder="예) 부제를 더 담백하게. 본문은 3문단으로, 린넨 결을 첫 문장에."></textarea>
|
||||||
|
<button id="aiRun" class="primary">AI 실행</button>
|
||||||
|
</div>
|
||||||
|
<div class="ai-examples" id="aiExamples">
|
||||||
|
<button class="chip" data-p="부제를 더 담백하게, 20자 이내로">부제 간결하게</button>
|
||||||
|
<button class="chip" data-p="본문을 3문단으로 다시 써. 만드는 시간과 재료를 숫자로 넣어">본문 3문단</button>
|
||||||
|
<button class="chip" data-p="40~50대 여성이 읽기 편하게 문장을 짧게 끊어">문장 짧게</button>
|
||||||
|
<button class="chip" data-p="규격과 소재를 첫 문단에 자연스럽게 넣어">재료 강조</button>
|
||||||
|
</div>
|
||||||
|
<div class="hint" id="aiStatus"></div>
|
||||||
|
<div id="aiResult"></div>
|
||||||
|
</div>
|
||||||
<div class="editor-body" id="edBody">
|
<div class="editor-body" id="edBody">
|
||||||
<p class="empty">왼쪽 목록에서 작품을 고르면 여기서 바로 고칠 수 있습니다.</p>
|
<p class="empty">왼쪽 목록에서 작품을 고르면 여기서 바로 고칠 수 있습니다.</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -282,7 +326,7 @@ async function api(path, opts) {
|
|||||||
function markDirty(dirty) {
|
function markDirty(dirty) {
|
||||||
state.dirty = dirty;
|
state.dirty = dirty;
|
||||||
$('state').textContent = dirty ? '저장하지 않은 변경' : '변경 없음';
|
$('state').textContent = dirty ? '저장하지 않은 변경' : '변경 없음';
|
||||||
$('btnSave').disabled = !state.current || !dirty;
|
$('btnSave').disabled = !($('f_slug') || state.current) || !dirty;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------------ 목록 */
|
/* ------------------------------------------------------------ 목록 */
|
||||||
@@ -355,10 +399,17 @@ function fieldHtml(f, value) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function renderEditor(p) {
|
function renderEditor(p) {
|
||||||
const known = new Set(state.fields.map((f) => f.key));
|
const values = p.fields || {};
|
||||||
const grid = state.fields.map((f) => fieldHtml(f, p.fields[f.key])).join('');
|
const isDraft = !!p.draft;
|
||||||
const extra = p.extra_keys.length
|
if (isDraft) state.current = null;
|
||||||
? '<p class="hint">이 파일에만 있는 키(보존됨): ' + p.extra_keys.map(esc).join(', ') + '</p>'
|
const slugField = isDraft
|
||||||
|
? '<label class="field wide"><span class="lbl">슬러그 (주소·파일명, 영문 소문자·하이픈)</span>' +
|
||||||
|
'<input type="text" id="f_slug" value="' + esc(p.slug || '') + '" placeholder="예: magnolia-tea-mat"></label>'
|
||||||
|
: '';
|
||||||
|
const grid = slugField + state.fields.map((f) => fieldHtml(f, values[f.key])).join('');
|
||||||
|
const extraKeys = p.extra_keys || [];
|
||||||
|
const extra = extraKeys.length
|
||||||
|
? '<p class="hint">이 파일에만 있는 키(보존됨): ' + extraKeys.map(esc).join(', ') + '</p>'
|
||||||
: '';
|
: '';
|
||||||
$('edBody').innerHTML =
|
$('edBody').innerHTML =
|
||||||
'<div class="grid">' + grid + '</div>' +
|
'<div class="grid">' + grid + '</div>' +
|
||||||
@@ -367,9 +418,9 @@ function renderEditor(p) {
|
|||||||
'<textarea id="body" rows="14" style="min-height:240px">' + esc(p.body) + '</textarea>' +
|
'<textarea id="body" rows="14" style="min-height:240px">' + esc(p.body) + '</textarea>' +
|
||||||
'<p class="hint" style="margin-top:8px">문단은 빈 줄로 나눕니다. <code>## 제목</code>, <code>- 목록</code>, <code></code> 지원.</p>' +
|
'<p class="hint" style="margin-top:8px">문단은 빈 줄로 나눕니다. <code>## 제목</code>, <code>- 목록</code>, <code></code> 지원.</p>' +
|
||||||
'<div style="margin-top:10px">' + extra + '</div>';
|
'<div style="margin-top:10px">' + extra + '</div>';
|
||||||
$('edTitle').textContent = p.fields.title || p.slug;
|
$('edTitle').textContent = isDraft ? '새 작품 (저장 전)' : (values.title || p.slug);
|
||||||
$('edSlug').textContent = p.slug;
|
$('edSlug').textContent = isDraft ? '' : p.slug;
|
||||||
$('edModified').textContent = '파일 수정 ' + p.modified;
|
$('edModified').textContent = isDraft ? 'AI 초안' : '파일 수정 ' + p.modified;
|
||||||
$('btnReload').disabled = false;
|
$('btnReload').disabled = false;
|
||||||
wireEditor();
|
wireEditor();
|
||||||
markDirty(false);
|
markDirty(false);
|
||||||
@@ -432,12 +483,18 @@ function collect() {
|
|||||||
document.querySelectorAll('[data-key]').forEach((el) => {
|
document.querySelectorAll('[data-key]').forEach((el) => {
|
||||||
fields[el.dataset.key] = el.type === 'checkbox' ? el.checked : el.value;
|
fields[el.dataset.key] = el.type === 'checkbox' ? el.checked : el.value;
|
||||||
});
|
});
|
||||||
return { slug: state.current, fields, body: $('body').value, deploy: $('deployToo').checked };
|
const slugEl = $('f_slug');
|
||||||
|
return {
|
||||||
|
slug: slugEl ? slugEl.value.trim() : state.current,
|
||||||
|
fields, body: $('body').value,
|
||||||
|
deploy: $('deployToo').checked,
|
||||||
|
create: !!slugEl,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function save() {
|
async function save() {
|
||||||
if (!state.current) return;
|
|
||||||
const payload = collect();
|
const payload = collect();
|
||||||
|
if (!payload.slug) { toast('슬러그를 입력해 주세요', 'err'); return; }
|
||||||
$('btnSave').disabled = true;
|
$('btnSave').disabled = true;
|
||||||
$('state').textContent = '저장 중… (빌드 → 커밋)';
|
$('state').textContent = '저장 중… (빌드 → 커밋)';
|
||||||
const data = await api('/api/product', {
|
const data = await api('/api/product', {
|
||||||
@@ -452,7 +509,13 @@ async function save() {
|
|||||||
markDirty(false);
|
markDirty(false);
|
||||||
const deployNote = data.deploy ? (data.deploy.ok ? ' / 배포 OK' : ' / 배포 실패') : '';
|
const deployNote = data.deploy ? (data.deploy.ok ? ' / 배포 OK' : ' / 배포 실패') : '';
|
||||||
toast(data.message + (data.commit ? ' · ' + data.commit : '') + deployNote + (data.log ? '\n' + data.log : ''), data.deploy && !data.deploy.ok ? 'err' : 'ok');
|
toast(data.message + (data.commit ? ' · ' + data.commit : '') + deployNote + (data.log ? '\n' + data.log : ''), data.deploy && !data.deploy.ok ? 'err' : 'ok');
|
||||||
|
if (payload.create) {
|
||||||
|
state.current = null;
|
||||||
await refresh({ keep: true });
|
await refresh({ keep: true });
|
||||||
|
await openProduct(payload.slug);
|
||||||
|
} else {
|
||||||
|
await refresh({ keep: true });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function refresh(opts = {}) {
|
async function refresh(opts = {}) {
|
||||||
@@ -468,6 +531,175 @@ async function refresh(opts = {}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------ AI */
|
||||||
|
let aiLast = null;
|
||||||
|
let aiModelLabel = '';
|
||||||
|
|
||||||
|
function labels() {
|
||||||
|
const map = {};
|
||||||
|
state.fields.forEach((f) => { map[f.key] = f.label; });
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
function diffLines(before, after) {
|
||||||
|
const a = String(before || '').split('\n');
|
||||||
|
const b = String(after || '').split('\n');
|
||||||
|
const m = a.length, n = b.length;
|
||||||
|
const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
|
||||||
|
for (let i = m - 1; i >= 0; i--) {
|
||||||
|
for (let j = n - 1; j >= 0; j--) {
|
||||||
|
dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const out = [];
|
||||||
|
let i = 0, j = 0;
|
||||||
|
while (i < m && j < n) {
|
||||||
|
if (a[i] === b[j]) { out.push({ t: 'same', s: a[i] }); i++; j++; }
|
||||||
|
else if (dp[i + 1][j] >= dp[i][j + 1]) { out.push({ t: 'del', s: a[i] }); i++; }
|
||||||
|
else { out.push({ t: 'add', s: b[j] }); j++; }
|
||||||
|
}
|
||||||
|
while (i < m) out.push({ t: 'del', s: a[i++] });
|
||||||
|
while (j < n) out.push({ t: 'add', s: b[j++] });
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function diffHtml(before, after) {
|
||||||
|
const rows = diffLines(before, after);
|
||||||
|
const shown = rows.slice(0, 160).map((r) => {
|
||||||
|
if (r.t === 'same') return esc(r.s);
|
||||||
|
return '<span class="' + (r.t === 'add' ? 'add' : 'del') + '">' + (r.t === 'add' ? '+ ' : '- ') + esc(r.s) + '</span>';
|
||||||
|
});
|
||||||
|
if (rows.length > 160) shown.push('…');
|
||||||
|
return shown.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadAiStatus() {
|
||||||
|
const data = await api('/api/ai-status');
|
||||||
|
const el = $('aiStatus');
|
||||||
|
if (!data.ok || !data.configured) {
|
||||||
|
aiModelLabel = '';
|
||||||
|
el.innerHTML = 'AI 연결 안 됨: ' + esc(data.error || '키를 확인하세요');
|
||||||
|
el.style.color = 'var(--warn)';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
aiModelLabel = data.model || '';
|
||||||
|
el.textContent = 'AI: ' + data.model + ' · 키 출처 ' + data.source;
|
||||||
|
el.style.color = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runAi() {
|
||||||
|
const mode = $('aiMode').value;
|
||||||
|
const prompt = $('aiPrompt').value.trim();
|
||||||
|
if (prompt.length < 2) { toast('요청 내용을 입력해 주세요', 'err'); $('aiPrompt').focus(); return; }
|
||||||
|
if (mode === 'edit' && !state.current) { toast('먼저 왼쪽에서 작품을 고르세요', 'err'); return; }
|
||||||
|
|
||||||
|
$('aiRun').disabled = true;
|
||||||
|
$('aiResult').innerHTML = '';
|
||||||
|
$('aiStatus').innerHTML = '<span class="ai-spin"></span>' + (mode === 'draft' ? 'AI가 초안을 쓰는 중…' : 'AI가 고치는 중…');
|
||||||
|
const data = await api('/api/ai', {
|
||||||
|
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ mode, slug: state.current, prompt }),
|
||||||
|
});
|
||||||
|
$('aiRun').disabled = false;
|
||||||
|
loadAiStatus();
|
||||||
|
if (!data.ok) { toast(data.error || 'AI 호출 실패', 'err'); return; }
|
||||||
|
if (mode === 'draft') { renderDraftResult(data); return; }
|
||||||
|
if (data.empty) {
|
||||||
|
aiLast = null;
|
||||||
|
$('aiResult').innerHTML = '<div class="ai-result"><p class="ai-note">' + esc(data.note || '바꿀 내용이 없습니다') + '</p><div class="ai-actions"><span class="spacer"></span><button class="ghost" onclick="document.getElementById(\'aiResult\').innerHTML=\'\'">닫기</button></div></div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
aiLast = data;
|
||||||
|
renderAiResult(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderAiResult(data) {
|
||||||
|
const map = labels();
|
||||||
|
const keys = Object.keys(data.changes).filter((k) => k !== 'body');
|
||||||
|
const rows = keys.map((key) => {
|
||||||
|
const before = data.current.fields[key] ?? '';
|
||||||
|
const after = data.changes[key] ?? '';
|
||||||
|
return '<tr><th>' + esc(map[key] || key) + '</th><td><span class="old">' + esc(String(before) || '(빈 값)') +
|
||||||
|
'</span><br><span class="new">' + esc(String(after) || '(비움)') + '</span></td></tr>';
|
||||||
|
}).join('');
|
||||||
|
const bodyChanged = Object.prototype.hasOwnProperty.call(data.changes, 'body');
|
||||||
|
const bodyBlock = bodyChanged
|
||||||
|
? '<div class="section-label">본문 변경</div><div class="ai-diff">' + diffHtml(data.current.body, data.changes.body) + '</div>'
|
||||||
|
: '';
|
||||||
|
const meta = [data.model || aiModelLabel, data.tokens ? data.tokens + ' 토큰' : ''].filter(Boolean).join(' · ');
|
||||||
|
$('aiResult').innerHTML =
|
||||||
|
'<div class="ai-result">' +
|
||||||
|
'<p class="ai-note"><strong>' + esc(data.note || 'AI 제안') + '</strong> <span class="hint">' + esc(meta) + '</span></p>' +
|
||||||
|
(rows ? '<table class="ai-changes"><tbody>' + rows + '</tbody></table>' : '') +
|
||||||
|
bodyBlock +
|
||||||
|
'<div class="ai-actions">' +
|
||||||
|
'<button class="primary" id="aiApply">폼에 적용</button>' +
|
||||||
|
'<button id="aiApplySave">적용하고 저장</button>' +
|
||||||
|
'<span class="spacer"></span>' +
|
||||||
|
'<button class="ghost" id="aiDiscard">버리기</button>' +
|
||||||
|
'</div>' +
|
||||||
|
'</div>';
|
||||||
|
$('aiApply').addEventListener('click', () => applyAi(false));
|
||||||
|
$('aiApplySave').addEventListener('click', () => applyAi(true));
|
||||||
|
$('aiDiscard').addEventListener('click', discardAi);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderDraftResult(data) {
|
||||||
|
const f = data.fields || {};
|
||||||
|
$('aiResult').innerHTML =
|
||||||
|
'<div class="ai-result">' +
|
||||||
|
'<p class="ai-note"><strong>' + esc(f.title || '제목 없음') + '</strong> ' +
|
||||||
|
'<span class="hint">slug ' + esc(f.slug || '') + (f.price ? ' · ' + Number(f.price).toLocaleString('ko-KR') + '원' : '') + '</span></p>' +
|
||||||
|
(f.subtitle ? '<p class="hint" style="margin:0 0 8px">' + esc(f.subtitle) + '</p>' : '') +
|
||||||
|
'<div class="ai-diff">' + esc(data.body || '') + '</div>' +
|
||||||
|
'<div class="ai-actions">' +
|
||||||
|
'<button class="primary" id="aiDraftOpen">초안 열기 (편집)</button>' +
|
||||||
|
'<span class="spacer"></span>' +
|
||||||
|
'<button class="ghost" id="aiDiscardDraft">버리기</button>' +
|
||||||
|
'</div>' +
|
||||||
|
'</div>';
|
||||||
|
$('aiDraftOpen').addEventListener('click', () => applyDraft(data));
|
||||||
|
$('aiDiscardDraft').addEventListener('click', discardAi);
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyAi(saveNow) {
|
||||||
|
if (!aiLast) return;
|
||||||
|
let touched = false;
|
||||||
|
Object.keys(aiLast.changes).forEach((key) => {
|
||||||
|
if (key === 'body') {
|
||||||
|
$('body').value = aiLast.changes.body;
|
||||||
|
touched = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const el = document.querySelector('[data-key="' + key + '"]');
|
||||||
|
if (!el) return;
|
||||||
|
if (el.type === 'checkbox') el.checked = !!aiLast.changes[key];
|
||||||
|
else el.value = aiLast.changes[key];
|
||||||
|
el.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
touched = true;
|
||||||
|
});
|
||||||
|
if (!touched) return;
|
||||||
|
markDirty(true);
|
||||||
|
if (saveNow) save();
|
||||||
|
else toast('폼에 적용했습니다. 확인 후 저장하세요.', 'ok');
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyDraft(data) {
|
||||||
|
const fields = {};
|
||||||
|
state.fields.forEach((f) => { fields[f.key] = ''; });
|
||||||
|
Object.keys(data.fields || {}).forEach((key) => { fields[key] = data.fields[key] == null ? '' : String(data.fields[key]); });
|
||||||
|
state.current = null;
|
||||||
|
renderList();
|
||||||
|
renderEditor({ slug: data.fields.slug || '', fields, body: data.body || '', draft: true, extra_keys: [], modified: '' });
|
||||||
|
$('aiResult').innerHTML = '<p class="hint">초안을 폼에 열었습니다. 대표 이미지를 올리고 슬러그를 확인한 뒤 [저장(커밋)]을 누르세요.</p>';
|
||||||
|
if (!fields.image) { const pick = $('f_image'); if (pick) pick.focus(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
function discardAi() {
|
||||||
|
aiLast = null;
|
||||||
|
$('aiResult').innerHTML = '';
|
||||||
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------------ 이력 */
|
/* ------------------------------------------------------------ 이력 */
|
||||||
async function openHistory() {
|
async function openHistory() {
|
||||||
const data = await api('/api/history');
|
const data = await api('/api/history');
|
||||||
@@ -511,6 +743,31 @@ $('rows').addEventListener('click', (e) => {
|
|||||||
if (btn) openProduct(btn.dataset.slug);
|
if (btn) openProduct(btn.dataset.slug);
|
||||||
});
|
});
|
||||||
$('btnSave').addEventListener('click', save);
|
$('btnSave').addEventListener('click', save);
|
||||||
|
$('aiRun').addEventListener('click', runAi);
|
||||||
|
$('aiPrompt').addEventListener('keydown', (e) => {
|
||||||
|
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') { e.preventDefault(); runAi(); }
|
||||||
|
});
|
||||||
|
$('aiExamples').addEventListener('click', (e) => {
|
||||||
|
const chip = e.target.closest('.chip');
|
||||||
|
if (!chip) return;
|
||||||
|
$('aiPrompt').value = chip.dataset.p;
|
||||||
|
$('aiPrompt').focus();
|
||||||
|
});
|
||||||
|
$('aiMode').addEventListener('change', (e) => {
|
||||||
|
discardAi();
|
||||||
|
$('aiPrompt').placeholder = e.target.value === 'draft'
|
||||||
|
? '예) 겨울 매화 티매트, 32×48cm, 6만원. 매화를 놓은 과정을 담백하게.'
|
||||||
|
: '예) 부제를 더 담백하게. 본문은 3문단으로, 린넨 결을 첫 문장에.';
|
||||||
|
});
|
||||||
|
$('btnNew').addEventListener('click', () => {
|
||||||
|
if (state.dirty && !confirm('저장하지 않은 변경이 있습니다. 버리고 새 작품을 쓸까요?')) return;
|
||||||
|
$('aiMode').value = 'draft';
|
||||||
|
state.q = ''; $('q').value = '';
|
||||||
|
discardAi();
|
||||||
|
$('aiPrompt').placeholder = '예) 겨울 매화 티매트, 32×48cm, 6만원. 매화를 놓은 과정을 담백하게.';
|
||||||
|
$('aiPrompt').focus();
|
||||||
|
toast('새 작품: 만들 내용을 적고 AI 실행을 누르세요');
|
||||||
|
});
|
||||||
$('btnReload').addEventListener('click', () => { if (state.current) openProduct(state.current); });
|
$('btnReload').addEventListener('click', () => { if (state.current) openProduct(state.current); });
|
||||||
$('btnHistory').addEventListener('click', openHistory);
|
$('btnHistory').addEventListener('click', openHistory);
|
||||||
$('btnCloseDrawer').addEventListener('click', () => $('drawer').classList.remove('open'));
|
$('btnCloseDrawer').addEventListener('click', () => $('drawer').classList.remove('open'));
|
||||||
@@ -539,7 +796,19 @@ document.addEventListener('keydown', (e) => {
|
|||||||
|
|
||||||
window.addEventListener('beforeunload', (e) => { if (state.dirty) { e.preventDefault(); e.returnValue = ''; } });
|
window.addEventListener('beforeunload', (e) => { if (state.dirty) { e.preventDefault(); e.returnValue = ''; } });
|
||||||
|
|
||||||
refresh();
|
async function boot() {
|
||||||
|
await refresh();
|
||||||
|
const params = new URLSearchParams(location.search);
|
||||||
|
const preset = params.get('prompt');
|
||||||
|
if (preset) {
|
||||||
|
$('aiPrompt').value = preset;
|
||||||
|
if (params.get('run') === '1') setTimeout(runAi, 600);
|
||||||
|
}
|
||||||
|
if (params.get('mode') === 'draft') $('aiMode').value = 'draft';
|
||||||
|
loadAiStatus();
|
||||||
|
}
|
||||||
|
|
||||||
|
boot();
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
+210
-4
@@ -13,10 +13,13 @@ from __future__ import annotations
|
|||||||
import argparse
|
import argparse
|
||||||
import json
|
import json
|
||||||
import mimetypes
|
import mimetypes
|
||||||
|
import os
|
||||||
import re
|
import re
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
|
import urllib.error
|
||||||
import urllib.parse
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -29,6 +32,14 @@ ASSETS = ROOT / "assets"
|
|||||||
APP = BASE / "app.html"
|
APP = BASE / "app.html"
|
||||||
LIST_KEYS = {"gallery"}
|
LIST_KEYS = {"gallery"}
|
||||||
|
|
||||||
|
# ---- AI(DeepSeek) 설정 ------------------------------------------------------
|
||||||
|
AI_BASE_URL = "https://api.deepseek.com/v1"
|
||||||
|
AI_MODEL = "deepseek-flash"
|
||||||
|
AI_CONFIG = Path.home() / ".config" / "teamat-studio" / "ai.json"
|
||||||
|
CLAUDE_SETTINGS = Path.home() / ".claude" / "settings.json"
|
||||||
|
# AI 가 손댈 수 있는 필드 (slug·date·image·gallery·sold_out·featured·naver_url 은 제외)
|
||||||
|
AI_FIELDS = ["title", "subtitle", "price", "material", "size", "care", "image_alt"]
|
||||||
|
|
||||||
# 폼에 노출할 필드와 순서. 여기 없는 키도 파일에 있으면 보존한다.
|
# 폼에 노출할 필드와 순서. 여기 없는 키도 파일에 있으면 보존한다.
|
||||||
FIELDS: List[Dict[str, str]] = [
|
FIELDS: List[Dict[str, str]] = [
|
||||||
{"key": "title", "label": "제목", "type": "text"},
|
{"key": "title", "label": "제목", "type": "text"},
|
||||||
@@ -278,8 +289,21 @@ def coerce(field: Dict[str, str], value: Any) -> Any:
|
|||||||
|
|
||||||
|
|
||||||
def save_product(payload: Dict[str, Any]) -> Dict[str, Any]:
|
def save_product(payload: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
slug = str(payload.get("slug", ""))
|
slug = str(payload.get("slug", "")).strip()
|
||||||
path = product_path(slug)
|
if not re.fullmatch(r"[a-z0-9][a-z0-9-]*", slug or ""):
|
||||||
|
raise ValueError("슬러그는 영문 소문자·숫자·하이픈만 쓸 수 있습니다")
|
||||||
|
|
||||||
|
path = PRODUCTS / f"{slug}.md"
|
||||||
|
creating = not path.exists()
|
||||||
|
if creating and not payload.get("create"):
|
||||||
|
raise FileNotFoundError(f"작품 파일이 없습니다: {slug}.md")
|
||||||
|
|
||||||
|
if creating:
|
||||||
|
original = None
|
||||||
|
old_body = ""
|
||||||
|
order: List[str] = list(DEFAULT_ORDER)
|
||||||
|
data: Dict[str, Any] = {"slug": slug, "date": datetime.now().strftime("%Y-%m-%d")}
|
||||||
|
else:
|
||||||
original = path.read_text(encoding="utf-8")
|
original = path.read_text(encoding="utf-8")
|
||||||
lines, old_body = split_front(original)
|
lines, old_body = split_front(original)
|
||||||
order, data = parse_front(lines)
|
order, data = parse_front(lines)
|
||||||
@@ -293,6 +317,11 @@ def save_product(payload: Dict[str, Any]) -> Dict[str, Any]:
|
|||||||
order.append(key)
|
order.append(key)
|
||||||
data[key] = value
|
data[key] = value
|
||||||
|
|
||||||
|
if creating and not str(data.get("title") or "").strip():
|
||||||
|
raise ValueError("제목이 비어 있어 새 작품을 만들 수 없습니다")
|
||||||
|
if creating and not str(data.get("image") or "").strip():
|
||||||
|
raise ValueError("대표 이미지가 필요합니다 (assets/img/... 경로)")
|
||||||
|
|
||||||
body = str(payload.get("body", old_body))
|
body = str(payload.get("body", old_body))
|
||||||
updated = assemble(order, data, body)
|
updated = assemble(order, data, body)
|
||||||
if updated == original:
|
if updated == original:
|
||||||
@@ -301,10 +330,16 @@ def save_product(payload: Dict[str, Any]) -> Dict[str, Any]:
|
|||||||
path.write_text(updated, encoding="utf-8")
|
path.write_text(updated, encoding="utf-8")
|
||||||
built, build_log = build()
|
built, build_log = build()
|
||||||
if not built:
|
if not built:
|
||||||
|
if creating:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
error = "빌드 실패 — 새 작품 파일을 만들지 않았습니다"
|
||||||
|
else:
|
||||||
path.write_text(original, encoding="utf-8")
|
path.write_text(original, encoding="utf-8")
|
||||||
return {"ok": False, "stage": "build", "error": "빌드 실패 — 저장을 취소하고 원본을 되돌렸습니다", "log": build_log}
|
error = "빌드 실패 — 저장을 취소하고 원본을 되돌렸습니다"
|
||||||
|
return {"ok": False, "stage": "build", "error": error, "log": build_log}
|
||||||
|
|
||||||
committed, commit_log = git_commit(f"작품 수정: {data.get('title') or slug}", [str(path.relative_to(ROOT))])
|
label = "작품 추가" if creating else "작품 수정"
|
||||||
|
committed, commit_log = git_commit(f"{label}: {data.get('title') or slug}", [str(path.relative_to(ROOT))])
|
||||||
if not committed:
|
if not committed:
|
||||||
return {"ok": False, "stage": "git", "error": "git 커밋 실패 (파일은 저장됨)", "log": commit_log}
|
return {"ok": False, "stage": "git", "error": "git 커밋 실패 (파일은 저장됨)", "log": commit_log}
|
||||||
|
|
||||||
@@ -359,6 +394,156 @@ def upload_image(name: str, data: bytes) -> Dict[str, Any]:
|
|||||||
return {"ok": True, "path": f"assets/img/{target.name}", "bytes": len(data)}
|
return {"ok": True, "path": f"assets/img/{target.name}", "bytes": len(data)}
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- AI
|
||||||
|
|
||||||
|
SYSTEM_PROMPT = """너는 한국의 핸드메이드 자수 브랜드 "한땀"의 카피라이터다.
|
||||||
|
|
||||||
|
브랜드: 아이보리 린넨·무명 위에 면사로 그림을 놓는 작은 작업실. 타깃은 40~50대 여성, 일부 20대.
|
||||||
|
톤: 담백하고 구체적. 재료와 시간을 숫자로 말한다("린넨 100%", "30 × 45 cm", "열흘 남짓").
|
||||||
|
|
||||||
|
반드시 지킬 규칙:
|
||||||
|
1. 없는 사실을 만들지 않는다. 후기·별점·판매량·수상·재고·할인·배송일 약속 금지.
|
||||||
|
2. 이모지 금지. 느낌표 남용 금지. "최고급/완벽한/특별한/럭셔리" 같은 형용사 금지.
|
||||||
|
3. 본문은 2~4문단, 문단당 2~3문장. 마크다운은 문단, "## 소제목", "- 목록", "" 만 쓴다.
|
||||||
|
4. 요청받지 않은 필드는 건드리지 않는다. 특히 price·material·size·care 는 근거 없이 바꾸지 않는다.
|
||||||
|
5. 한국어로만 쓴다.
|
||||||
|
|
||||||
|
응답은 설명 없이 JSON 객체 하나만 출력한다. 스키마:
|
||||||
|
{"note": "무엇을 어떻게 바꿨는지 한 줄(한국어)",
|
||||||
|
"fields": {"바꾼필드": "새 값"}, // 바꾼 필드만 넣는다. 없으면 {}
|
||||||
|
"body": "새 본문 전문"} // 본문을 바꿀 때만 넣는다. 안 바꾸면 생략
|
||||||
|
"""
|
||||||
|
|
||||||
|
DRAFT_SCHEMA = """너는 위 규칙에 따라 새 작품 1점의 원고를 쓴다.
|
||||||
|
응답은 설명 없이 JSON 객체 하나만 출력한다. 스키마:
|
||||||
|
{"note": "한 줄 요약",
|
||||||
|
"fields": {"slug": "영문-소문자-하이픈", "title": "", "subtitle": "", "price": 0,
|
||||||
|
"material": "", "size": "", "care": "", "image_alt": ""},
|
||||||
|
"body": "본문 전문(2~4문단)"}
|
||||||
|
price 는 원 단위 정수. 모르면 0 이 아니라 null 이 아니라 빈 문자열 "" 로 둔다.
|
||||||
|
slug 는 제목을 영문 소문자·하이픈으로 옮긴 것(예: magnolia-tea-mat).
|
||||||
|
"""
|
||||||
|
|
||||||
|
DEFAULT_ORDER = ["slug", "title", "subtitle", "date", "price", "sold_out", "featured",
|
||||||
|
"image", "image_alt", "gallery", "material", "size", "care", "naver_url"]
|
||||||
|
|
||||||
|
|
||||||
|
def ai_config() -> Dict[str, str]:
|
||||||
|
"""키 우선순위: 환경변수 -> ~/.config/teamat-studio/ai.json -> Claude Code 의 DeepSeek 토큰."""
|
||||||
|
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), "source": "환경변수 DEEPSEEK_API_KEY"}
|
||||||
|
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), "source": str(AI_CONFIG)}
|
||||||
|
if CLAUDE_SETTINGS.is_file():
|
||||||
|
env = json.loads(CLAUDE_SETTINGS.read_text(encoding="utf-8")).get("env", {})
|
||||||
|
token = str(env.get("ANTHROPIC_AUTH_TOKEN") or "")
|
||||||
|
if token.startswith("sk-") and "api.deepseek.com" in str(env.get("ANTHROPIC_BASE_URL") or ""):
|
||||||
|
return {"api_key": token, "base_url": AI_BASE_URL, "model": AI_MODEL,
|
||||||
|
"source": "~/.claude/settings.json 의 DeepSeek 토큰"}
|
||||||
|
raise RuntimeError(
|
||||||
|
"DeepSeek API 키가 없습니다. ~/.config/teamat-studio/ai.json 에 "
|
||||||
|
'{"api_key": "sk-..."} 를 만들거나 DEEPSEEK_API_KEY 환경변수를 주세요.'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def ai_status() -> Dict[str, Any]:
|
||||||
|
try:
|
||||||
|
cfg = ai_config()
|
||||||
|
except RuntimeError as error:
|
||||||
|
return {"ok": True, "configured": False, "error": str(error)}
|
||||||
|
return {"ok": True, "configured": True, "model": cfg["model"], "source": cfg["source"]}
|
||||||
|
|
||||||
|
|
||||||
|
def ai_chat(system: str, user: str, max_tokens: int = 3000) -> Dict[str, Any]:
|
||||||
|
cfg = ai_config()
|
||||||
|
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",
|
||||||
|
)
|
||||||
|
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")[:400]
|
||||||
|
raise RuntimeError(f"DeepSeek 오류 {error.code}: {detail}") from error
|
||||||
|
except urllib.error.URLError as error:
|
||||||
|
raise RuntimeError(f"DeepSeek 연결 실패: {error.reason}") from error
|
||||||
|
|
||||||
|
text = (body.get("choices") or [{}])[0].get("message", {}).get("content", "")
|
||||||
|
usage = body.get("usage") or {}
|
||||||
|
try:
|
||||||
|
data = json.loads(text)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
match = re.search(r"\{.*\}", text, re.S)
|
||||||
|
if not match:
|
||||||
|
raise RuntimeError(f"AI 응답을 JSON 으로 읽지 못했습니다: {text[:300]}")
|
||||||
|
data = json.loads(match.group(0))
|
||||||
|
return {"data": data, "model": body.get("model") or cfg["model"],
|
||||||
|
"tokens": usage.get("total_tokens"), "prompt_tokens": usage.get("prompt_tokens")}
|
||||||
|
|
||||||
|
|
||||||
|
def ai_edit(slug: str, prompt: str) -> Dict[str, Any]:
|
||||||
|
product = load_product(slug)
|
||||||
|
current_fields = {key: product["fields"].get(key, "") for key in AI_FIELDS}
|
||||||
|
current_body = product["body"]
|
||||||
|
user = json.dumps(
|
||||||
|
{"요청": prompt, "현재_작품": {"fields": current_fields, "body": current_body}},
|
||||||
|
ensure_ascii=False,
|
||||||
|
indent=2,
|
||||||
|
)
|
||||||
|
result = ai_chat(SYSTEM_PROMPT, user)
|
||||||
|
data = result["data"]
|
||||||
|
|
||||||
|
changes: Dict[str, Any] = {}
|
||||||
|
proposed = data.get("fields") or {}
|
||||||
|
if isinstance(proposed, dict):
|
||||||
|
for key, value in proposed.items():
|
||||||
|
if key not in AI_FIELDS:
|
||||||
|
continue
|
||||||
|
if str(value).strip() == str(current_fields.get(key, "")).strip():
|
||||||
|
continue
|
||||||
|
changes[key] = value
|
||||||
|
new_body = str(data.get("body") or "").strip()
|
||||||
|
if new_body and new_body != current_body.strip():
|
||||||
|
changes["body"] = new_body
|
||||||
|
if not changes:
|
||||||
|
return {"ok": True, "note": str(data.get("note") or "바꿀 것이 없다고 판단했습니다"), "changes": {},
|
||||||
|
"current": {"fields": current_fields, "body": current_body},
|
||||||
|
"model": result["model"], "tokens": result["tokens"], "empty": True}
|
||||||
|
return {"ok": True, "note": str(data.get("note") or ""), "changes": changes,
|
||||||
|
"current": {"fields": current_fields, "body": current_body},
|
||||||
|
"model": result["model"], "tokens": result["tokens"]}
|
||||||
|
|
||||||
|
|
||||||
|
def ai_draft(prompt: str) -> Dict[str, Any]:
|
||||||
|
result = ai_chat(SYSTEM_PROMPT + "\n" + DRAFT_SCHEMA, prompt)
|
||||||
|
data = result["data"]
|
||||||
|
fields = data.get("fields") or {}
|
||||||
|
slug = re.sub(r"[^a-z0-9-]+", "-", str(fields.get("slug") or "").lower()).strip("-")
|
||||||
|
if not slug:
|
||||||
|
slug = "work-" + datetime.now().strftime("%m%d-%H%M")
|
||||||
|
candidate, index = slug, 2
|
||||||
|
while (PRODUCTS / f"{candidate}.md").exists():
|
||||||
|
candidate = f"{slug}-{index}"
|
||||||
|
index += 1
|
||||||
|
fields["slug"] = candidate
|
||||||
|
return {"ok": True, "note": str(data.get("note") or ""), "fields": fields,
|
||||||
|
"body": str(data.get("body") or ""), "model": result["model"], "tokens": result["tokens"]}
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------------ server
|
# ------------------------------------------------------------------------ server
|
||||||
|
|
||||||
|
|
||||||
@@ -422,6 +607,9 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
except ValueError as error:
|
except ValueError as error:
|
||||||
self.send_json({"ok": False, "error": str(error)}, 400)
|
self.send_json({"ok": False, "error": str(error)}, 400)
|
||||||
return
|
return
|
||||||
|
if path == "/api/ai-status":
|
||||||
|
self.send_json(ai_status())
|
||||||
|
return
|
||||||
if path == "/api/history":
|
if path == "/api/history":
|
||||||
self.send_json({"ok": True, "history": history(25), "head": head_sha()})
|
self.send_json({"ok": True, "history": history(25), "head": head_sha()})
|
||||||
return
|
return
|
||||||
@@ -455,6 +643,24 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
except ValueError as error:
|
except ValueError as error:
|
||||||
self.send_json({"ok": False, "error": str(error)}, 400)
|
self.send_json({"ok": False, "error": str(error)}, 400)
|
||||||
return
|
return
|
||||||
|
if path == "/api/ai":
|
||||||
|
payload = self.read_json()
|
||||||
|
prompt = str(payload.get("prompt") or "").strip()
|
||||||
|
if len(prompt) < 2:
|
||||||
|
self.send_json({"ok": False, "error": "요청 내용을 입력해 주세요"}, 400)
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
if str(payload.get("mode")) == "draft":
|
||||||
|
self.send_json(ai_draft(prompt))
|
||||||
|
else:
|
||||||
|
self.send_json(ai_edit(str(payload.get("slug") or ""), prompt))
|
||||||
|
except FileNotFoundError as error:
|
||||||
|
self.send_json({"ok": False, "error": str(error)}, 404)
|
||||||
|
except (RuntimeError, ValueError) as error:
|
||||||
|
self.send_json({"ok": False, "error": str(error)}, 502)
|
||||||
|
except json.JSONDecodeError as error:
|
||||||
|
self.send_json({"ok": False, "error": f"AI 응답 형식 오류: {error}"}, 502)
|
||||||
|
return
|
||||||
if path == "/api/revert":
|
if path == "/api/revert":
|
||||||
payload = self.read_json()
|
payload = self.read_json()
|
||||||
self.send_json(revert(str(payload.get("sha", "")), bool(payload.get("deploy"))))
|
self.send_json(revert(str(payload.get("sha", "")), bool(payload.get("deploy"))))
|
||||||
|
|||||||
Reference in new issue
Block a user