Add client/server split and TTS app

Set up FastAPI server, vanilla UI, and deployment scripts for the TTS app, including DB/ffmpeg wiring and Apache config.
This commit is contained in:
dsyoon
2026-01-30 13:17:24 +09:00
commit 3cc8fb2694
14 changed files with 737 additions and 0 deletions

1
server/__init__.py Normal file
View File

@@ -0,0 +1 @@

138
server/db.py Normal file
View File

@@ -0,0 +1,138 @@
import os
from typing import List, Optional, Dict, Any
import psycopg2
import psycopg2.extras
def get_conn():
user = os.getenv("DB_USER")
password = os.getenv("DB_PASSWORD")
if not user or not password:
raise RuntimeError("DB_USER 또는 DB_PASSWORD가 설정되지 않았습니다.")
return psycopg2.connect(
host="ncue.net",
port=5432,
dbname="tts",
user=user,
password=password,
)
def init_db():
with get_conn() as conn:
with conn.cursor() as cur:
cur.execute(
"""
CREATE TABLE IF NOT EXISTS tts_items (
id SERIAL PRIMARY KEY,
text TEXT NOT NULL,
filename TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
"""
)
cur.execute(
"""
CREATE INDEX IF NOT EXISTS tts_items_created_at_idx
ON tts_items (created_at DESC);
"""
)
conn.commit()
def create_item(text: str) -> Dict[str, Any]:
with get_conn() as conn:
with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:
cur.execute(
"""
INSERT INTO tts_items (text)
VALUES (%s)
RETURNING id, created_at;
""",
(text,),
)
row = cur.fetchone()
conn.commit()
return row
def update_filename(tts_id: int, filename: str) -> None:
with get_conn() as conn:
with conn.cursor() as cur:
cur.execute(
"""
UPDATE tts_items
SET filename = %s
WHERE id = %s;
""",
(filename, tts_id),
)
conn.commit()
def list_items() -> List[Dict[str, Any]]:
with get_conn() as conn:
with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:
cur.execute(
"""
SELECT id, created_at, filename
FROM tts_items
ORDER BY created_at DESC;
"""
)
rows = cur.fetchall()
return rows
def get_item(tts_id: int) -> Optional[Dict[str, Any]]:
with get_conn() as conn:
with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:
cur.execute(
"""
SELECT id, text, filename, created_at
FROM tts_items
WHERE id = %s;
""",
(tts_id,),
)
row = cur.fetchone()
return row
def delete_items(ids: List[int]) -> List[Dict[str, Any]]:
with get_conn() as conn:
with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:
cur.execute(
"""
SELECT id, filename
FROM tts_items
WHERE id = ANY(%s);
""",
(ids,),
)
rows = cur.fetchall()
cur.execute(
"""
DELETE FROM tts_items
WHERE id = ANY(%s);
""",
(ids,),
)
conn.commit()
return rows
def delete_item_by_id(tts_id: int) -> None:
with get_conn() as conn:
with conn.cursor() as cur:
cur.execute(
"""
DELETE FROM tts_items
WHERE id = %s;
""",
(tts_id,),
)
conn.commit()

170
server/main.py Normal file
View File

@@ -0,0 +1,170 @@
from pathlib import Path
from typing import List
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
from .db import (
init_db,
create_item,
update_filename,
list_items,
get_item,
delete_items,
delete_item_by_id,
)
from .tts_service import text_to_mp3
BASE_DIR = Path(__file__).resolve().parent
ROOT_DIR = BASE_DIR.parent
CLIENT_DIR = ROOT_DIR / "client"
RESOURCES_DIR = ROOT_DIR / "resources"
# 프로젝트 루트의 .env를 명시적으로 로드
load_dotenv(dotenv_path=ROOT_DIR / ".env")
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.mount("/static", StaticFiles(directory=str(CLIENT_DIR / "static")), name="static")
templates = Jinja2Templates(directory=str(CLIENT_DIR / "templates"))
class TtsCreateRequest(BaseModel):
text: str
class TtsDeleteRequest(BaseModel):
ids: List[int]
def format_display_time(dt):
# 한국 표기 형식으로 변환
local_dt = dt.astimezone()
return local_dt.strftime("%Y년 %m월 %d%H:%M:%S")
def ensure_resources_dir():
# mp3 저장 디렉토리 보장
RESOURCES_DIR.mkdir(parents=True, exist_ok=True)
@app.on_event("startup")
def on_startup():
ensure_resources_dir()
init_db()
@app.get("/")
def index(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.get("/api/tts")
def api_list_tts():
rows = list_items()
return [
{
"id": row["id"],
"created_at": row["created_at"].isoformat(),
"display_time": format_display_time(row["created_at"]),
"filename": row["filename"],
}
for row in rows
]
@app.post("/api/tts")
def api_create_tts(payload: TtsCreateRequest):
text = (payload.text or "").strip()
if len(text) < 11:
raise HTTPException(status_code=400, detail="텍스트는 11글자 이상이어야 합니다.")
created = create_item(text)
tts_id = created["id"]
created_at = created["created_at"]
timestamp = created_at.astimezone().strftime("%Y%m%d_%H%M%S")
filename = f"tts_{tts_id}_{timestamp}.mp3"
mp3_path = RESOURCES_DIR / filename
try:
text_to_mp3(text=text, mp3_path=str(mp3_path))
except Exception as exc:
delete_item_by_id(tts_id)
raise HTTPException(status_code=500, detail=str(exc)) from exc
update_filename(tts_id, filename)
return {
"id": tts_id,
"created_at": created_at.isoformat(),
"display_time": format_display_time(created_at),
"filename": filename,
}
@app.get("/api/tts/{tts_id}")
def api_get_tts(tts_id: int):
row = get_item(tts_id)
if not row:
raise HTTPException(status_code=404, detail="해당 항목이 없습니다.")
return {
"id": row["id"],
"text": row["text"],
"created_at": row["created_at"].isoformat(),
"display_time": format_display_time(row["created_at"]),
"filename": row["filename"],
"download_url": f"/api/tts/{row['id']}/download",
}
@app.get("/api/tts/{tts_id}/download")
def api_download_tts(tts_id: int):
row = get_item(tts_id)
if not row or not row["filename"]:
raise HTTPException(status_code=404, detail="파일이 없습니다.")
file_path = RESOURCES_DIR / row["filename"]
if not file_path.exists():
raise HTTPException(status_code=404, detail="파일이 없습니다.")
return FileResponse(
path=str(file_path),
media_type="audio/mpeg",
filename=row["filename"],
)
@app.delete("/api/tts")
def api_delete_tts(payload: TtsDeleteRequest):
ids = [int(i) for i in payload.ids if isinstance(i, int) or str(i).isdigit()]
if not ids:
raise HTTPException(status_code=400, detail="삭제할 항목이 없습니다.")
deleted_rows = delete_items(ids)
deleted_ids = []
for row in deleted_rows:
deleted_ids.append(row["id"])
if row.get("filename"):
file_path = RESOURCES_DIR / row["filename"]
if file_path.exists():
try:
file_path.unlink()
except OSError:
pass
return {"deleted": deleted_ids}

17
server/run.sh Normal file
View File

@@ -0,0 +1,17 @@
#!/usr/bin/env bash
set -euo pipefail
cd /home/dsyoon/workspace/tts
PORT="${PORT:-8018}"
if lsof -ti tcp:"${PORT}" >/dev/null 2>&1; then
echo "Stopping existing server on port ${PORT}..."
lsof -ti tcp:"${PORT}" | xargs -r kill -9
sleep 1
fi
python -m pip install -r requirements.txt
PORT="${PORT}" nohup uvicorn server.main:app --host 0.0.0.0 --port "${PORT}" > server.log 2>&1 &
echo "Server started (PID: $!). Logs: server.log"

42
server/tts_service.py Normal file
View File

@@ -0,0 +1,42 @@
import os
import subprocess
import tempfile
from pathlib import Path
import pyttsx3
def text_to_mp3(text: str, mp3_path: str) -> None:
if not text:
raise RuntimeError("텍스트가 비어 있습니다.")
mp3_target = Path(mp3_path)
mp3_target.parent.mkdir(parents=True, exist_ok=True)
engine = pyttsx3.init()
wav_fd, wav_path = tempfile.mkstemp(suffix=".wav")
os.close(wav_fd)
try:
# pyttsx3로 wav 생성 후 ffmpeg로 mp3 변환
engine.save_to_file(text, wav_path)
engine.runAndWait()
subprocess.run(
["ffmpeg", "-y", "-i", wav_path, str(mp3_target)],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
if not mp3_target.exists():
raise RuntimeError("mp3 파일 생성에 실패했습니다.")
except subprocess.CalledProcessError as exc:
raise RuntimeError("ffmpeg 변환에 실패했습니다.") from exc
except OSError as exc:
raise RuntimeError("파일 생성 권한 또는 경로 오류입니다.") from exc
finally:
try:
os.remove(wav_path)
except OSError:
pass