Initial commit: AI Station Portal v0.8.4
This commit is contained in:
+35
@@ -0,0 +1,35 @@
|
|||||||
|
# Python
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*.pyo
|
||||||
|
|
||||||
|
# Virtual environments
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
|
||||||
|
# Local configuration and secrets
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
*.key
|
||||||
|
*.pem
|
||||||
|
*.crt
|
||||||
|
|
||||||
|
# Runtime data
|
||||||
|
*.log
|
||||||
|
*.pid
|
||||||
|
*.sock
|
||||||
|
instance/
|
||||||
|
state/
|
||||||
|
data/
|
||||||
|
|
||||||
|
# Backups and temporary files
|
||||||
|
*.bak
|
||||||
|
*.bak.*
|
||||||
|
*.before-*
|
||||||
|
*~
|
||||||
|
.DS_Store
|
||||||
|
|
||||||
|
# Backup files
|
||||||
|
*.bak*
|
||||||
|
*.before-*
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
# AI Station Portal v0.8.0
|
||||||
|
|
||||||
|
Локальный портал AI Station: карточки сервисов, проверка доступности, расшифровка аудио через Speaches и базовые настройки станции.
|
||||||
|
|
||||||
|
## Установка / обновление
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /opt/ai-station-portal
|
||||||
|
python3 -m venv .venv # только при первой установке
|
||||||
|
source .venv/bin/activate
|
||||||
|
pip install -r requirements.txt
|
||||||
|
uvicorn app:app --host 0.0.0.0 --port 8090
|
||||||
|
```
|
||||||
|
|
||||||
|
Системные зависимости Ubuntu:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo apt update
|
||||||
|
sudo apt install -y libpam0g libpam0g-dev sudo
|
||||||
|
```
|
||||||
|
|
||||||
|
Открыть `http://192.168.1.26:8090`.
|
||||||
|
|
||||||
|
## Функции
|
||||||
|
|
||||||
|
- Главная страница с карточками сервисов и проверкой доступности.
|
||||||
|
- `/transcription` — загрузка аудио, распознавание через Speaches, редактирование и экспорт стенограммы.
|
||||||
|
- `/admin/login` — вход системным паролем пользователя `theroot` через PAM.
|
||||||
|
- `/admin` — просмотр и изменение hostname, часового пояса и состояния NTP.
|
||||||
|
- `/admin/terminal` — браузерный терминал, доступный только после административной авторизации; shell запускается от имени пользователя приложения.
|
||||||
|
- `/health` — проверка портала.
|
||||||
|
|
||||||
|
Модель распознавания: `Systran/faster-whisper-small`. Адрес Speaches задаётся константой `SPEACHES_URL` в `app.py`.
|
||||||
|
|
||||||
|
## Системные операции v0.6
|
||||||
|
|
||||||
|
Приложение не запускается от root. Для трёх ограниченных операций используется отдельный root-helper.
|
||||||
|
|
||||||
|
Установить helper:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo install -o root -g root -m 0755 ai-station-portal-admin /usr/local/sbin/ai-station-portal-admin
|
||||||
|
```
|
||||||
|
|
||||||
|
Создать sudoers-правило:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
printf '%s\n' 'theroot ALL=(root) NOPASSWD: /usr/local/sbin/ai-station-portal-admin' | sudo tee /etc/sudoers.d/ai-station-portal >/dev/null
|
||||||
|
sudo chmod 0440 /etc/sudoers.d/ai-station-portal
|
||||||
|
sudo visudo -cf /etc/sudoers.d/ai-station-portal
|
||||||
|
```
|
||||||
|
|
||||||
|
Если системный администратор называется не `theroot`, замените имя в sudoers-правиле на фактическое имя пользователя, от которого работает Uvicorn.
|
||||||
|
|
||||||
|
Helper принимает только три операции и проверяет аргументы самостоятельно:
|
||||||
|
|
||||||
|
- `hostname <hostname>`
|
||||||
|
- `timezone <IANA timezone>`
|
||||||
|
- `ntp yes|no`
|
||||||
|
|
||||||
|
Никакого произвольного выполнения shell-команд через веб-интерфейс нет. Не добавляйте в sudoers разрешение на `/bin/bash`, `sh` или произвольные команды.
|
||||||
|
|
||||||
|
После установки helper и sudoers перезапустите портал. Если helper не установлен, просмотр текущих параметров продолжит работать, а изменение настроек завершится сообщением об ошибке.
|
||||||
|
|
||||||
|
## Администрирование
|
||||||
|
|
||||||
|
- PAM проверяет системный пароль пользователя `theroot` (можно переопределить `AI_STATION_ADMIN_USER`).
|
||||||
|
- Сессия истекает через 10 минут бездействия.
|
||||||
|
- Для стабильной подписи cookie задайте постоянный секрет окружения `AI_STATION_SESSION_SECRET` (длинная случайная строка).
|
||||||
|
- После настройки HTTPS задайте `AI_STATION_COOKIE_SECURE=1`.
|
||||||
|
|
||||||
|
## Зависимости
|
||||||
|
|
||||||
|
Python-зависимости перечислены в `requirements.txt`, включая `python-docx`, `python-pam` и `itsdangerous`.
|
||||||
|
|
||||||
|
|
||||||
|
## Исправления v0.6.1
|
||||||
|
|
||||||
|
- Текущий часовой пояс читается через `timedatectl show -p Timezone`, а не из `/etc/timezone` (этот файл может не соответствовать активной настройке).
|
||||||
|
- Выбор часового пояса — выпадающий список полного набора IANA timezones, доступных в системе.
|
||||||
|
- После изменения часового пояса и NTP портал повторно читает значение из ОС и показывает успех только при совпадении.
|
||||||
|
|
||||||
|
|
||||||
|
## Терминал v0.8
|
||||||
|
|
||||||
|
- Кнопка «Открыть терминал» находится в административной панели.
|
||||||
|
- WebSocket endpoint `/admin/terminal/ws` проверяет административную сессию и Origin.
|
||||||
|
- Используется локальный PTY и `/bin/bash -l`; shell работает от имени пользователя, под которым запущен Uvicorn (ожидается `theroot`).
|
||||||
|
- Приложение не получает root-права. Для системных операций в терминале пользователь может использовать обычный `sudo` согласно системной политике.
|
||||||
|
- Закрытие вкладки завершает shell-сессию.
|
||||||
|
- Не публикуйте приложение без HTTPS в недоверенной сети. Терминал предоставляет полноценный доступ к учётной записи `theroot`.
|
||||||
|
|
||||||
|
Терминал использует xterm.js из CDN; для полностью изолированной установки следует локально разместить JS/CSS-файлы xterm.js и FitAddon.
|
||||||
|
|
||||||
|
|
||||||
|
## v0.8 — сетевое администрирование
|
||||||
|
|
||||||
|
Добавлены DHCP/статический IPv4, шлюз, DNS и search domain для интерфейса lan0. Изменения Netplan применяются с 120-секундным systemd-таймером автоматического отката. После проверки доступа администратор подтверждает новую конфигурацию в веб-интерфейсе. При отсутствии подтверждения helper восстанавливает резервные копии Netplan и cloud-init network config.
|
||||||
|
|
||||||
|
Helper должен быть установлен как `/usr/local/sbin/ai-station-portal-admin` с root-владельцем и правами 0755. Sudoers должен разрешать только этот helper без пароля для пользователя портала.
|
||||||
|
|
||||||
|
|
||||||
|
## Hotfix 5
|
||||||
|
|
||||||
|
- Network confirmation is refused unless the systemd rollback timer is active.
|
||||||
|
- The admin page shows pending rollback state based on the privileged helper, including after an error redirect.
|
||||||
|
- If the timer is missing or the rollback service failed, confirmation is disabled and the page reports an attention state.
|
||||||
|
- Network apply has a bounded 90-second Netplan apply window, shorter than the 120-second watchdog; the watchdog is the sole rollback owner after an apply error (no concurrent inline rollback).
|
||||||
|
- Rollback Netplan apply is allowed up to 180 seconds.
|
||||||
|
- Portal service links use the current request hostname via `{station_host}` instead of a fixed station IP. The transcription backend URL uses the same current host.
|
||||||
|
- Static checks only; no live network change or Netplan operation is performed by this package.
|
||||||
Executable
+335
@@ -0,0 +1,335 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
"""Restricted root helper for AI Station Portal v0.8."""
|
||||||
|
import fcntl, base64, json, os, re, subprocess, sys, ipaddress, time
|
||||||
|
from pathlib import Path
|
||||||
|
from zoneinfo import available_timezones
|
||||||
|
|
||||||
|
STATE_DIR = Path('/var/lib/ai-station-portal')
|
||||||
|
STATE = STATE_DIR / 'network-try.json'
|
||||||
|
DBUS_SERVICE = 'io.netplan.Netplan'
|
||||||
|
DBUS_ROOT = '/io/netplan/Netplan'
|
||||||
|
DBUS_IFACE = 'io.netplan.Netplan'
|
||||||
|
DBUS_CONFIG_IFACE = 'io.netplan.Netplan.Config'
|
||||||
|
NETPLAN_TIMEOUT = 120
|
||||||
|
|
||||||
|
def run(*args, timeout=30):
|
||||||
|
return subprocess.run(args, check=True, timeout=timeout, capture_output=True, text=True)
|
||||||
|
|
||||||
|
def write(path, data, mode=0o600):
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
tmp = path.with_suffix(path.suffix + '.tmp')
|
||||||
|
tmp.write_text(data)
|
||||||
|
os.chmod(tmp, mode)
|
||||||
|
os.replace(tmp, path)
|
||||||
|
|
||||||
|
def busctl(*args, timeout=15):
|
||||||
|
return subprocess.run(
|
||||||
|
['/usr/bin/busctl', '--system', *args],
|
||||||
|
check=True, timeout=timeout, capture_output=True, text=True
|
||||||
|
).stdout.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def dbus_config_create():
|
||||||
|
output = busctl('call', DBUS_SERVICE, DBUS_ROOT, DBUS_IFACE, 'Config')
|
||||||
|
match = re.fullmatch(r'o "(/io/netplan/Netplan/config/[A-Z0-9]+)"', output)
|
||||||
|
if not match:
|
||||||
|
raise RuntimeError(f'Unexpected Netplan D-Bus Config response: {output}')
|
||||||
|
return match.group(1)
|
||||||
|
|
||||||
|
|
||||||
|
def dbus_config_call(obj, method, *signature_and_values, timeout=15):
|
||||||
|
output = busctl(
|
||||||
|
'call', DBUS_SERVICE, obj, DBUS_CONFIG_IFACE, method,
|
||||||
|
*signature_and_values, timeout=timeout
|
||||||
|
)
|
||||||
|
if output != 'b true':
|
||||||
|
raise RuntimeError(f'Netplan D-Bus {method} failed: {output}')
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def dbus_object_exists(obj):
|
||||||
|
result = subprocess.run(
|
||||||
|
['/usr/bin/busctl', '--system', 'introspect', DBUS_SERVICE, obj],
|
||||||
|
capture_output=True, text=True, timeout=8, check=False
|
||||||
|
)
|
||||||
|
return result.returncode == 0
|
||||||
|
|
||||||
|
|
||||||
|
def network_apply(encoded):
|
||||||
|
"""Create an isolated Netplan config and start its native Try transaction."""
|
||||||
|
lock_path = Path('/run/lock/ai-station-network.lock')
|
||||||
|
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with lock_path.open('w') as lock:
|
||||||
|
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||||
|
return _network_apply_locked(encoded)
|
||||||
|
|
||||||
|
|
||||||
|
def _network_apply_locked(encoded):
|
||||||
|
if STATE.exists():
|
||||||
|
old = json.loads(STATE.read_text())
|
||||||
|
if dbus_object_exists(old.get('object', '')):
|
||||||
|
raise ValueError('A network change is already pending')
|
||||||
|
STATE.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
cfg = json.loads(base64.urlsafe_b64decode(encoded.encode()).decode())
|
||||||
|
if cfg.get('mode') not in ('dhcp', 'static'):
|
||||||
|
raise ValueError('Invalid mode')
|
||||||
|
|
||||||
|
current = subprocess.check_output(
|
||||||
|
['/usr/sbin/netplan', 'get', 'network.ethernets.lan0'],
|
||||||
|
text=True, timeout=10
|
||||||
|
)
|
||||||
|
mac_match = re.search(
|
||||||
|
r'^\s*macaddress:\s*"?([0-9a-fA-F]{2}(?::[0-9a-fA-F]{2}){5})',
|
||||||
|
current, re.MULTILINE
|
||||||
|
)
|
||||||
|
mac = mac_match.group(1) if mac_match else Path(
|
||||||
|
'/sys/class/net/lan0/address'
|
||||||
|
).read_text().strip()
|
||||||
|
if not re.fullmatch(r'(?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}', mac):
|
||||||
|
raise ValueError('Invalid interface MAC')
|
||||||
|
|
||||||
|
# Netplan D-Bus Set() merges YAML values. Empty arrays do not reliably
|
||||||
|
# replace inherited lists, so remove the existing keys with NULL first.
|
||||||
|
# This prevents old addresses, routes and DNS entries accumulating.
|
||||||
|
deltas = [
|
||||||
|
f'network.ethernets.lan0.match.macaddress="{mac.lower()}"',
|
||||||
|
'network.ethernets.lan0.set-name=lan0',
|
||||||
|
'network.ethernets.lan0.dhcp4=' + ('true' if cfg['mode'] == 'dhcp' else 'false'),
|
||||||
|
'network.ethernets.lan0.addresses=NULL',
|
||||||
|
'network.ethernets.lan0.routes=NULL',
|
||||||
|
'network.ethernets.lan0.nameservers.addresses=NULL',
|
||||||
|
'network.ethernets.lan0.nameservers.search=NULL',
|
||||||
|
]
|
||||||
|
if cfg['mode'] == 'static':
|
||||||
|
interface = ipaddress.ip_interface(cfg['address'])
|
||||||
|
gateway = ipaddress.ip_address(cfg['gateway'])
|
||||||
|
if interface.version != 4 or gateway.version != 4 or gateway not in interface.network:
|
||||||
|
raise ValueError('Invalid IPv4 network')
|
||||||
|
deltas.extend([
|
||||||
|
f'network.ethernets.lan0.addresses=["{interface}"]',
|
||||||
|
f'network.ethernets.lan0.routes=[{{to: default, via: {gateway}}}]',
|
||||||
|
])
|
||||||
|
dns = []
|
||||||
|
for value in (cfg.get('dns1'), cfg.get('dns2')):
|
||||||
|
if value:
|
||||||
|
dns_ip = ipaddress.ip_address(value)
|
||||||
|
if dns_ip.version != 4:
|
||||||
|
raise ValueError('DNS must be IPv4')
|
||||||
|
dns.append(str(dns_ip))
|
||||||
|
deltas.append('network.ethernets.lan0.nameservers.addresses=[' + ', '.join('"'+x+'"' for x in dns) + ']')
|
||||||
|
domain = cfg.get('search_domain', '').strip()
|
||||||
|
if domain:
|
||||||
|
labels = domain.rstrip('.').split('.')
|
||||||
|
if len(domain) > 253 or any(not re.fullmatch(r'(?i)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?', x) for x in labels):
|
||||||
|
raise ValueError('Invalid search domain')
|
||||||
|
domain = '.'.join(labels)
|
||||||
|
deltas.append('network.ethernets.lan0.nameservers.search=["' + domain + '"]')
|
||||||
|
else:
|
||||||
|
deltas.append('network.ethernets.lan0.nameservers.search=[]')
|
||||||
|
else:
|
||||||
|
# Explicitly clear static properties inherited from the existing profile.
|
||||||
|
deltas.extend([
|
||||||
|
])
|
||||||
|
|
||||||
|
obj = dbus_config_create()
|
||||||
|
try:
|
||||||
|
for delta in deltas:
|
||||||
|
dbus_config_call(obj, 'Set', 'ss', delta, '50-cloud-init')
|
||||||
|
|
||||||
|
# Validate the merged candidate before touching the live network.
|
||||||
|
merged = busctl('call', DBUS_SERVICE, obj, DBUS_CONFIG_IFACE, 'Get', timeout=10)
|
||||||
|
if 'lan0' not in merged:
|
||||||
|
raise RuntimeError('Candidate Netplan configuration does not contain lan0')
|
||||||
|
|
||||||
|
expected = '' if cfg['mode'] == 'dhcp' else str(interface)
|
||||||
|
state = {
|
||||||
|
'object': obj,
|
||||||
|
'started_at': time.time(),
|
||||||
|
'timeout': NETPLAN_TIMEOUT,
|
||||||
|
'expected_address': expected,
|
||||||
|
'mode': cfg['mode'],
|
||||||
|
'phase': 'starting',
|
||||||
|
}
|
||||||
|
STATE_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
write(STATE, json.dumps(state), 0o600)
|
||||||
|
|
||||||
|
# D-Bus Try() starts netplan try and returns once its ready stamp exists.
|
||||||
|
dbus_config_call(obj, 'Try', 'u', str(NETPLAN_TIMEOUT), timeout=20)
|
||||||
|
state['phase'] = 'pending'
|
||||||
|
write(STATE, json.dumps(state), 0o600)
|
||||||
|
return 0
|
||||||
|
except Exception:
|
||||||
|
# Cancel discards an un-applied object, or rejects a Try already started.
|
||||||
|
try:
|
||||||
|
if dbus_object_exists(obj):
|
||||||
|
dbus_config_call(obj, 'Cancel', timeout=25)
|
||||||
|
except Exception as cancel_error:
|
||||||
|
print(f'Netplan cleanup warning: {cancel_error}', file=sys.stderr)
|
||||||
|
STATE.unlink(missing_ok=True)
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def network_status():
|
||||||
|
address = ''
|
||||||
|
try:
|
||||||
|
result = subprocess.run(
|
||||||
|
['/usr/sbin/ip', '-o', '-4', 'addr', 'show', 'dev', 'lan0', 'scope', 'global'],
|
||||||
|
capture_output=True, text=True, timeout=5, check=False
|
||||||
|
)
|
||||||
|
match = re.search(r'\binet\s+(\d{1,3}(?:\.\d{1,3}){3}/\d+)', result.stdout)
|
||||||
|
if result.returncode == 0 and match:
|
||||||
|
address = match.group(1)
|
||||||
|
except (subprocess.TimeoutExpired, OSError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
if not STATE.exists():
|
||||||
|
print(json.dumps({'pending': False, 'remaining_seconds': 0, 'try_active': False, 'timer_active': False,
|
||||||
|
'rollback_failed': False, 'address': address}))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
try:
|
||||||
|
state = json.loads(STATE.read_text())
|
||||||
|
obj = state.get('object', '')
|
||||||
|
active = bool(state.get('phase') == 'pending' and obj and dbus_object_exists(obj))
|
||||||
|
if state.get('phase') == 'starting' and obj and dbus_object_exists(obj):
|
||||||
|
# A helper crash before Try() became ready must not look like a live transaction.
|
||||||
|
try:
|
||||||
|
dbus_config_call(obj, 'Cancel', timeout=10)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
except Exception:
|
||||||
|
state, active = {}, False
|
||||||
|
|
||||||
|
if not active:
|
||||||
|
STATE.unlink(missing_ok=True)
|
||||||
|
print(json.dumps({'pending': False, 'remaining_seconds': 0, 'try_active': False, 'timer_active': False,
|
||||||
|
'rollback_failed': False, 'address': address}))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
elapsed = max(0, int(time.time() - float(state.get('started_at', time.time()))))
|
||||||
|
remaining = max(0, int(state.get('timeout', NETPLAN_TIMEOUT)) - elapsed)
|
||||||
|
print(json.dumps({'pending': True, 'remaining_seconds': remaining,
|
||||||
|
'try_active': True, 'timer_active': True, 'rollback_failed': False,
|
||||||
|
'address': address, 'expected_address': state.get('expected_address', '')}))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def network_confirm():
|
||||||
|
lock_path = Path('/run/lock/ai-station-network.lock')
|
||||||
|
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with lock_path.open('w') as lock:
|
||||||
|
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||||
|
if not STATE.exists():
|
||||||
|
raise RuntimeError('No pending Netplan configuration')
|
||||||
|
state = json.loads(STATE.read_text())
|
||||||
|
obj = state.get('object', '')
|
||||||
|
if not obj or not dbus_object_exists(obj):
|
||||||
|
STATE.unlink(missing_ok=True)
|
||||||
|
raise RuntimeError('Netplan Try has already ended or rolled back')
|
||||||
|
|
||||||
|
expected = state.get('expected_address', '')
|
||||||
|
current = subprocess.run(
|
||||||
|
['/usr/sbin/ip', '-o', '-4', 'addr', 'show', 'dev', 'lan0', 'scope', 'global'],
|
||||||
|
capture_output=True, text=True, timeout=5, check=False
|
||||||
|
)
|
||||||
|
addresses = re.findall(r'\binet\s+(\d{1,3}(?:\.\d{1,3}){3}/\d+)', current.stdout)
|
||||||
|
if expected and expected not in addresses:
|
||||||
|
raise RuntimeError(f'Current interface address does not match candidate: expected {expected}, found {addresses}')
|
||||||
|
if not expected and not addresses:
|
||||||
|
raise RuntimeError('No IPv4 address is configured on lan0; refusing confirmation')
|
||||||
|
|
||||||
|
dbus_config_call(obj, 'Apply', timeout=25)
|
||||||
|
STATE.unlink(missing_ok=True)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def network_cancel():
|
||||||
|
if not STATE.exists():
|
||||||
|
return 0
|
||||||
|
state = json.loads(STATE.read_text())
|
||||||
|
obj = state.get('object', '')
|
||||||
|
if obj and dbus_object_exists(obj):
|
||||||
|
dbus_config_call(obj, 'Cancel', timeout=25)
|
||||||
|
STATE.unlink(missing_ok=True)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def network_read(iface):
|
||||||
|
if iface != 'lan0':
|
||||||
|
raise ValueError('Unsupported interface')
|
||||||
|
def output(*args):
|
||||||
|
try:
|
||||||
|
return run(*args, timeout=8).stdout.strip()
|
||||||
|
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError):
|
||||||
|
return ''
|
||||||
|
addr_text = output('/usr/sbin/ip', '-o', '-4', 'addr', 'show', 'dev', iface)
|
||||||
|
addr_match = re.search(r'\binet\s+(\d{1,3}(?:\.\d{1,3}){3}/\d+)', addr_text)
|
||||||
|
route_text = output('/usr/sbin/ip', '-4', 'route', 'show', 'default', 'dev', iface)
|
||||||
|
gw_match = re.search(r'\bvia\s+(\d{1,3}(?:\.\d{1,3}){3})', route_text)
|
||||||
|
dns_text = output('/usr/bin/resolvectl', 'dns', iface)
|
||||||
|
dns_match = re.search(r'^Link\s+\d+\s+\([^)]*\):\s*(.*)$', dns_text, re.MULTILINE)
|
||||||
|
dns = re.findall(r'(?:\d{1,3}\.){3}\d{1,3}', dns_match.group(1)) if dns_match else []
|
||||||
|
domain_text = output('/usr/bin/resolvectl', 'domain', iface)
|
||||||
|
domain_match = re.search(r'^Link\s+\d+\s+\([^)]*\):\s*(.*)$', domain_text, re.MULTILINE)
|
||||||
|
domains = domain_match.group(1).split() if domain_match else []
|
||||||
|
search_domain = next((d for d in domains if not d.startswith('~')), '')
|
||||||
|
config = output('/usr/sbin/netplan', 'get', 'network.ethernets.' + iface)
|
||||||
|
dhcp_match = re.search(r'^\s*dhcp4:\s*(true|false)\s*$', config, re.MULTILINE | re.IGNORECASE)
|
||||||
|
if not dhcp_match:
|
||||||
|
raise ValueError('Cannot determine DHCP mode from Netplan configuration')
|
||||||
|
mac_path = Path('/sys/class/net') / iface / 'address'
|
||||||
|
mac = mac_path.read_text().strip() if mac_path.exists() else ''
|
||||||
|
print(json.dumps({
|
||||||
|
'interface': iface,
|
||||||
|
'address': addr_match.group(1) if addr_match else '',
|
||||||
|
'gateway': gw_match.group(1) if gw_match else '',
|
||||||
|
'dns1': dns[0] if dns else '',
|
||||||
|
'dns2': dns[1] if len(dns) > 1 else '',
|
||||||
|
'search_domain': search_domain,
|
||||||
|
'dhcp': dhcp_match.group(1).lower() == 'true',
|
||||||
|
'mac': mac,
|
||||||
|
}))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
def main():
|
||||||
|
if len(sys.argv) != 3: return 2
|
||||||
|
action, value = sys.argv[1:]
|
||||||
|
if action == 'hostname':
|
||||||
|
if len(value) > 63 or not re.fullmatch(r'[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?', value): return 2
|
||||||
|
run('/usr/bin/hostnamectl', 'set-hostname', value); return 0
|
||||||
|
if action == 'timezone':
|
||||||
|
if value not in available_timezones(): return 2
|
||||||
|
run('/usr/bin/timedatectl', 'set-timezone', value); return 0
|
||||||
|
if action == 'ntp':
|
||||||
|
if value not in {'yes', 'no'}: return 2
|
||||||
|
run('/usr/bin/timedatectl', 'set-ntp', 'true' if value == 'yes' else 'false'); return 0
|
||||||
|
if action == 'network-read': return network_read(value)
|
||||||
|
if action == 'network-status': return network_status()
|
||||||
|
if action == 'network-apply': return network_apply(value)
|
||||||
|
if action == 'network-confirm': return network_confirm()
|
||||||
|
if action == 'network-cancel': return network_cancel()
|
||||||
|
return 2
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
try:
|
||||||
|
raise SystemExit(main())
|
||||||
|
except subprocess.CalledProcessError as exc:
|
||||||
|
command = ' '.join(str(part) for part in (exc.cmd or []))
|
||||||
|
print(f'Command failed (exit {exc.returncode}): {command}', file=sys.stderr)
|
||||||
|
if exc.stdout:
|
||||||
|
print('STDOUT:', exc.stdout.strip(), file=sys.stderr)
|
||||||
|
if exc.stderr:
|
||||||
|
print('STDERR:', exc.stderr.strip(), file=sys.stderr)
|
||||||
|
raise SystemExit(1)
|
||||||
|
except subprocess.TimeoutExpired as exc:
|
||||||
|
command = ' '.join(str(part) for part in (exc.cmd or []))
|
||||||
|
print(f'Command timed out after {exc.timeout}s: {command}', file=sys.stderr)
|
||||||
|
if exc.stdout:
|
||||||
|
print('STDOUT:', exc.stdout.decode(errors='replace').strip() if isinstance(exc.stdout, bytes) else exc.stdout.strip(), file=sys.stderr)
|
||||||
|
if exc.stderr:
|
||||||
|
print('STDERR:', exc.stderr.decode(errors='replace').strip() if isinstance(exc.stderr, bytes) else exc.stderr.strip(), file=sys.stderr)
|
||||||
|
raise SystemExit(1)
|
||||||
|
except Exception as exc:
|
||||||
|
print(f'{type(exc).__name__}: {exc}', file=sys.stderr)
|
||||||
|
raise SystemExit(1)
|
||||||
@@ -0,0 +1,576 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import pty
|
||||||
|
import fcntl
|
||||||
|
import termios
|
||||||
|
import struct
|
||||||
|
import signal
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
import socket
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
import ipaddress
|
||||||
|
import logging
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from zoneinfo import available_timezones
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from fastapi import FastAPI, File, Form, HTTPException, Request, UploadFile, WebSocket, WebSocketDisconnect
|
||||||
|
from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse, RedirectResponse
|
||||||
|
from io import BytesIO
|
||||||
|
from docx import Document
|
||||||
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
from starlette.middleware.sessions import SessionMiddleware
|
||||||
|
import pam
|
||||||
|
from fastapi.templating import Jinja2Templates
|
||||||
|
|
||||||
|
BASE_DIR = Path(__file__).resolve().parent
|
||||||
|
SERVICES_FILE = BASE_DIR / "services.json"
|
||||||
|
|
||||||
|
SPEACHES_URL = "http://192.168.1.26:8000"
|
||||||
|
WHISPER_MODEL = "Systran/faster-whisper-small"
|
||||||
|
MAX_UPLOAD_BYTES = 500 * 1024 * 1024
|
||||||
|
ALLOWED_EXTENSIONS = {".wav", ".mp3", ".m4a", ".mp4", ".mpeg", ".mpga", ".webm", ".ogg", ".oga", ".flac"}
|
||||||
|
|
||||||
|
app = FastAPI(title="AI Station Portal", version="0.8.2")
|
||||||
|
app.add_middleware(
|
||||||
|
SessionMiddleware,
|
||||||
|
secret_key=os.getenv("AI_STATION_SESSION_SECRET") or secrets.token_urlsafe(48),
|
||||||
|
session_cookie="ai_station_admin",
|
||||||
|
max_age=600,
|
||||||
|
same_site="strict",
|
||||||
|
https_only=os.getenv("AI_STATION_COOKIE_SECURE", "0") == "1",
|
||||||
|
)
|
||||||
|
ADMIN_USER = os.getenv("AI_STATION_ADMIN_USER", "theroot")
|
||||||
|
ADMIN_IDLE_SECONDS = 600
|
||||||
|
ADMIN_HELPER = "/home/theroot/ai-station-portal-v0.8.4-hotfix5/ai-station-portal-admin"
|
||||||
|
app.mount("/static", StaticFiles(directory=BASE_DIR / "static"), name="static")
|
||||||
|
templates = Jinja2Templates(directory=BASE_DIR / "templates")
|
||||||
|
|
||||||
|
|
||||||
|
def load_services(station_host: str | None = None) -> list[dict[str, Any]]:
|
||||||
|
try:
|
||||||
|
data = json.loads(SERVICES_FILE.read_text(encoding="utf-8"))
|
||||||
|
host = station_host or "127.0.0.1"
|
||||||
|
for item in data:
|
||||||
|
for key in ("url", "health_url"):
|
||||||
|
value = item.get(key)
|
||||||
|
if isinstance(value, str):
|
||||||
|
item[key] = value.replace("{station_host}", host)
|
||||||
|
return [item for item in data if item.get("enabled", True)]
|
||||||
|
except (OSError, json.JSONDecodeError):
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
async def check_service(client: httpx.AsyncClient, service: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
item = dict(service)
|
||||||
|
if item.get("internal"):
|
||||||
|
item["status"] = "local"
|
||||||
|
item["status_label"] = "В портале"
|
||||||
|
return item
|
||||||
|
health_url = item.get("health_url") or item.get("url")
|
||||||
|
if not health_url or health_url == "#":
|
||||||
|
item["status"] = "unknown"
|
||||||
|
item["status_label"] = "Не настроен"
|
||||||
|
return item
|
||||||
|
try:
|
||||||
|
response = await client.get(health_url, follow_redirects=True)
|
||||||
|
if response.status_code < 500:
|
||||||
|
item["status"] = "online"
|
||||||
|
item["status_label"] = "Доступен"
|
||||||
|
else:
|
||||||
|
item["status"] = "offline"
|
||||||
|
item["status_label"] = "Ошибка сервиса"
|
||||||
|
except httpx.HTTPError:
|
||||||
|
item["status"] = "offline"
|
||||||
|
item["status_label"] = "Недоступен"
|
||||||
|
return item
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/", response_class=HTMLResponse)
|
||||||
|
async def index(request: Request):
|
||||||
|
services = load_services(request.url.hostname)
|
||||||
|
timeout = httpx.Timeout(2.5, connect=1.5)
|
||||||
|
async with httpx.AsyncClient(timeout=timeout) as client:
|
||||||
|
checked = await asyncio.gather(*(check_service(client, item) for item in services))
|
||||||
|
online_count = sum(item["status"] in {"online", "local"} for item in checked)
|
||||||
|
return templates.TemplateResponse(
|
||||||
|
request=request,
|
||||||
|
name="index.html",
|
||||||
|
context={"services": checked, "online_count": online_count},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/transcription", response_class=HTMLResponse)
|
||||||
|
async def transcription_page(request: Request):
|
||||||
|
return templates.TemplateResponse(
|
||||||
|
request=request,
|
||||||
|
name="transcription.html",
|
||||||
|
context={},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/admin/login", response_class=HTMLResponse)
|
||||||
|
async def admin_login_page(request: Request):
|
||||||
|
if request.session.get("admin_authenticated"):
|
||||||
|
return RedirectResponse("/admin", status_code=303)
|
||||||
|
return templates.TemplateResponse(request=request, name="admin_login.html", context={"error": None})
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/admin/login", response_class=HTMLResponse)
|
||||||
|
async def admin_login(request: Request, password: str = Form(...)):
|
||||||
|
authenticated = False
|
||||||
|
try:
|
||||||
|
authenticated = pam.pam().authenticate(ADMIN_USER, password, service="login")
|
||||||
|
except Exception:
|
||||||
|
authenticated = False
|
||||||
|
if not authenticated:
|
||||||
|
return templates.TemplateResponse(
|
||||||
|
request=request,
|
||||||
|
name="admin_login.html",
|
||||||
|
context={"error": "Неверный системный пароль или ошибка проверки PAM."},
|
||||||
|
status_code=401,
|
||||||
|
)
|
||||||
|
request.session.clear()
|
||||||
|
request.session["admin_authenticated"] = True
|
||||||
|
request.session["admin_user"] = ADMIN_USER
|
||||||
|
request.session["admin_last_seen"] = int(time.time())
|
||||||
|
return RedirectResponse("/admin", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
def admin_session_valid(request: Request) -> bool:
|
||||||
|
last_seen = request.session.get("admin_last_seen", 0)
|
||||||
|
if not request.session.get("admin_authenticated") or time.time() - last_seen > ADMIN_IDLE_SECONDS:
|
||||||
|
request.session.clear()
|
||||||
|
return False
|
||||||
|
request.session["admin_last_seen"] = int(time.time())
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def run_helper(*args: str) -> tuple[bool, str]:
|
||||||
|
try:
|
||||||
|
result = subprocess.run(
|
||||||
|
["sudo", "-n", ADMIN_HELPER, *args],
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
timeout=30 if args and args[0] in {"network-apply", "network-confirm", "network-cancel"} else 15,
|
||||||
|
check=False,
|
||||||
|
)
|
||||||
|
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||||
|
return False, str(exc)
|
||||||
|
output = "\n".join(part.strip() for part in (result.stdout, result.stderr) if part and part.strip())
|
||||||
|
return result.returncode == 0, output
|
||||||
|
|
||||||
|
|
||||||
|
def timedatectl_value(property_name: str) -> str | None:
|
||||||
|
"""Read the live system value from systemd-timedated, not cached config files."""
|
||||||
|
try:
|
||||||
|
result = subprocess.run(
|
||||||
|
["timedatectl", "show", f"-p{property_name}", "--value"],
|
||||||
|
capture_output=True, text=True, timeout=5, check=False,
|
||||||
|
)
|
||||||
|
if result.returncode == 0:
|
||||||
|
return result.stdout.strip()
|
||||||
|
except (OSError, subprocess.TimeoutExpired):
|
||||||
|
pass
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def get_system_settings() -> dict[str, str]:
|
||||||
|
timezone_name = timedatectl_value("Timezone")
|
||||||
|
if not timezone_name:
|
||||||
|
# Fallback to the active localtime symlink; /etc/timezone can be stale.
|
||||||
|
try:
|
||||||
|
localtime = Path("/etc/localtime").resolve()
|
||||||
|
marker = "/zoneinfo/"
|
||||||
|
if marker in str(localtime):
|
||||||
|
timezone_name = str(localtime).split(marker, 1)[1]
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
if not timezone_name:
|
||||||
|
timezone_name = "Unknown"
|
||||||
|
|
||||||
|
ntp_value = timedatectl_value("NTP")
|
||||||
|
ntp_enabled = "yes" if ntp_value == "yes" else "no" if ntp_value == "no" else "unknown"
|
||||||
|
now = datetime.now().astimezone()
|
||||||
|
return {
|
||||||
|
"hostname": socket.gethostname(),
|
||||||
|
"timezone": timezone_name,
|
||||||
|
"ntp": ntp_enabled,
|
||||||
|
"local_time": now.strftime("%Y-%m-%d %H:%M:%S %Z"),
|
||||||
|
"utc_time": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def read_network_settings() -> dict[str, Any]:
|
||||||
|
"""Read privileged Netplan configuration through the restricted root helper."""
|
||||||
|
ok, output = run_helper("network-read", "lan0")
|
||||||
|
if not ok:
|
||||||
|
return {
|
||||||
|
"interface": "lan0", "address": "", "gateway": "",
|
||||||
|
"dns1": "", "dns2": "", "search_domain": "",
|
||||||
|
"dhcp": False, "mac": "", "read_error": output or "Не удалось прочитать сетевую конфигурацию",
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
data = json.loads(output)
|
||||||
|
data["read_error"] = ""
|
||||||
|
return data
|
||||||
|
except (json.JSONDecodeError, TypeError):
|
||||||
|
return {
|
||||||
|
"interface": "lan0", "address": "", "gateway": "",
|
||||||
|
"dns1": "", "dns2": "", "search_domain": "",
|
||||||
|
"dhcp": False, "mac": "", "read_error": "Некорректный ответ системного helper",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def validate_network_form(mode: str, address: str, gateway: str, dns1: str, dns2: str, search_domain: str) -> dict[str, str]:
|
||||||
|
if mode not in {"dhcp", "static"}:
|
||||||
|
raise ValueError("invalid mode")
|
||||||
|
result = {"mode": mode}
|
||||||
|
if mode == "static":
|
||||||
|
interface = ipaddress.ip_interface(address.strip())
|
||||||
|
gw = ipaddress.ip_address(gateway.strip())
|
||||||
|
if interface.version != 4 or gw.version != 4 or gw not in interface.network:
|
||||||
|
raise ValueError("invalid address/gateway")
|
||||||
|
result.update({"address": str(interface), "gateway": str(gw)})
|
||||||
|
for key, value in (("dns1", dns1), ("dns2", dns2)):
|
||||||
|
value = value.strip()
|
||||||
|
if value:
|
||||||
|
ip = ipaddress.ip_address(value)
|
||||||
|
if ip.version != 4:
|
||||||
|
raise ValueError("DNS must be IPv4")
|
||||||
|
result[key] = str(ip)
|
||||||
|
domain = search_domain.strip()
|
||||||
|
if domain:
|
||||||
|
if len(domain) > 253 or not re.fullmatch(r"(?i)[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?", domain):
|
||||||
|
raise ValueError("invalid search domain")
|
||||||
|
result["search_domain"] = domain
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/admin", response_class=HTMLResponse)
|
||||||
|
async def admin_page(request: Request):
|
||||||
|
if not admin_session_valid(request):
|
||||||
|
return RedirectResponse("/admin/login", status_code=303)
|
||||||
|
network_state = {"pending": False, "remaining_seconds": 0, "try_active": False, "timer_active": False, "rollback_failed": False}
|
||||||
|
ok, status_output = run_helper("network-status", "status")
|
||||||
|
if ok:
|
||||||
|
try:
|
||||||
|
network_state = json.loads(status_output)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass
|
||||||
|
network = read_network_settings()
|
||||||
|
network_url = ""
|
||||||
|
if network.get("address"):
|
||||||
|
try:
|
||||||
|
current_ip = str(ipaddress.ip_interface(network["address"]).ip)
|
||||||
|
port = request.url.port
|
||||||
|
host = f"{current_ip}:{port}" if port else current_ip
|
||||||
|
network_url = f"{request.url.scheme}://{host}/admin"
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
return templates.TemplateResponse(
|
||||||
|
request=request,
|
||||||
|
name="admin.html",
|
||||||
|
context={
|
||||||
|
"admin_user": ADMIN_USER,
|
||||||
|
"settings": get_system_settings(),
|
||||||
|
"timezones": sorted(available_timezones()),
|
||||||
|
"network": network,
|
||||||
|
"network_url": network_url,
|
||||||
|
"network_state": network_state,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/admin/settings/network")
|
||||||
|
async def update_network(
|
||||||
|
request: Request,
|
||||||
|
mode: str = Form(...),
|
||||||
|
address: str = Form(""),
|
||||||
|
gateway: str = Form(""),
|
||||||
|
dns1: str = Form(""),
|
||||||
|
dns2: str = Form(""),
|
||||||
|
search_domain: str = Form(""),
|
||||||
|
):
|
||||||
|
if not admin_session_valid(request):
|
||||||
|
return RedirectResponse("/admin/login", status_code=303)
|
||||||
|
try:
|
||||||
|
config = validate_network_form(mode, address, gateway, dns1, dns2, search_domain)
|
||||||
|
except ValueError:
|
||||||
|
return RedirectResponse("/admin?error=invalid-network", status_code=303)
|
||||||
|
import base64
|
||||||
|
payload = base64.urlsafe_b64encode(json.dumps(config).encode()).decode()
|
||||||
|
ok, output = run_helper("network-apply", payload)
|
||||||
|
if not ok:
|
||||||
|
logging.getLogger("ai_station_portal").error(
|
||||||
|
"network-apply helper failed: %s", output or "no diagnostic output"
|
||||||
|
)
|
||||||
|
return RedirectResponse("/admin?error=network-apply", status_code=303)
|
||||||
|
|
||||||
|
# After a static IP change, send the browser directly to the candidate address.
|
||||||
|
if config.get("mode") == "static":
|
||||||
|
target_ip = str(ipaddress.ip_interface(config["address"]).ip)
|
||||||
|
port = request.url.port
|
||||||
|
host = f"{target_ip}:{port}" if port else target_ip
|
||||||
|
target_url = f"{request.url.scheme}://{host}/admin?result=network-pending"
|
||||||
|
return RedirectResponse(target_url, status_code=303)
|
||||||
|
return RedirectResponse("/admin?result=network-pending", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/admin/settings/network/status")
|
||||||
|
async def network_status(request: Request):
|
||||||
|
if not admin_session_valid(request):
|
||||||
|
raise HTTPException(status_code=401, detail="Admin authentication required")
|
||||||
|
ok, output = run_helper("network-status", "status")
|
||||||
|
if not ok:
|
||||||
|
raise HTTPException(status_code=503, detail=output or "Не удалось получить состояние таймера")
|
||||||
|
try:
|
||||||
|
return JSONResponse(json.loads(output))
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
raise HTTPException(status_code=502, detail="Некорректный ответ системного helper")
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/admin/settings/network/confirm")
|
||||||
|
async def confirm_network(request: Request):
|
||||||
|
if not admin_session_valid(request):
|
||||||
|
return RedirectResponse("/admin/login", status_code=303)
|
||||||
|
ok, _ = run_helper("network-confirm", "confirm")
|
||||||
|
return RedirectResponse("/admin?result=network-confirmed" if ok else "/admin?error=network-confirm", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/admin/settings/hostname")
|
||||||
|
async def update_hostname(request: Request, hostname: str = Form(...)):
|
||||||
|
if not admin_session_valid(request):
|
||||||
|
return RedirectResponse("/admin/login", status_code=303)
|
||||||
|
hostname = hostname.strip().lower()
|
||||||
|
if len(hostname) > 63 or not re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", hostname):
|
||||||
|
return RedirectResponse("/admin?error=invalid-hostname", status_code=303)
|
||||||
|
ok, _ = run_helper("hostname", hostname)
|
||||||
|
return RedirectResponse("/admin?result=hostname-ok" if ok else "/admin?error=helper", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/admin/settings/timezone")
|
||||||
|
async def update_timezone(request: Request, timezone_name: str = Form(...)):
|
||||||
|
if not admin_session_valid(request):
|
||||||
|
return RedirectResponse("/admin/login", status_code=303)
|
||||||
|
if timezone_name not in available_timezones():
|
||||||
|
return RedirectResponse("/admin?error=invalid-timezone", status_code=303)
|
||||||
|
ok, _ = run_helper("timezone", timezone_name)
|
||||||
|
actual = timedatectl_value("Timezone") if ok else None
|
||||||
|
if not ok:
|
||||||
|
return RedirectResponse("/admin?error=helper", status_code=303)
|
||||||
|
if actual != timezone_name:
|
||||||
|
return RedirectResponse("/admin?error=verify-timezone", status_code=303)
|
||||||
|
return RedirectResponse("/admin?result=timezone-ok", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/admin/settings/ntp")
|
||||||
|
async def update_ntp(request: Request, enabled: str = Form(...)):
|
||||||
|
if not admin_session_valid(request):
|
||||||
|
return RedirectResponse("/admin/login", status_code=303)
|
||||||
|
if enabled not in {"yes", "no"}:
|
||||||
|
return RedirectResponse("/admin?error=invalid-ntp", status_code=303)
|
||||||
|
ok, _ = run_helper("ntp", enabled)
|
||||||
|
actual = timedatectl_value("NTP") if ok else None
|
||||||
|
if not ok:
|
||||||
|
return RedirectResponse("/admin?error=helper", status_code=303)
|
||||||
|
if actual != enabled:
|
||||||
|
return RedirectResponse("/admin?error=verify-ntp", status_code=303)
|
||||||
|
return RedirectResponse("/admin?result=ntp-ok", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/admin/terminal", response_class=HTMLResponse)
|
||||||
|
async def admin_terminal_page(request: Request):
|
||||||
|
if not admin_session_valid(request):
|
||||||
|
return RedirectResponse("/admin/login", status_code=303)
|
||||||
|
return templates.TemplateResponse(
|
||||||
|
request=request,
|
||||||
|
name="terminal.html",
|
||||||
|
context={"admin_user": ADMIN_USER},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.websocket("/admin/terminal/ws")
|
||||||
|
async def admin_terminal_ws(websocket: WebSocket):
|
||||||
|
# Require the same-origin browser session used by the admin panel.
|
||||||
|
session = websocket.session
|
||||||
|
last_seen = session.get("admin_last_seen", 0)
|
||||||
|
if (
|
||||||
|
not session.get("admin_authenticated")
|
||||||
|
or time.time() - last_seen > ADMIN_IDLE_SECONDS
|
||||||
|
or session.get("admin_user") != ADMIN_USER
|
||||||
|
):
|
||||||
|
await websocket.close(code=4401, reason="Admin authentication required")
|
||||||
|
return
|
||||||
|
|
||||||
|
origin = websocket.headers.get("origin", "")
|
||||||
|
host = websocket.headers.get("host", "")
|
||||||
|
if not origin or not host or origin.split("://", 1)[-1].rstrip("/").lower() != host.lower():
|
||||||
|
await websocket.close(code=4403, reason="Invalid origin")
|
||||||
|
return
|
||||||
|
|
||||||
|
await websocket.accept()
|
||||||
|
master_fd = None
|
||||||
|
child = None
|
||||||
|
try:
|
||||||
|
master_fd, slave_fd = pty.openpty()
|
||||||
|
# The shell runs as the portal service account (normally theroot), never as root.
|
||||||
|
env = os.environ.copy()
|
||||||
|
env.update({"TERM": "xterm-256color", "COLORTERM": "truecolor"})
|
||||||
|
child = subprocess.Popen(
|
||||||
|
["/bin/bash", "-l"],
|
||||||
|
stdin=slave_fd,
|
||||||
|
stdout=slave_fd,
|
||||||
|
stderr=slave_fd,
|
||||||
|
cwd=os.path.expanduser("~"),
|
||||||
|
env=env,
|
||||||
|
close_fds=True,
|
||||||
|
start_new_session=True,
|
||||||
|
)
|
||||||
|
os.close(slave_fd)
|
||||||
|
os.set_blocking(master_fd, False)
|
||||||
|
|
||||||
|
async def read_pty():
|
||||||
|
while child and child.poll() is None:
|
||||||
|
try:
|
||||||
|
data = await asyncio.to_thread(os.read, master_fd, 4096)
|
||||||
|
except BlockingIOError:
|
||||||
|
await asyncio.sleep(0.02)
|
||||||
|
continue
|
||||||
|
except OSError:
|
||||||
|
break
|
||||||
|
if not data:
|
||||||
|
break
|
||||||
|
await websocket.send_text(data.decode("utf-8", errors="replace"))
|
||||||
|
|
||||||
|
reader = asyncio.create_task(read_pty())
|
||||||
|
while child.poll() is None:
|
||||||
|
try:
|
||||||
|
message = await asyncio.wait_for(websocket.receive_json(), timeout=1.0)
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
continue
|
||||||
|
kind = message.get("type")
|
||||||
|
if kind == "input":
|
||||||
|
value = str(message.get("data", ""))
|
||||||
|
if len(value) > 8192:
|
||||||
|
continue
|
||||||
|
os.write(master_fd, value.encode("utf-8", errors="ignore"))
|
||||||
|
elif kind == "resize":
|
||||||
|
cols = max(20, min(300, int(message.get("cols", 100))))
|
||||||
|
rows = max(5, min(100, int(message.get("rows", 30))))
|
||||||
|
fcntl.ioctl(master_fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))
|
||||||
|
os.killpg(child.pid, signal.SIGWINCH)
|
||||||
|
reader.cancel()
|
||||||
|
await asyncio.gather(reader, return_exceptions=True)
|
||||||
|
except (WebSocketDisconnect, OSError, ValueError, TypeError):
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
if child is not None and child.poll() is None:
|
||||||
|
try:
|
||||||
|
os.killpg(child.pid, signal.SIGHUP)
|
||||||
|
child.wait(timeout=2)
|
||||||
|
except Exception:
|
||||||
|
try:
|
||||||
|
os.killpg(child.pid, signal.SIGKILL)
|
||||||
|
except ProcessLookupError:
|
||||||
|
pass
|
||||||
|
if master_fd is not None:
|
||||||
|
try:
|
||||||
|
os.close(master_fd)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
await websocket.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/admin/logout")
|
||||||
|
async def admin_logout(request: Request):
|
||||||
|
request.session.clear()
|
||||||
|
return RedirectResponse("/", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/transcribe")
|
||||||
|
async def transcribe(
|
||||||
|
request: Request,
|
||||||
|
file: UploadFile = File(...),
|
||||||
|
language: str = Form("auto"),
|
||||||
|
):
|
||||||
|
filename = file.filename or "audio"
|
||||||
|
suffix = Path(filename).suffix.lower()
|
||||||
|
if suffix not in ALLOWED_EXTENSIONS:
|
||||||
|
raise HTTPException(status_code=400, detail="Неподдерживаемый формат аудио")
|
||||||
|
|
||||||
|
content = await file.read(MAX_UPLOAD_BYTES + 1)
|
||||||
|
if not content:
|
||||||
|
raise HTTPException(status_code=400, detail="Файл пуст")
|
||||||
|
if len(content) > MAX_UPLOAD_BYTES:
|
||||||
|
raise HTTPException(status_code=413, detail="Максимальный размер файла — 500 МБ")
|
||||||
|
|
||||||
|
data = {"model": WHISPER_MODEL, "response_format": "verbose_json"}
|
||||||
|
if language and language != "auto":
|
||||||
|
data["language"] = language
|
||||||
|
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=httpx.Timeout(3600.0, connect=15.0)) as client:
|
||||||
|
response = await client.post(
|
||||||
|
f"http://{request.url.hostname}:8000/v1/audio/transcriptions",
|
||||||
|
data=data,
|
||||||
|
files={"file": (filename, content, file.content_type or "application/octet-stream")},
|
||||||
|
)
|
||||||
|
response.raise_for_status()
|
||||||
|
except httpx.HTTPStatusError as exc:
|
||||||
|
detail = exc.response.text[:1200] or f"Speaches вернул HTTP {exc.response.status_code}"
|
||||||
|
raise HTTPException(status_code=502, detail=f"Ошибка Speaches: {detail}") from exc
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise HTTPException(status_code=502, detail=f"Не удалось связаться со Speaches: {exc}") from exc
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = response.json()
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=502, detail="Speaches вернул некорректный ответ") from exc
|
||||||
|
|
||||||
|
return JSONResponse({
|
||||||
|
"text": result.get("text", ""),
|
||||||
|
"language": result.get("language"),
|
||||||
|
"duration": result.get("duration"),
|
||||||
|
"segments": result.get("segments", []),
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/export/docx")
|
||||||
|
async def export_docx(request: Request):
|
||||||
|
payload = await request.json()
|
||||||
|
text = str(payload.get("text", ""))
|
||||||
|
if not text.strip():
|
||||||
|
raise HTTPException(status_code=400, detail="Нет текста для экспорта")
|
||||||
|
|
||||||
|
document = Document()
|
||||||
|
document.add_heading("Расшифровка аудио", level=1)
|
||||||
|
for paragraph in text.splitlines():
|
||||||
|
document.add_paragraph(paragraph)
|
||||||
|
|
||||||
|
output = BytesIO()
|
||||||
|
document.save(output)
|
||||||
|
output.seek(0)
|
||||||
|
headers = {"Content-Disposition": 'attachment; filename="transcript.docx"'}
|
||||||
|
return StreamingResponse(
|
||||||
|
output,
|
||||||
|
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health")
|
||||||
|
async def health():
|
||||||
|
return {"status": "ok"}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
fastapi>=0.115,<1
|
||||||
|
uvicorn[standard]>=0.30,<1
|
||||||
|
jinja2>=3.1,<4
|
||||||
|
httpx>=0.27,<1
|
||||||
|
python-multipart>=0.0.9
|
||||||
|
python-docx>=1.1,<2
|
||||||
|
python-pam>=2.0.2,<3
|
||||||
|
itsdangerous>=2.2,<3
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"name": "Open WebUI",
|
||||||
|
"description": "Интерфейс работы с языковыми моделями",
|
||||||
|
"url": "http://{station_host}:3000",
|
||||||
|
"health_url": "http://{station_host}:3000/health",
|
||||||
|
"icon": "bi-chat-square-text",
|
||||||
|
"enabled": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "LLM Systems Manager",
|
||||||
|
"description": "Управление LLM-сервисами и моделями",
|
||||||
|
"url": "http://{station_host}:5000/",
|
||||||
|
"health_url": "http://{station_host}:5000/",
|
||||||
|
"icon": "bi-cpu",
|
||||||
|
"enabled": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Расшифровка аудио",
|
||||||
|
"description": "Загрузка записей и создание стенограмм",
|
||||||
|
"url": "/transcription",
|
||||||
|
"icon": "bi-file-earmark-music",
|
||||||
|
"enabled": true,
|
||||||
|
"internal": true
|
||||||
|
}
|
||||||
|
]
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
:root { color-scheme: dark; }
|
||||||
|
body { min-height: 100vh; background: radial-gradient(ellipse at 15% 0%, #1b2b42 0, #111827 42%, #0b1120 100%); }
|
||||||
|
.service-card { background: rgba(25, 35, 52, .78); border: 1px solid rgba(148, 163, 184, .17); color: #f1f5f9; transition: transform .15s ease, border-color .15s ease, background .15s ease; }
|
||||||
|
.service-card:hover { color: #fff; transform: translateY(-3px); border-color: rgba(96, 165, 250, .65); background: rgba(34, 48, 70, .95); }
|
||||||
|
.service-icon { width: 48px; height: 48px; display: grid; place-items: center; border-radius: 14px; background: rgba(59, 130, 246, .14); color: #93c5fd; font-size: 1.45rem; }
|
||||||
|
.upload-area { border: 1px dashed rgba(148, 163, 184, .45); border-radius: 1rem; cursor: pointer; background: rgba(15, 23, 42, .35); transition: border-color .15s ease, background .15s ease; }
|
||||||
|
.upload-area:hover, .upload-area.drag-over { border-color: #60a5fa; background: rgba(59, 130, 246, .10); }
|
||||||
|
.transcript-area { min-height: 22rem; line-height: 1.65; }
|
||||||
@@ -0,0 +1,321 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="ru" data-bs-theme="dark">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Администрирование — AI Station</title>
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.min.css" rel="stylesheet">
|
||||||
|
<link href="/static/style.css" rel="stylesheet">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main class="container py-5" style="max-width:1000px">
|
||||||
|
<header class="d-flex align-items-center justify-content-between mb-4 gap-3">
|
||||||
|
<div><div class="text-secondary small text-uppercase fw-semibold mb-2">AI Station</div><h1 class="h2 mb-1">Администрирование</h1><div class="text-secondary">Вход выполнен: {{ admin_user }}</div></div>
|
||||||
|
<div class="d-flex gap-2 flex-wrap">
|
||||||
|
<a class="btn btn-outline-danger" href="/admin/terminal" target="_blank" rel="noopener"><i class="bi bi-terminal me-2"></i>Открыть терминал</a>
|
||||||
|
<form method="post" action="/admin/logout"><button class="btn btn-outline-secondary" type="submit"><i class="bi bi-box-arrow-right me-2"></i>Выйти</button></form>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{% if network_state.pending %}
|
||||||
|
<div class="alert alert-warning" id="networkPending">
|
||||||
|
<strong>Сеть перенастроена.</strong> Проверьте доступность портала и сервисов. Если всё работает, подтвердите новую конфигурацию.
|
||||||
|
{% if network_url %}
|
||||||
|
<div class="mt-2">
|
||||||
|
Адрес портала: <a href="{{ network_url }}" class="link-info fw-semibold" id="networkPortalLink">{{ network_url }}</a>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
<div class="mt-3 mb-2">
|
||||||
|
<div class="small text-secondary">До автоматического отката осталось</div>
|
||||||
|
<div class="fs-2 fw-bold font-monospace" id="networkCountdown" aria-live="polite">Загрузка таймера…</div>
|
||||||
|
<div class="progress mt-2" style="height:6px"><div class="progress-bar bg-warning" id="networkCountdownBar" style="width:100%"></div></div>
|
||||||
|
</div>
|
||||||
|
{% if network_state.try_active or network_state.timer_active %}
|
||||||
|
<form method="post" action="/admin/settings/network/confirm" class="mt-3" id="networkConfirmForm">
|
||||||
|
<button class="btn btn-success" type="submit" id="networkConfirmButton">Подтвердить новую конфигурацию</button>
|
||||||
|
</form>
|
||||||
|
{% else %}
|
||||||
|
<div class="small mt-2 text-danger" id="networkTimerError">Netplan не подтвердил запуск временной конфигурации. Проверьте состояние сети.</div>
|
||||||
|
{% endif %}
|
||||||
|
<div class="small mt-2" id="networkCountdownHint">Если не подтвердить изменения до окончания отсчёта, система автоматически восстановит предыдущую конфигурацию.</div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
(() => {
|
||||||
|
const countdown = document.getElementById('networkCountdown');
|
||||||
|
const bar = document.getElementById('networkCountdownBar');
|
||||||
|
const button = document.getElementById('networkConfirmButton');
|
||||||
|
const form = document.getElementById('networkConfirmForm');
|
||||||
|
const hint = document.getElementById('networkCountdownHint');
|
||||||
|
const timerError = document.getElementById('networkTimerError');
|
||||||
|
const portalLink = document.getElementById('networkPortalLink');
|
||||||
|
|
||||||
|
let remaining = null;
|
||||||
|
let initial = null;
|
||||||
|
let lastSync = Date.now();
|
||||||
|
let lastTick = Date.now();
|
||||||
|
|
||||||
|
function render() {
|
||||||
|
if (remaining === null) return;
|
||||||
|
|
||||||
|
const value = Math.max(0, remaining);
|
||||||
|
const m = String(Math.floor(value / 60)).padStart(2, '0');
|
||||||
|
const s = String(value % 60).padStart(2, '0');
|
||||||
|
|
||||||
|
countdown.textContent = `${m}:${s}`;
|
||||||
|
|
||||||
|
if (initial && bar) {
|
||||||
|
bar.style.width =
|
||||||
|
`${Math.max(0, Math.min(100, value / initial * 100))}%`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value <= 0) {
|
||||||
|
if (button) button.disabled = true;
|
||||||
|
if (hint) {
|
||||||
|
hint.textContent =
|
||||||
|
'Время подтверждения истекло. Ожидается автоматический откат конфигурации.';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function showTimerError(message) {
|
||||||
|
remaining = null;
|
||||||
|
|
||||||
|
if (button) button.disabled = true;
|
||||||
|
if (countdown) countdown.textContent = 'Откат требует внимания';
|
||||||
|
if (timerError) timerError.textContent = message;
|
||||||
|
if (hint) {
|
||||||
|
hint.textContent = 'Подтверждение конфигурации заблокировано.';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function syncStatus() {
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
'/admin/settings/network/status',
|
||||||
|
{ cache: 'no-store' }
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('status unavailable');
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (portalLink && data.address) {
|
||||||
|
const target = new URL(portalLink.href);
|
||||||
|
target.hostname = data.address.split('/')[0];
|
||||||
|
target.pathname = '/admin';
|
||||||
|
target.search = '';
|
||||||
|
target.hash = '';
|
||||||
|
portalLink.href = target.href;
|
||||||
|
portalLink.textContent = target.href;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!data.pending) {
|
||||||
|
remaining = null;
|
||||||
|
if (button) button.disabled = true;
|
||||||
|
countdown.textContent = 'Операция завершена';
|
||||||
|
if (hint) {
|
||||||
|
hint.textContent =
|
||||||
|
'Ожидается обновление состояния страницы.';
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.rollback_failed || !(data.try_active || data.timer_active)) {
|
||||||
|
showTimerError(
|
||||||
|
'Системный таймер не активен или служба отката завершилась ошибкой.'
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.remaining_seconds === null ||
|
||||||
|
data.remaining_seconds === undefined) {
|
||||||
|
showTimerError(
|
||||||
|
'Не удалось определить срок отката. Подтверждение запрещено.'
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
remaining = Math.max(
|
||||||
|
0,
|
||||||
|
Number(data.remaining_seconds) || 0
|
||||||
|
);
|
||||||
|
|
||||||
|
if (initial === null) {
|
||||||
|
initial = Math.max(1, remaining);
|
||||||
|
}
|
||||||
|
|
||||||
|
lastSync = Date.now();
|
||||||
|
lastTick = lastSync;
|
||||||
|
|
||||||
|
if (button) button.disabled = remaining <= 0;
|
||||||
|
|
||||||
|
if (timerError) {
|
||||||
|
timerError.textContent = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
render();
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
// A transient status request failure must not permanently disable
|
||||||
|
// confirmation while Netplan's own Try transaction is running.
|
||||||
|
if (countdown) countdown.textContent =
|
||||||
|
remaining === null ? 'Проверяем состояние Netplan…' : countdown.textContent;
|
||||||
|
if (hint) hint.textContent =
|
||||||
|
'Временно не удалось обновить статус. Повторная проверка через несколько секунд.';
|
||||||
|
lastSync = Date.now();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (form) {
|
||||||
|
form.addEventListener('submit', event => {
|
||||||
|
if (remaining === null || remaining <= 0) {
|
||||||
|
event.preventDefault();
|
||||||
|
if (button) button.disabled = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
setInterval(() => {
|
||||||
|
const now = Date.now();
|
||||||
|
const elapsed = Math.floor((now - lastTick) / 1000);
|
||||||
|
|
||||||
|
if (elapsed > 0 && remaining !== null && remaining > 0) {
|
||||||
|
remaining = Math.max(0, remaining - elapsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
lastTick = now;
|
||||||
|
render();
|
||||||
|
|
||||||
|
if (now - lastSync >= 5000) {
|
||||||
|
syncStatus();
|
||||||
|
}
|
||||||
|
}, 1000);
|
||||||
|
|
||||||
|
syncStatus();
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
{% elif request.query_params.get('result') == 'network-confirmed' %}<div class="alert alert-success">Новая сетевая конфигурация подтверждена.</div>{% elif request.query_params.get('result') %}<div class="alert alert-success">Настройка успешно применена. Некоторые изменения могут отобразиться после обновления страницы.</div>{% endif %}
|
||||||
|
{% if request.query_params.get('error') %}<div class="alert alert-danger">{% if request.query_params.get('error') == 'verify-timezone' %}Команда выполнена, но система не подтвердила изменение часового пояса.{% elif request.query_params.get('error') == 'verify-ntp' %}Команда выполнена, но система не подтвердила изменение NTP.{% elif request.query_params.get('error') == 'invalid-network' %}Проверьте IP-адрес, префикс, шлюз, DNS и домен поиска.{% elif request.query_params.get('error') == 'network-apply' %}Не удалось применить сетевую конфигурацию. Проверьте журнал helper; прежняя конфигурация должна быть восстановлена автоматически.{% elif request.query_params.get('error') == 'network-confirm' %}Не удалось подтвердить сетевую конфигурацию. Проверьте состояние системы.{% else %}Не удалось применить настройку. Проверьте значение и настройку системного helper.{% endif %}</div>{% endif %}
|
||||||
|
|
||||||
|
<section class="card bg-dark border-secondary mb-4">
|
||||||
|
<div class="card-body p-4">
|
||||||
|
<div class="d-flex align-items-center gap-3 mb-3"><i class="bi bi-pc-display fs-3 text-info"></i><div><h2 class="h5 mb-0">Состояние станции</h2><div class="text-secondary small">Текущие системные параметры</div></div></div>
|
||||||
|
<div class="row g-3">
|
||||||
|
<div class="col-md-6"><div class="text-secondary small">Имя машины</div><div class="fw-semibold">{{ settings.hostname }}</div></div>
|
||||||
|
<div class="col-md-6"><div class="text-secondary small">Часовой пояс</div><div class="fw-semibold">{{ settings.timezone }}</div></div>
|
||||||
|
<div class="col-md-6"><div class="text-secondary small">Локальное время</div><div class="fw-semibold">{{ settings.local_time }}</div></div>
|
||||||
|
<div class="col-md-6"><div class="text-secondary small">Синхронизация NTP</div><div class="fw-semibold">{{ 'Включена' if settings.ntp == 'yes' else ('Выключена' if settings.ntp == 'no' else 'Не удалось определить') }}</div></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card bg-dark border-secondary mb-4">
|
||||||
|
<div class="card-body p-4">
|
||||||
|
<h2 class="h5 mb-3"><i class="bi bi-sliders text-info me-2"></i>Общие настройки</h2>
|
||||||
|
<div class="row g-4">
|
||||||
|
<div class="col-md-6">
|
||||||
|
<form method="post" action="/admin/settings/hostname">
|
||||||
|
<label for="hostname" class="form-label">Имя машины (hostname)</label>
|
||||||
|
<div class="input-group"><input class="form-control" id="hostname" name="hostname" value="{{ settings.hostname }}" maxlength="63" pattern="[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?" required><button class="btn btn-outline-info" type="submit">Применить</button></div>
|
||||||
|
<div class="form-text">После изменения новое имя может потребовать перезапуска некоторых сервисов.</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-6">
|
||||||
|
<form method="post" action="/admin/settings/timezone">
|
||||||
|
<label for="timezone_name" class="form-label">Часовой пояс</label>
|
||||||
|
<div class="input-group"><select class="form-select" id="timezone_name" name="timezone_name" required>
|
||||||
|
{% for tz in timezones %}<option value="{{ tz }}" {{ 'selected' if tz == settings.timezone else '' }}>{{ tz }}</option>{% endfor %}
|
||||||
|
</select><button class="btn btn-outline-info" type="submit">Применить</button></div>
|
||||||
|
<div class="form-text">Текущее значение считывается непосредственно из системной конфигурации.</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-6">
|
||||||
|
<form method="post" action="/admin/settings/ntp">
|
||||||
|
<label for="enabled" class="form-label">Синхронизация времени NTP</label>
|
||||||
|
<div class="input-group"><select class="form-select" id="enabled" name="enabled"><option value="yes" {{ 'selected' if settings.ntp == 'yes' else '' }}>Включена</option><option value="no" {{ 'selected' if settings.ntp == 'no' else '' }}>Выключена</option></select><button class="btn btn-outline-info" type="submit">Применить</button></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card bg-dark border-secondary mb-4">
|
||||||
|
<div class="card-body p-4">
|
||||||
|
<h2 class="h5 mb-1"><i class="bi bi-ethernet text-info me-2"></i>Сеть</h2>
|
||||||
|
<p class="text-secondary small mb-3">Интерфейс {{ network.interface }} · MAC {{ network.mac }} · управление Netplan / systemd-networkd</p>
|
||||||
|
<form method="post" action="/admin/settings/network" id="networkForm">
|
||||||
|
<div class="mb-3"><label class="form-label" for="networkMode">Режим IPv4</label>
|
||||||
|
<select class="form-select" id="networkMode" name="mode"><option value="dhcp" {{ 'selected' if network.dhcp else '' }}>DHCP (автоматически)</option><option value="static" {{ 'selected' if not network.dhcp else '' }}>Статический IP</option></select></div>
|
||||||
|
<div id="staticFields" class="row g-3">
|
||||||
|
<div class="col-md-6"><label class="form-label">IP-адрес / префикс</label><input class="form-control" name="address" placeholder="192.168.1.26/24" value="{{ network.address }}"></div>
|
||||||
|
<div class="col-md-6"><label class="form-label">Шлюз</label><input class="form-control" name="gateway" placeholder="192.168.1.1" value="{{ network.gateway }}"></div>
|
||||||
|
<div class="col-md-6"><label class="form-label">Основной DNS</label><input class="form-control" name="dns1" placeholder="192.168.1.2" value="{{ network.dns1 }}"></div>
|
||||||
|
<div class="col-md-6"><label class="form-label">Дополнительный DNS</label><input class="form-control" name="dns2" placeholder="192.168.1.1" value="{{ network.dns2 }}"></div>
|
||||||
|
<div class="col-12"><label class="form-label">DNS Search Domain</label><input class="form-control" name="search_domain" placeholder="example.local" value="{{ network.search_domain }}"></div>
|
||||||
|
</div>
|
||||||
|
<div id="networkTargetPreview" class="alert alert-secondary py-2 small" hidden>
|
||||||
|
После применения портал будет доступен по адресу:
|
||||||
|
<a id="networkTargetPreviewLink" class="link-info fw-semibold" href="#" target="_blank" rel="noopener"></a>
|
||||||
|
</div>
|
||||||
|
<div class="alert alert-info mt-3 mb-3 small">После применения будет запущен 120-секундный автоматический откат. Подтверждайте изменение только после проверки доступа к порталу по новому адресу.</div>
|
||||||
|
<button class="btn btn-outline-info" type="submit" onclick="return confirm('Применить сетевые настройки? При смене IP текущая страница может отключиться.')">Применить сетевые настройки</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<script>
|
||||||
|
const mode = document.getElementById('networkMode');
|
||||||
|
const fields = document.getElementById('staticFields');
|
||||||
|
const addressInput = document.querySelector('#networkForm [name="address"]');
|
||||||
|
const preview = document.getElementById('networkTargetPreview');
|
||||||
|
const previewLink = document.getElementById('networkTargetPreviewLink');
|
||||||
|
|
||||||
|
function updateNetworkPreview() {
|
||||||
|
if (mode.value !== 'static' || !addressInput.value.trim()) {
|
||||||
|
preview.hidden = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ip = addressInput.value.trim().split('/')[0];
|
||||||
|
const octets = ip.split('.');
|
||||||
|
const valid = octets.length === 4 &&
|
||||||
|
octets.every(part => /^\d{1,3}$/.test(part) &&
|
||||||
|
Number(part) >= 0 && Number(part) <= 255);
|
||||||
|
|
||||||
|
if (!valid) {
|
||||||
|
preview.hidden = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const target = new URL(window.location.href);
|
||||||
|
target.hostname = ip;
|
||||||
|
target.pathname = '/admin';
|
||||||
|
target.search = '';
|
||||||
|
target.hash = '';
|
||||||
|
|
||||||
|
previewLink.href = target.href;
|
||||||
|
previewLink.textContent = target.href;
|
||||||
|
preview.hidden = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateNetworkMode() {
|
||||||
|
fields.style.display = mode.value === 'static' ? '' : 'none';
|
||||||
|
updateNetworkPreview();
|
||||||
|
}
|
||||||
|
|
||||||
|
mode.addEventListener('change', updateNetworkMode);
|
||||||
|
addressInput.addEventListener('input', updateNetworkPreview);
|
||||||
|
updateNetworkMode();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<section class="card bg-dark border-secondary">
|
||||||
|
<div class="card-body p-4">
|
||||||
|
<h2 class="h5"><i class="bi bi-shield-lock text-info me-2"></i>Безопасность</h2>
|
||||||
|
<p class="text-secondary mb-0">Смена системного пароля и управление публичными SSH-ключами будут добавлены следующим этапом.</p>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<a href="/" class="d-inline-block mt-4 text-secondary text-decoration-none">← На главную</a>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="ru" data-bs-theme="dark">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Вход в администрирование — AI Station</title>
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||||
|
<link href="/static/style.css" rel="stylesheet">
|
||||||
|
</head>
|
||||||
|
<body class="d-flex align-items-center">
|
||||||
|
<main class="container" style="max-width:440px">
|
||||||
|
<div class="card border-secondary bg-dark shadow-lg">
|
||||||
|
<div class="card-body p-4 p-md-5">
|
||||||
|
<div class="text-secondary small text-uppercase fw-semibold mb-2">AI Station</div>
|
||||||
|
<h1 class="h3 mb-2">Администрирование</h1>
|
||||||
|
<p class="text-secondary mb-4">Введите системный пароль пользователя theroot.</p>
|
||||||
|
{% if error %}<div class="alert alert-danger py-2">{{ error }}</div>{% endif %}
|
||||||
|
<form method="post" action="/admin/login">
|
||||||
|
<label for="password" class="form-label">Системный пароль</label>
|
||||||
|
<input id="password" name="password" type="password" class="form-control form-control-lg mb-3" required autofocus autocomplete="current-password">
|
||||||
|
<button class="btn btn-primary btn-lg w-100" type="submit">Войти</button>
|
||||||
|
</form>
|
||||||
|
<a href="/" class="d-inline-block mt-4 text-secondary text-decoration-none">← Вернуться на главную</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="ru" data-bs-theme="dark">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>AI Station</title>
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.min.css" rel="stylesheet">
|
||||||
|
<link href="/static/style.css" rel="stylesheet">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main class="container py-5">
|
||||||
|
<header class="d-flex align-items-center justify-content-between mb-5">
|
||||||
|
<div>
|
||||||
|
<div class="text-secondary small text-uppercase fw-semibold mb-2">AI infrastructure</div>
|
||||||
|
<h1 class="h2 mb-1">AI Station</h1>
|
||||||
|
<div class="text-secondary">Центр доступа к сервисам станции</div>
|
||||||
|
</div>
|
||||||
|
<span class="badge rounded-pill text-bg-success px-3 py-2"><i class="bi bi-circle-fill me-2 small"></i>{{ online_count }} из {{ services | length }} доступны</span>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<div class="d-flex align-items-center justify-content-between mb-3">
|
||||||
|
<h2 class="h5 mb-0">Сервисы</h2>
|
||||||
|
<span class="text-secondary small">{{ services | length }} сервиса</span>
|
||||||
|
</div>
|
||||||
|
<div class="row g-3">
|
||||||
|
{% for service in services %}
|
||||||
|
<div class="col-12 col-md-6 col-xl-4">
|
||||||
|
<a class="service-card card h-100 text-decoration-none" href="{{ service.url }}" {% if not service.internal and service.url != '#' %}target="_blank" rel="noopener noreferrer"{% endif %}>
|
||||||
|
<div class="card-body p-4">
|
||||||
|
<div class="d-flex align-items-start justify-content-between mb-4">
|
||||||
|
<div class="service-icon"><i class="bi {{ service.icon }}"></i></div>
|
||||||
|
<span class="badge {% if service.status == 'online' or service.status == 'local' %}text-bg-success{% elif service.status == 'offline' %}text-bg-danger{% else %}text-bg-secondary{% endif %}">{{ service.status_label }}</span>
|
||||||
|
</div>
|
||||||
|
<h3 class="h5">{{ service.name }}</h3>
|
||||||
|
<p class="text-secondary mb-0">{{ service.description }}</p>
|
||||||
|
</div>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="col-12"><div class="alert alert-secondary">Сервисы пока не настроены. Отредактируйте services.json.</div></div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<footer class="mt-5 pt-3 border-top border-secondary-subtle d-flex justify-content-between text-secondary small">
|
||||||
|
<span>AI Station Portal v0.8</span>
|
||||||
|
<a class="text-secondary text-decoration-none" href="/admin/login">Администрирование</a>
|
||||||
|
</footer>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="ru" data-bs-theme="dark">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Терминал — AI Station</title>
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||||
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm@5.3.0/css/xterm.css">
|
||||||
|
<link href="/static/style.css" rel="stylesheet">
|
||||||
|
<style>
|
||||||
|
html,body{height:100%;margin:0;background:#0b1220}
|
||||||
|
.terminal-shell{height:calc(100vh - 120px);min-height:360px;background:#080d16;border:1px solid #29364a;border-radius:10px;padding:10px}
|
||||||
|
#terminal{height:100%;width:100%}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main class="container-fluid p-3 p-lg-4">
|
||||||
|
<header class="d-flex align-items-center justify-content-between gap-3 mb-3">
|
||||||
|
<div><div class="text-secondary small text-uppercase">AI Station · {{ admin_user }}</div><h1 class="h4 mb-0">Терминал</h1></div>
|
||||||
|
<div class="d-flex align-items-center gap-2"><span id="connection" class="badge text-bg-secondary">Подключение…</span><a class="btn btn-outline-secondary btn-sm" href="/admin">К администрированию</a></div>
|
||||||
|
</header>
|
||||||
|
<div class="alert alert-warning py-2 small">Shell работает от имени пользователя веб-приложения ({{ admin_user }}), не от root. Для системных команд используйте sudo.</div>
|
||||||
|
<section class="terminal-shell"><div id="terminal"></div></section>
|
||||||
|
</main>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/xterm@5.3.0/lib/xterm.min.js"></script>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/xterm-addon-fit@0.8.0/lib/xterm-addon-fit.min.js"></script>
|
||||||
|
<script>
|
||||||
|
const statusEl=document.getElementById('connection');
|
||||||
|
const term=new Terminal({cursorBlink:true,convertEol:true,scrollback:5000,fontFamily:'ui-monospace,SFMono-Regular,Consolas,monospace',fontSize:14,theme:{background:'#080d16',foreground:'#d8e1ef',cursor:'#62d6ff',selectionBackground:'#29435c'}});
|
||||||
|
const fit=new FitAddon.FitAddon(); term.loadAddon(fit); term.open(document.getElementById('terminal'));
|
||||||
|
let ws;
|
||||||
|
function connect(){
|
||||||
|
const proto=location.protocol==='https:'?'wss':'ws';
|
||||||
|
ws=new WebSocket(`${proto}://${location.host}/admin/terminal/ws`);
|
||||||
|
ws.onopen=()=>{statusEl.className='badge text-bg-success';statusEl.textContent='Подключено';fit.fit();ws.send(JSON.stringify({type:'resize',cols:term.cols,rows:term.rows}));term.focus();};
|
||||||
|
ws.onmessage=e=>term.write(e.data);
|
||||||
|
ws.onclose=e=>{statusEl.className='badge text-bg-danger';statusEl.textContent=e.code===4401?'Сессия истекла':'Отключено';term.write('\r\n\r\n[Соединение закрыто]\r\n');};
|
||||||
|
ws.onerror=()=>{statusEl.className='badge text-bg-danger';statusEl.textContent='Ошибка соединения';};
|
||||||
|
}
|
||||||
|
term.onData(data=>{if(ws&&ws.readyState===WebSocket.OPEN)ws.send(JSON.stringify({type:'input',data}));});
|
||||||
|
const resizeObserver=new ResizeObserver(()=>{fit.fit();if(ws&&ws.readyState===WebSocket.OPEN)ws.send(JSON.stringify({type:'resize',cols:term.cols,rows:term.rows}));});
|
||||||
|
resizeObserver.observe(document.getElementById('terminal'));
|
||||||
|
window.addEventListener('beforeunload',()=>{resizeObserver.disconnect();if(ws)ws.close();});
|
||||||
|
connect();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="ru" data-bs-theme="dark">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Расшифровка аудио — AI Station</title>
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.min.css" rel="stylesheet">
|
||||||
|
<link href="/static/style.css" rel="stylesheet">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main class="container py-5">
|
||||||
|
<header class="d-flex align-items-center justify-content-between gap-3 mb-4">
|
||||||
|
<div>
|
||||||
|
<a href="/" class="text-decoration-none text-secondary small"><i class="bi bi-arrow-left me-1"></i>На главную</a>
|
||||||
|
<h1 class="h2 mt-2 mb-1">Расшифровка аудио</h1>
|
||||||
|
<div class="text-secondary">Локальное распознавание через faster-whisper</div>
|
||||||
|
</div>
|
||||||
|
<span class="badge rounded-pill text-bg-success px-3 py-2">Локальный AI</span>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section class="card border-secondary-subtle bg-dark-subtle mb-4">
|
||||||
|
<div class="card-body p-4">
|
||||||
|
<form id="transcribe-form">
|
||||||
|
<label for="audio-file" class="upload-area d-flex flex-column align-items-center justify-content-center text-center p-5 mb-3">
|
||||||
|
<i class="bi bi-cloud-arrow-up display-4 text-info mb-3"></i>
|
||||||
|
<span class="fw-semibold">Выберите аудиофайл или перетащите его сюда</span>
|
||||||
|
<span class="text-secondary small mt-2">WAV, MP3, M4A, OGG, FLAC, WEBM · до 500 МБ</span>
|
||||||
|
<span id="file-name" class="small text-info mt-3">Файл не выбран</span>
|
||||||
|
</label>
|
||||||
|
<input class="visually-hidden" type="file" id="audio-file" name="file" accept="audio/*,.mp4,.mpeg,.mpga,.webm" required>
|
||||||
|
<div class="row g-3 align-items-end">
|
||||||
|
<div class="col-12 col-md-5">
|
||||||
|
<label for="language" class="form-label">Язык записи</label>
|
||||||
|
<select class="form-select" id="language" name="language">
|
||||||
|
<option value="auto" selected>Автоопределение</option>
|
||||||
|
<option value="ru">Русский</option>
|
||||||
|
<option value="en">Английский</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="col-12 col-md-7 d-grid">
|
||||||
|
<button class="btn btn-primary btn-lg" id="submit-button" type="submit"><i class="bi bi-soundwave me-2"></i>Начать распознавание</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
<div id="progress" class="mt-3 d-none">
|
||||||
|
<div class="d-flex justify-content-between small text-secondary mb-2"><span id="progress-label">Распознавание...</span><span>Пожалуйста, подождите</span></div>
|
||||||
|
<div class="progress" role="progressbar"><div class="progress-bar progress-bar-striped progress-bar-animated" style="width:100%"></div></div>
|
||||||
|
</div>
|
||||||
|
<div id="error" class="alert alert-danger mt-3 mb-0 d-none" role="alert"></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section id="result-section" class="card border-secondary-subtle bg-dark-subtle d-none">
|
||||||
|
<div class="card-body p-4">
|
||||||
|
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
|
||||||
|
<div>
|
||||||
|
<h2 class="h5 mb-1">Результат расшифровки</h2>
|
||||||
|
<div id="result-meta" class="text-secondary small"></div>
|
||||||
|
</div>
|
||||||
|
<div class="d-flex flex-wrap gap-2">
|
||||||
|
<button class="btn btn-outline-light btn-sm" id="copy-button"><i class="bi bi-copy me-1"></i>Копировать</button>
|
||||||
|
<button class="btn btn-outline-light btn-sm" id="txt-button"><i class="bi bi-file-earmark-text me-1"></i>TXT</button>
|
||||||
|
<button class="btn btn-outline-light btn-sm" id="srt-button"><i class="bi bi-subtitles me-1"></i>SRT</button>
|
||||||
|
<button class="btn btn-outline-light btn-sm" id="docx-button"><i class="bi bi-file-earmark-word me-1"></i>DOCX</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<textarea id="transcript" class="form-control transcript-area" rows="16" spellcheck="true" placeholder="Здесь появится распознанный текст..."></textarea>
|
||||||
|
<div class="form-text">Текст можно исправить перед копированием или экспортом.</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<footer class="mt-5 pt-3 border-top border-secondary-subtle d-flex justify-content-between text-secondary small"><span>AI Station Portal v0.8</span><span>Обработка выполняется локально</span></footer>
|
||||||
|
</main>
|
||||||
|
<script>
|
||||||
|
const form = document.getElementById('transcribe-form');
|
||||||
|
const fileInput = document.getElementById('audio-file');
|
||||||
|
const fileName = document.getElementById('file-name');
|
||||||
|
const submitButton = document.getElementById('submit-button');
|
||||||
|
const progress = document.getElementById('progress');
|
||||||
|
const errorBox = document.getElementById('error');
|
||||||
|
const resultSection = document.getElementById('result-section');
|
||||||
|
const transcript = document.getElementById('transcript');
|
||||||
|
let lastSegments = [];
|
||||||
|
|
||||||
|
fileInput.addEventListener('change', () => { fileName.textContent = fileInput.files[0]?.name || 'Файл не выбран'; });
|
||||||
|
const uploadArea = document.querySelector('.upload-area');
|
||||||
|
uploadArea.addEventListener('dragover', e => { e.preventDefault(); uploadArea.classList.add('drag-over'); });
|
||||||
|
uploadArea.addEventListener('dragleave', () => uploadArea.classList.remove('drag-over'));
|
||||||
|
uploadArea.addEventListener('drop', e => { e.preventDefault(); uploadArea.classList.remove('drag-over'); if (e.dataTransfer.files.length) { fileInput.files = e.dataTransfer.files; fileName.textContent = fileInput.files[0].name; } });
|
||||||
|
|
||||||
|
form.addEventListener('submit', async e => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!fileInput.files.length) return;
|
||||||
|
errorBox.classList.add('d-none'); resultSection.classList.add('d-none'); progress.classList.remove('d-none');
|
||||||
|
submitButton.disabled = true;
|
||||||
|
document.getElementById('progress-label').textContent = 'Файл отправлен. Выполняется распознавание...';
|
||||||
|
const body = new FormData(); body.append('file', fileInput.files[0]); body.append('language', document.getElementById('language').value);
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/transcribe', {method:'POST', body});
|
||||||
|
const data = await response.json();
|
||||||
|
if (!response.ok) throw new Error(data.detail || `Ошибка HTTP ${response.status}`);
|
||||||
|
transcript.value = data.text || '';
|
||||||
|
lastSegments = data.segments || [];
|
||||||
|
const meta = [];
|
||||||
|
if (data.language) meta.push(`Язык: ${data.language}`);
|
||||||
|
if (Number.isFinite(data.duration)) meta.push(`Длительность: ${Math.round(data.duration)} сек.`);
|
||||||
|
document.getElementById('result-meta').textContent = meta.join(' · ');
|
||||||
|
resultSection.classList.remove('d-none');
|
||||||
|
resultSection.scrollIntoView({behavior:'smooth', block:'start'});
|
||||||
|
} catch (err) { errorBox.textContent = err.message; errorBox.classList.remove('d-none'); }
|
||||||
|
finally { progress.classList.add('d-none'); submitButton.disabled = false; }
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('copy-button').addEventListener('click', async () => { await navigator.clipboard.writeText(transcript.value); });
|
||||||
|
function download(name, content, type) { const blob = new Blob([content], {type}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download=name; a.click(); URL.revokeObjectURL(url); }
|
||||||
|
document.getElementById('txt-button').addEventListener('click', () => download('transcript.txt', transcript.value, 'text/plain;charset=utf-8'));
|
||||||
|
function stamp(seconds) { const ms=Math.round(seconds*1000); const h=String(Math.floor(ms/3600000)).padStart(2,'0'); const m=String(Math.floor(ms%3600000/60000)).padStart(2,'0'); const s=String(Math.floor(ms%60000/1000)).padStart(2,'0'); const milli=String(ms%1000).padStart(3,'0'); return `${h}:${m}:${s},${milli}`; }
|
||||||
|
document.getElementById('srt-button').addEventListener('click', () => { const srt=lastSegments.map((x,i)=>`${i+1}\n${stamp(x.start||0)} --> ${stamp(x.end||x.start||0)}\n${x.text||''}`).join('\n\n'); if (!srt) { errorBox.textContent='Speaches не вернул сегменты с таймкодами. Доступен экспорт TXT и DOCX.'; errorBox.classList.remove('d-none'); return; } download('transcript.srt', srt, 'text/plain;charset=utf-8'); });
|
||||||
|
document.getElementById('docx-button').addEventListener('click', async () => { try { const response = await fetch('/api/export/docx', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({text:transcript.value})}); if (!response.ok) { const data=await response.json(); throw new Error(data.detail || 'Ошибка экспорта DOCX'); } const blob=await response.blob(); const url=URL.createObjectURL(blob); const a=document.createElement('a'); a.href=url; a.download='transcript.docx'; a.click(); URL.revokeObjectURL(url); } catch(err) { errorBox.textContent=err.message; errorBox.classList.remove('d-none'); } });
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in New Issue
Block a user