Pick recording servers from the voice-changer app; fix per-server recording status
consent-recorder: operators (ADMIN_DISCORD_IDS) create an app key on the site; the app calls GET/POST /api/guilds with it to turn servers on/off. Turned-off servers are left immediately. recordingNow() now checks the user picked that server, so someone who only chose server A is not shown as recorded while sitting in a B channel the bot records for others. voice-changer: new "녹음 서버" dialog (record_servers.py), network in a worker thread, key saved in config/record-servers.json; upgrade cleanup list knows the new file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -54,6 +54,17 @@
|
||||
- 잡음 무시: 이 크기(dB)보다 작은 소리는 변환하지 않습니다. 키보드 소리가 들어가면 올리세요.
|
||||
- 설정은 `config\settings.json` 에 저장돼 다음에 그대로 열립니다.
|
||||
|
||||
## 녹음할 서버 정하기 — 녹음 서버
|
||||
|
||||
녹음 봇(동의 사이트 https://vc.tkrmagid.kr)이 어느 디스코드 서버에서 녹음할지 앱에서 켜고 끕니다.
|
||||
|
||||
1. 동의 사이트에 운영자 디스코드 계정으로 로그인해서 **앱 연결 키 만들기**를 누르고 키를 복사합니다 (한 번만 보입니다. 새로 만들면 예전 키는 못 씁니다).
|
||||
2. 앱의 **녹음 서버…** 버튼 → 사이트 주소(기본값 그대로)와 앱 연결 키를 넣고 **불러오기**.
|
||||
3. 녹음할 서버만 체크하고 **저장**. 끈 서버에서는 봇이 바로 나가고 더는 따라 들어가지 않습니다.
|
||||
|
||||
- 켠 서버에서도 녹음에 동의하고 그 서버를 녹음할 서버로 고른 사람의 목소리만 녹음합니다 (각자 사이트에서 고름).
|
||||
- 사이트 주소와 키는 `config\record-servers.json` 에 저장됩니다.
|
||||
|
||||
## 목소리 모델 학습 — `train.bat`
|
||||
|
||||
동의 사이트 서버에서 학습 데이터를 꺼냅니다 (동의 중인 사람만 꺼내짐):
|
||||
@@ -97,7 +108,7 @@ VoiceChanger.exe 실행기 (env\Scripts\pythonw.exe app\voice_changer.py 를
|
||||
install.bat 엔진 내려받기 · 이어 받기 (scripts\install.ps1, 설치 프로그램도 이것을 실행)
|
||||
train.bat 학습 (app\train.py)
|
||||
examples.bat 예시 모델 (app\examples.py)
|
||||
app\ 화면 · 학습 · 모델 목록 · 마이크 모듈 연결(mic_bridge.py) 코드
|
||||
app\ 화면 · 학습 · 모델 목록 · 마이크 모듈 연결(mic_bridge.py) · 녹음 서버(record_servers.py) 코드
|
||||
apo\ 마이크 모듈 VoiceChangerAPO.dll 과 소스 (vcapo.cpp, 주고받는 규약 vccore.h)
|
||||
scripts\mic-apo.ps1 마이크 모듈 붙이기 · 떼기 (관리자)
|
||||
models\<아이디>\ model.pth · model.index · info.json(이름 · 성별 · 출처 · 라이선스)
|
||||
|
||||
154
voice-changer/app/record_servers.py
Normal file
154
voice-changer/app/record_servers.py
Normal file
@@ -0,0 +1,154 @@
|
||||
"""녹음 서버: 녹음 봇(consent-recorder)이 어느 디스코드 서버에서 녹음할지 이 앱에서 켜고 끈다.
|
||||
|
||||
녹음 동의 사이트에 운영자 계정으로 로그인해 만든 "앱 연결 키"로 사이트 API(/api/guilds)를 부른다.
|
||||
서버를 켜 두어도 그 서버에서 녹음에 동의하고 그 서버를 고른 사람의 목소리만 녹음한다.
|
||||
"""
|
||||
import json
|
||||
import queue
|
||||
import threading
|
||||
import tkinter as tk
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from tkinter import ttk
|
||||
|
||||
from common import CONFIG, load_json, save_json
|
||||
|
||||
DEFAULT_SITE = "https://vc.tkrmagid.kr"
|
||||
STORE = CONFIG / "record-servers.json" # 사이트 주소 · 앱 연결 키
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def api_url(site: str) -> str:
|
||||
site = site.strip().rstrip("/")
|
||||
u = urllib.parse.urlparse(site)
|
||||
local = u.hostname in ("localhost", "127.0.0.1")
|
||||
if not u.hostname or (u.scheme != "https" and not (u.scheme == "http" and local)):
|
||||
raise ApiError("사이트 주소는 https:// 로 시작해야 합니다")
|
||||
return site + "/api/guilds"
|
||||
|
||||
|
||||
def call(site: str, key: str, enabled=None, timeout: float = 10) -> list:
|
||||
"""서버 목록 [{id, name, enabled}]. enabled(켤 서버 아이디 목록)를 주면 그대로 저장한 뒤 목록을 돌려준다."""
|
||||
key = key.strip()
|
||||
if not key:
|
||||
raise ApiError("앱 연결 키를 넣어 주세요")
|
||||
body = None if enabled is None else json.dumps({"enabled": list(enabled)}).encode()
|
||||
req = urllib.request.Request(api_url(site), data=body, method="GET" if body is None else "POST",
|
||||
headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
data = json.loads(r.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as e:
|
||||
try:
|
||||
msg = json.loads(e.read().decode("utf-8")).get("error")
|
||||
except (ValueError, AttributeError):
|
||||
msg = None
|
||||
if e.code == 401:
|
||||
raise ApiError("앱 연결 키가 맞지 않습니다. 사이트에서 새로 만든 키를 넣어 주세요") from None
|
||||
raise ApiError(msg or f"사이트 오류 ({e.code})") from None
|
||||
except (urllib.error.URLError, TimeoutError, OSError) as e:
|
||||
raise ApiError(f"사이트에 연결할 수 없습니다: {getattr(e, 'reason', e)}") from None
|
||||
except ValueError:
|
||||
raise ApiError("사이트 응답이 올바르지 않습니다") from None
|
||||
guilds = data.get("guilds") if isinstance(data, dict) else None
|
||||
if not isinstance(guilds, list):
|
||||
raise ApiError("사이트 응답이 올바르지 않습니다")
|
||||
return [{"id": str(g["id"]), "name": str(g["name"]), "enabled": bool(g["enabled"])} for g in guilds]
|
||||
|
||||
|
||||
class ServerDialog:
|
||||
"""메인 화면의 "녹음 서버" 버튼으로 여는 창."""
|
||||
|
||||
def __init__(self, root: tk.Tk):
|
||||
saved = load_json(STORE, {})
|
||||
self.win = w = tk.Toplevel(root)
|
||||
w.title("녹음 서버")
|
||||
w.transient(root)
|
||||
w.minsize(460, 320)
|
||||
self.results = queue.Queue()
|
||||
self.checks = {} # 서버 아이디 → BooleanVar
|
||||
|
||||
pad = dict(padx=10, pady=4)
|
||||
ttk.Label(w, text="녹음 봇이 녹음할 디스코드 서버를 켜고 끕니다. 켠 서버에서도 녹음에 동의하고 그 서버를 고른 사람의 목소리만 녹음합니다.",
|
||||
wraplength=440, foreground="#555").grid(row=0, column=0, columnspan=3, sticky="w", **pad)
|
||||
ttk.Label(w, text="사이트 주소").grid(row=1, column=0, sticky="w", **pad)
|
||||
self.site = tk.StringVar(value=saved.get("site", DEFAULT_SITE))
|
||||
ttk.Entry(w, textvariable=self.site).grid(row=1, column=1, columnspan=2, sticky="ew", padx=10)
|
||||
ttk.Label(w, text="앱 연결 키").grid(row=2, column=0, sticky="w", **pad)
|
||||
self.key = tk.StringVar(value=saved.get("key", ""))
|
||||
ttk.Entry(w, textvariable=self.key, show="•").grid(row=2, column=1, sticky="ew", padx=10)
|
||||
self.load_btn = ttk.Button(w, text="불러오기", command=self.load)
|
||||
self.load_btn.grid(row=2, column=2, sticky="e", padx=10)
|
||||
ttk.Label(w, text="키는 사이트에 운영자 디스코드 계정으로 로그인한 뒤 \"앱 연결 키 만들기\"로 만듭니다.",
|
||||
foreground="#555").grid(row=3, column=0, columnspan=3, sticky="w", padx=10)
|
||||
|
||||
self.list = ttk.Frame(w)
|
||||
self.list.grid(row=4, column=0, columnspan=3, sticky="nsew", **pad)
|
||||
self.save_btn = ttk.Button(w, text="저장", command=self.save, state="disabled")
|
||||
self.save_btn.grid(row=5, column=0, columnspan=3, pady=6)
|
||||
self.status = ttk.Label(w, text="")
|
||||
self.status.grid(row=6, column=0, columnspan=3, sticky="w", **pad)
|
||||
w.columnconfigure(1, weight=1)
|
||||
w.rowconfigure(4, weight=1)
|
||||
if self.key.get():
|
||||
self.load()
|
||||
|
||||
def _run(self, text, enabled=None):
|
||||
"""네트워크는 작업 스레드에서 (창이 멈추지 않게), 결과는 메인 스레드에서 그린다."""
|
||||
site, key = self.site.get(), self.key.get()
|
||||
self.load_btn.config(state="disabled")
|
||||
self.save_btn.config(state="disabled")
|
||||
self.status.config(text=text, foreground="")
|
||||
|
||||
def work():
|
||||
try:
|
||||
self.results.put((True, call(site, key, enabled)))
|
||||
except ApiError as e:
|
||||
self.results.put((False, str(e)))
|
||||
|
||||
threading.Thread(target=work, daemon=True).start()
|
||||
self.win.after(100, self._poll, site, key, enabled is not None)
|
||||
|
||||
def _poll(self, site, key, saved):
|
||||
try:
|
||||
ok, data = self.results.get_nowait()
|
||||
except queue.Empty:
|
||||
if self.win.winfo_exists():
|
||||
self.win.after(100, self._poll, site, key, saved)
|
||||
return
|
||||
if not self.win.winfo_exists():
|
||||
return
|
||||
self.load_btn.config(state="normal")
|
||||
if not ok:
|
||||
self.status.config(text=f"⚠ {data}", foreground="#b00020")
|
||||
if self.checks:
|
||||
self.save_btn.config(state="normal")
|
||||
return
|
||||
save_json(STORE, {"site": site.strip().rstrip("/"), "key": key.strip()}) # 맞는 키만 기억한다
|
||||
self.show(data)
|
||||
on = [g["name"] for g in data if g["enabled"]]
|
||||
done = "저장했습니다" if saved else "불러왔습니다"
|
||||
self.status.config(text=f"✓ {done}. 녹음하는 서버: {', '.join(on) if on else '없음'}", foreground="#188038")
|
||||
|
||||
def show(self, guilds):
|
||||
for c in self.list.winfo_children():
|
||||
c.destroy()
|
||||
self.checks = {}
|
||||
if not guilds:
|
||||
ttk.Label(self.list, text="봇이 들어가 있는 서버가 없습니다.").pack(anchor="w")
|
||||
return
|
||||
for g in guilds:
|
||||
v = tk.BooleanVar(value=g["enabled"])
|
||||
self.checks[g["id"]] = v
|
||||
ttk.Checkbutton(self.list, text=g["name"], variable=v).pack(anchor="w", pady=2)
|
||||
self.save_btn.config(state="normal")
|
||||
|
||||
def load(self):
|
||||
self._run("불러오는 중…")
|
||||
|
||||
def save(self):
|
||||
self._run("저장하는 중…", [gid for gid, v in self.checks.items() if v.get()])
|
||||
@@ -15,6 +15,7 @@ from tkinter import messagebox, ttk
|
||||
|
||||
from common import ROOT, SETTINGS, load_json, save_json, use_engine
|
||||
from models import GENDERS, auto_pitch, list_models
|
||||
from record_servers import ServerDialog
|
||||
|
||||
LATENCY = {"낮음 (약 0.15초, GPU 여유 필요)": 128, "보통 (약 0.25초)": 250, "안정 (약 0.4초)": 400}
|
||||
|
||||
@@ -331,6 +332,7 @@ class App:
|
||||
self.start_btn.pack(side="left", padx=6)
|
||||
self.stop_btn = ttk.Button(b, text="■ 정지", command=self.stop, state="disabled")
|
||||
self.stop_btn.pack(side="left", padx=6)
|
||||
ttk.Button(b, text="녹음 서버…", command=lambda: ServerDialog(self.root)).pack(side="left", padx=6)
|
||||
self.status = ttk.Label(f, text="꺼짐")
|
||||
self.status.grid(row=12, column=0, columnspan=3, sticky="w", **pad)
|
||||
|
||||
|
||||
@@ -73,7 +73,7 @@ if ($Mode -eq 'Prepare') {
|
||||
$known = [ordered]@{
|
||||
'.' = @('VoiceChanger.exe', 'install.bat', 'train.bat', 'examples.bat', 'README.md')
|
||||
'scripts' = @('install.ps1', 'mic-apo.ps1')
|
||||
'app' = @('common.py', 'examples.py', 'mic_bridge.py', 'models.py', 'setup_engine.py', 'train.py', 'voice_changer.py')
|
||||
'app' = @('common.py', 'examples.py', 'mic_bridge.py', 'models.py', 'record_servers.py', 'setup_engine.py', 'train.py', 'voice_changer.py')
|
||||
'launcher' = @('launcher.c')
|
||||
'apo' = @('VoiceChangerAPO.dll', 'vcapo.cpp', 'vccore.h', 'vcapo.def', 'mic-apo.json', 'mic-apo.log')
|
||||
'uninstall' = @('unins*.exe', 'unins*.dat', 'unins*.msg')
|
||||
|
||||
95
voice-changer/tests/test_record_servers.py
Normal file
95
voice-changer/tests/test_record_servers.py
Normal file
@@ -0,0 +1,95 @@
|
||||
"""앱의 "녹음 서버" 화면이 녹음 동의 사이트 API(/api/guilds)와 주고받는 부분 (가짜 사이트로)."""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "app"))
|
||||
os.environ.setdefault("VC_ROOT", tempfile.mkdtemp())
|
||||
|
||||
try:
|
||||
import tkinter # noqa: F401 (record_servers 가 불러옴)
|
||||
except ImportError:
|
||||
tkinter = None
|
||||
|
||||
KEY = "vc_good"
|
||||
STATE = {"g1": True, "g2": True}
|
||||
|
||||
|
||||
class FakeSite(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def reply(self, code, data):
|
||||
body = json.dumps(data, ensure_ascii=False).encode()
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def guilds(self):
|
||||
return {"guilds": [{"id": g, "name": {"g1": "첫째 서버", "g2": "둘째 서버"}[g], "enabled": on} for g, on in STATE.items()]}
|
||||
|
||||
def do_GET(self):
|
||||
if self.path != "/api/guilds" or self.headers.get("Authorization") != f"Bearer {KEY}":
|
||||
return self.reply(401, {"error": "앱 연결 키가 맞지 않습니다"})
|
||||
self.reply(200, self.guilds())
|
||||
|
||||
def do_POST(self):
|
||||
if self.headers.get("Authorization") != f"Bearer {KEY}":
|
||||
return self.reply(401, {"error": "앱 연결 키가 맞지 않습니다"})
|
||||
on = json.loads(self.rfile.read(int(self.headers["Content-Length"])))["enabled"]
|
||||
if any(g not in STATE for g in on):
|
||||
return self.reply(400, {"error": "봇이 들어가 있지 않은 서버입니다"})
|
||||
for g in STATE:
|
||||
STATE[g] = g in on
|
||||
self.reply(200, self.guilds())
|
||||
|
||||
|
||||
@unittest.skipIf(tkinter is None, "tkinter 없음")
|
||||
class RecordServersTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.httpd = HTTPServer(("127.0.0.1", 0), FakeSite)
|
||||
threading.Thread(target=cls.httpd.serve_forever, daemon=True).start()
|
||||
cls.site = f"http://127.0.0.1:{cls.httpd.server_port}/"
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.httpd.shutdown()
|
||||
|
||||
def test_load_and_save(self):
|
||||
from record_servers import call
|
||||
|
||||
self.assertEqual(call(self.site, KEY), [
|
||||
{"id": "g1", "name": "첫째 서버", "enabled": True},
|
||||
{"id": "g2", "name": "둘째 서버", "enabled": True},
|
||||
])
|
||||
after = call(self.site, f" {KEY} ", ["g2"])
|
||||
self.assertEqual([(g["id"], g["enabled"]) for g in after], [("g1", False), ("g2", True)])
|
||||
self.assertEqual(STATE, {"g1": False, "g2": True})
|
||||
call(self.site, KEY, ["g1", "g2"])
|
||||
|
||||
def test_errors_are_korean_messages(self):
|
||||
from record_servers import ApiError, call
|
||||
|
||||
with self.assertRaisesRegex(ApiError, "앱 연결 키가 맞지 않습니다"):
|
||||
call(self.site, "vc_wrong")
|
||||
with self.assertRaisesRegex(ApiError, "앱 연결 키를 넣어"):
|
||||
call(self.site, " ")
|
||||
with self.assertRaisesRegex(ApiError, "봇이 들어가 있지 않은 서버"):
|
||||
call(self.site, KEY, ["nope"])
|
||||
with self.assertRaisesRegex(ApiError, "https://"):
|
||||
call("http://example.com", KEY) # 키가 평문으로 나가지 않게 https 만 (localhost 예외)
|
||||
port = self.httpd.server_port + 1 if self.httpd.server_port < 65535 else 1
|
||||
with self.assertRaisesRegex(ApiError, "연결할 수 없습니다"):
|
||||
call(f"http://127.0.0.1:{port}", KEY, timeout=2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user