QNAP 이전: 등록 서버를 컨테이너로(8089, Caddy teamat-admin.lala.dedyn.io), 사진 원본 보관, 웹 루트 직접 배포, Gitea 자동 푸시

This commit is contained in:
한땀 작업실 committed 2026-11-01 03:52:58 +00:00
1 parent 5c5ecef578
commit 984fe68c12
7 files changed
+165 -19

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
# 한땀 작업실(QNAP) — 등록 서버 이미지
# 사진 축소·회전에 Pillow 를 쓰고, 커밋·푸시에 git 이 필요하다.
FROM python:3.12-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends git ca-certificates \
&& rm -rf /var/lib/apt/lists/* \
&& pip install --no-cache-dir pillow==11.3.0
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
TEAMAT_CONFIG_DIR=/config \
TEAMAT_DEFAULT_PAGE=m
WORKDIR /repo
EXPOSE 8089
CMD ["python3", "studio/server.py", "--port", "8089", "--host", "0.0.0.0"]
+36 -3
View File
@@ -11,6 +11,7 @@ studio/server.py 가 import 해서 쓴다. 표준 라이브러리 + macOS 기본
from __future__ import annotations
import base64
import io
import json
import os
import re
@@ -25,13 +26,21 @@ 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.home() / ".config" / "teamat-studio"
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"
@@ -122,7 +131,14 @@ def vision_status() -> Dict[str, Any]:
def _shrink(path: Path, limit: int = 900) -> bytes:
"""VLM 에 보낼 용량 줄이기. sips 는 macOS 기본 도구."""
"""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)],
@@ -314,6 +330,12 @@ def _orient(path: Path) -> None:
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
@@ -371,6 +393,13 @@ def publish(payload: Dict[str, Any], helpers: Dict[str, Any]) -> Dict[str, Any]:
_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,
@@ -421,6 +450,10 @@ def publish(payload: Dict[str, Any], helpers: Dict[str, Any]) -> Dict[str, Any]:
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"):
@@ -432,6 +465,6 @@ def publish(payload: Dict[str, Any], helpers: Dict[str, Any]) -> Dict[str, Any]:
return {"ok": True, "slug": slug, "title": title, "commit": commit_log,
"deployed": bool(payload.get("deploy")) and deploy_ok,
"other_drafts": drafts,
"other_drafts": drafts, "pushed": push_ok, "push_log": push_log[-200:],
"build_log": log, "deploy_log": deploy_log[-400:],
"url": f"/p/{slug}.html"}
+43 -3
View File
@@ -15,6 +15,7 @@ import json
import mimetypes
import os
import re
import shutil
import subprocess
import sys
import urllib.error
@@ -32,7 +33,10 @@ ASSETS = ROOT / "assets"
APP = BASE / "app.html"
MOBILE = BASE / "m.html"
MANIFEST = BASE / "manifest.json"
TOKEN_FILE = Path.home() / ".config" / "teamat-studio" / "token"
DIST = ROOT / "dist"
# 폰 우선 배포(QNAP)에서는 첫 화면이 등록 화면이다. 데스크톱 편집 화면은 /desk.
DEFAULT_MOBILE = os.environ.get("TEAMAT_DEFAULT_PAGE", "").strip().lower() in ("m", "mobile")
TOKEN_FILE = Path(os.environ.get("TEAMAT_CONFIG_DIR") or (Path.home() / ".config" / "teamat-studio")) / "token"
import register as reg # 휴대폰 등록 흐름(사진 인박스·판독·발행)
@@ -222,9 +226,42 @@ def build() -> Tuple[bool, str]:
def deploy() -> Tuple[bool, str]:
"""웹 루트가 지정돼 있으면(QNAP 컨테이너) dist 를 그 자리로 복사하고, 아니면 deploy.sh(rsync)."""
web_root = os.environ.get("TEAMAT_WEB_ROOT", "").strip()
if web_root:
target = Path(web_root)
try:
target.mkdir(parents=True, exist_ok=True)
wanted = set()
for path in DIST.rglob("*"):
rel = str(path.relative_to(DIST))
wanted.add(rel)
dest = target / rel
if path.is_dir():
dest.mkdir(parents=True, exist_ok=True)
else:
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(path, dest)
removed = 0
for path in sorted(target.rglob("*"), key=lambda p: len(p.parts), reverse=True):
rel = str(path.relative_to(target))
if rel in wanted:
continue
if path.is_file():
path.unlink()
removed += 1
elif path.is_dir() and not any(path.iterdir()):
path.rmdir()
return True, f"복사 완료: {target} (파일 {len(wanted)}개, 정리 {removed}개)"
except OSError as error:
return False, f"웹 루트 복사 실패: {error}"
return run(["bash", "scripts/deploy.sh"], timeout=300)
def push() -> Tuple[bool, str]:
return run(["git", "push", "origin", "HEAD:main"], timeout=180)
# -------------------------------------------------------------------- products io
@@ -651,11 +688,14 @@ class Handler(BaseHTTPRequestHandler):
return
if path in ("/", "/index.html"):
self.send_page(APP)
self.send_page(MOBILE if DEFAULT_MOBILE else APP)
return
if path in ("/m", "/m.html"):
self.send_page(MOBILE)
return
if path in ("/desk", "/app", "/app.html"):
self.send_page(APP)
return
if path == "/manifest.json":
self.send_page(MANIFEST, "application/manifest+json; charset=utf-8")
return
@@ -743,7 +783,7 @@ class Handler(BaseHTTPRequestHandler):
self.send_json({"ok": False, "error": str(error)}, 502)
return
if path == "/api/publish":
helpers = {"build": build, "git_commit": git_commit, "deploy": deploy}
helpers = {"build": build, "git_commit": git_commit, "deploy": deploy, "push": push}
try:
self.send_json(reg.publish(self.read_json(), helpers))
except ValueError as error: