"""휴대폰에서 상품을 등록하는 흐름을 받쳐 주는 모듈. studio/server.py 가 import 해서 쓴다. 표준 라이브러리 + macOS 기본 도구(sips)만 쓴다. 흐름: 1) /api/photo 사진을 _inbox 에 임시 저장 -> uid 2) /api/caption 사진을 읽어(VLM) 사실을 뽑고 문장을 씀 -> draft 3) /api/publish 사진을 assets/img// 로 옮기고 md·빌드·커밋(+배포) """ from __future__ import annotations import base64 import io 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 try: # 리눅스(QNAP 컨테이너)에서는 Pillow, macOS 기본 파이썬에는 없음 from PIL import Image, ImageOps HAS_PIL = True except ImportError: # pragma: no cover - macOS 폴백 HAS_PIL = False BASE = Path(__file__).resolve().parent ROOT = BASE.parent PRODUCTS = ROOT / "content" / "products" ASSETS = ROOT / "assets" INBOX = BASE / "_inbox" ARCHIVE = Path(os.environ.get("TEAMAT_ARCHIVE") or (BASE / "_archive")) CONFIG_DIR = Path(os.environ.get("TEAMAT_CONFIG_DIR") or (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 에 보낼 용량 줄이기. Pillow(리눅스) 또는 sips(macOS).""" if HAS_PIL: with Image.open(path) as image: image = ImageOps.exif_transpose(image).convert("RGB") image.thumbnail((limit, limit), Image.LANCZOS) buffer = io.BytesIO() image.save(buffer, format="JPEG", quality=75, optimize=True) return buffer.getvalue() 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: if HAS_PIL: with Image.open(source) as image: image = ImageOps.exif_transpose(image).convert("RGB") image.thumbnail((limit, limit), Image.LANCZOS) image.save(target, format="JPEG", quality=82, optimize=True, progressive=True) return 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]: """커밋되지 않은 다른 작품 초안. 배포하면 함께 올라가므로 미리 알린다.""" return [name for name in pending_drafts() if not name.endswith(f"/{slug}")] def pending_drafts() -> List[str]: """커밋되지 않은 작품 초안 전체(경로 기준).""" proc = subprocess.run(["git", "status", "--porcelain", "--", "content/products"], cwd=str(ROOT), capture_output=True, text=True, timeout=30) return [Path(line[3:].strip()).stem for line in (proc.stdout or "").splitlines() if line[3:].strip().endswith(".md")] 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}") # 원본(찍은 그대로)은 저장소 밖 보관함에 남긴다 — 나중에 다시 자르거나 크게 볼 때 쓴다. if ARCHIVE: keep = ARCHIVE / slug keep.mkdir(parents=True, exist_ok=True) for index, source in enumerate(sources): shutil.copyfile(source, keep / ("cover.jpg" if index == 0 else f"photo-{index:02d}.jpg")) 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) push_ok, push_log = True, "" if os.environ.get("TEAMAT_PUSH", "").strip().lower() in ("1", "true", "yes") and helpers.get("push"): push_ok, push_log = helpers["push"]() 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, "pushed": push_ok, "push_log": push_log[-200:], "build_log": log, "deploy_log": deploy_log[-400:], "url": f"/p/{slug}.html"}