-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathweb_server.py
More file actions
2517 lines (2221 loc) · 102 KB
/
Copy pathweb_server.py
File metadata and controls
2517 lines (2221 loc) · 102 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
web_server.py — Servidor HTTP embarcado para configuração e chat de voz via UI web.
Rota Método Descrição
/ GET Serve web/index.html
/api/config GET Retorna a config atual como JSON
/api/config POST Salva nova config; aplica mudanças ao bot em tempo real
/api/bot/info GET Retorna identidade e link oficial de convite do bot
/api/discord/token GET/POST Consulta o estado ou substitui o token no .env
/api/modelo/runtime GET/POST Consulta, liga ou desliga o modelo LLM local
/api/guilds GET Lista guilds do bot
/api/guilds/remover POST Remove o bot de uma guild
/api/voz/canais GET Lista canais de voz de uma guild
/api/voz/conectar POST Conecta bot a um canal de voz
/api/voz/desconectar POST Desconecta bot do canal de voz
/api/voz/chat POST Recebe WAV, transcreve, gera resposta LLM, fala no Discord
/api/voz/interromper POST Cancela imediatamente a fala atual sem desconectar
/api/voz/falar POST Recebe texto, gera TTS e fala no Discord
/api/voz/monitor GET Retorna estado do monitor local do canal
/api/voz/monitor POST Inicia, configura ou encerra o monitor local
/api/voz/config GET Retorna config de voz
/api/voz/config POST Salva config de voz
/api/voz/referencia POST Substitui o WAV usado para clonar a voz
/api/voz/limpar POST Limpa histórico do chat de voz
/api/transcricao GET Retorna o estado da geração de legendas SRT
/api/transcricao/iniciar POST Inicia transcrição do canal em modo separado
/api/transcricao/parar POST Finaliza os buffers e salva o arquivo SRT
Inicie com: start(bot, host="127.0.0.1", port=5000)
"""
import asyncio
import base64
import hashlib
import io
import json
import logging
import os
import re
import shutil
import subprocess
import tempfile
import threading
import time
import wave
from concurrent.futures import CancelledError, Future, ThreadPoolExecutor, TimeoutError as FutureTimeoutError
from collections import deque
from collections.abc import Awaitable, Callable
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from dotenv import dotenv_values, set_key
import config
log = logging.getLogger("web_server")
_WEB_DIR = Path(__file__).parent / "web"
_ENV_PATH = Path(__file__).parent / ".env"
_SHUTDOWN_FLAG = Path(__file__).parent / "logs" / "ui_shutdown.flag"
_VOICE_REFERENCE_PATH = Path(__file__).parent / "data" / "voz_referencia.wav"
_VOICE_REFERENCE_BACKUP_DIR = Path(__file__).parent / "data" / "voz_referencias"
_MAX_VOICE_REFERENCE_BYTES = 32 * 1024 * 1024
_VOICE_CONNECT_ATTEMPTS = 2
_VOICE_CONNECT_TIMEOUT = 12.0
_VOICE_CONNECT_RETRY_DELAY = 0.8
_bot_ref = None # discord.ext.commands.Bot
_loop_ref = None # asyncio event loop do bot
_voz_connect_locks: dict[int, asyncio.Lock] = {}
_voz_connect_tasks: dict[int, asyncio.Task] = {}
_guilds_removidas_ui: set[int] = set()
_tts_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="voz-tts")
_TTS_STARTUP_ESTIMATE_MS = 1800
_tts_state_lock = threading.Lock()
_tts_session_id = 0
_tts_futures: set[Future] = set()
_shutdown_solicitado = threading.Event()
_http_server: ThreadingHTTPServer | None = None
_server_lock = threading.Lock()
_voice_reference_lock = threading.Lock()
_discord_token_lock = threading.Lock()
_discord_token_activator: Callable[[str], Awaitable[bool]] | None = None
# ── Histórico do chat de voz (via web) ────────────────────────────────────────
_voz_historico: deque = deque(maxlen=4)
_voz_lock = threading.Lock()
# ── Push-to-Talk global (funciona fora do navegador) ─────────────────────────
_ptt_global_pressionado = False
def _validar_discord_token(valor: object) -> str:
token = str(valor or "").strip()
if token.lower().startswith(("bot ", "bearer ")):
raise ValueError("Cole somente o token, sem o prefixo Bot ou Bearer.")
if token in {"", "SEU_TOKEN_AQUI", "SEU_TOKEN_REAL"}:
raise ValueError("Informe um token do Discord válido.")
if len(token) < 30 or len(token) > 256 or re.fullmatch(r"[A-Za-z0-9._-]+", token) is None:
raise ValueError("O token informado não possui um formato válido.")
return token
def _obter_discord_token(env_path: Path | None = None) -> str:
path = env_path or _ENV_PATH
try:
with _discord_token_lock:
token = str(dotenv_values(path).get("DISCORD_TOKEN", "") or "").strip()
return _validar_discord_token(token)
except (OSError, ValueError):
return ""
def _discord_token_configurado(env_path: Path | None = None) -> bool:
return bool(_obter_discord_token(env_path))
def _salvar_discord_token(valor: object, env_path: Path | None = None) -> bool:
token = _validar_discord_token(valor)
path = env_path or _ENV_PATH
with _discord_token_lock:
path.parent.mkdir(parents=True, exist_ok=True)
path.touch(exist_ok=True)
sucesso, _, _ = set_key(
path,
"DISCORD_TOKEN",
token,
quote_mode="always",
encoding="utf-8",
)
if sucesso is not True:
raise OSError("Não foi possível atualizar o arquivo .env.")
salvo = str(dotenv_values(path).get("DISCORD_TOKEN", "") or "")
if salvo != token:
raise OSError("Não foi possível confirmar o token salvo.")
return token != str(config.DISCORD_TOKEN or "")
def _validar_wav_referencia(dados: bytes) -> dict:
"""Valida o WAV antes de substituir a referencia ativa."""
import numpy as np
import soundfile as sf
if not dados:
raise ValueError("O arquivo WAV está vazio.")
if len(dados) > _MAX_VOICE_REFERENCE_BYTES:
raise ValueError("O arquivo WAV deve ter no máximo 32 MB.")
try:
buffer = io.BytesIO(dados)
info = sf.info(buffer)
buffer.seek(0)
audio, sample_rate = sf.read(buffer, dtype="float32", always_2d=True)
except Exception as exc:
raise ValueError("O arquivo enviado não é um WAV de áudio válido.") from exc
if not str(info.format).upper().startswith("WAV"):
raise ValueError("O arquivo precisa estar no formato WAV.")
if info.channels not in (1, 2):
raise ValueError("Use um WAV mono ou estéreo.")
if sample_rate < 8000 or sample_rate > 192000:
raise ValueError("A taxa de amostragem do WAV não é compatível.")
duracao = float(info.frames) / float(sample_rate)
if duracao < 1.0:
raise ValueError("A referência precisa ter pelo menos 1 segundo de voz.")
if duracao > 120.0:
raise ValueError("A referência deve ter no máximo 2 minutos.")
if audio.size == 0 or not np.isfinite(audio).all():
raise ValueError("O WAV não contém áudio utilizável.")
mono = audio.mean(axis=1)
pico = float(np.max(np.abs(mono)))
rms = float(np.sqrt(np.mean(np.square(mono, dtype=np.float64))))
if pico < 1e-4 or rms < 1e-5:
raise ValueError("O WAV está vazio ou silencioso demais para clonar a voz.")
return {
"duracao_s": round(duracao, 3),
"sample_rate": int(sample_rate),
"canais": int(info.channels),
"tamanho": len(dados),
"sha256": hashlib.sha256(dados).hexdigest(),
}
def _salvar_wav_referencia(dados: bytes) -> dict:
"""Salva a referencia de forma atomica e preserva a versao anterior."""
meta = _validar_wav_referencia(dados)
destino = _VOICE_REFERENCE_PATH
backup = None
with _voice_reference_lock:
destino.parent.mkdir(parents=True, exist_ok=True)
if destino.exists():
hash_atual = hashlib.sha256(destino.read_bytes()).hexdigest()
if hash_atual == meta["sha256"]:
return {**meta, "alterado": False, "backup": None}
_VOICE_REFERENCE_BACKUP_DIR.mkdir(parents=True, exist_ok=True)
carimbo = time.strftime("%Y%m%d-%H%M%S")
backup = _VOICE_REFERENCE_BACKUP_DIR / f"voz_referencia-{carimbo}-{hash_atual[:8]}.wav"
if backup.exists():
backup = _VOICE_REFERENCE_BACKUP_DIR / (
f"voz_referencia-{carimbo}-{hash_atual[:8]}-{time.time_ns()}.wav"
)
shutil.copy2(destino, backup)
fd, temporario_nome = tempfile.mkstemp(
prefix=".voz_referencia-",
suffix=".tmp",
dir=destino.parent,
)
temporario = Path(temporario_nome)
try:
with os.fdopen(fd, "wb") as arquivo:
arquivo.write(dados)
arquivo.flush()
os.fsync(arquivo.fileno())
os.replace(temporario, destino)
finally:
temporario.unlink(missing_ok=True)
backup_relativo = None
if backup is not None:
try:
backup_relativo = backup.relative_to(Path(__file__).parent).as_posix()
except ValueError:
backup_relativo = backup.as_posix()
return {**meta, "alterado": True, "backup": backup_relativo}
def _caminhos_llama_locais(cliente=None) -> set[Path]:
"""Retorna somente executaveis llama-server pertencentes a esta instalacao."""
caminhos = {
Path(config.LLAMA_CPP_SERVER_EXE).resolve(),
(Path(__file__).parent / "temp_llama" / "llama" / "llama-server.exe").resolve(),
}
processo = getattr(cliente, "process", None)
argumentos = getattr(processo, "args", None)
if isinstance(argumentos, (list, tuple)) and argumentos:
caminhos.add(Path(str(argumentos[0])).resolve())
return caminhos
def _encerrar_llama_server() -> None:
"""Encerra o cliente ativo e remove processos locais orfaos do llama-server."""
cliente = None
try:
cog = _bot_ref.get_cog("LLM") if _bot_ref is not None else None
cliente = getattr(cog, "llm", None)
if cog is not None and hasattr(cog, "desligar_modelo"):
cog.desligar_modelo()
elif cliente is not None:
cliente.close()
except Exception:
log.exception("Falha ao encerrar o llama-server pelo cliente da LLM.")
if os.name != "nt":
return
caminhos = [str(caminho) for caminho in _caminhos_llama_locais(cliente) if caminho.is_file()]
if not caminhos:
return
alvos = ",".join("'" + caminho.replace("'", "''") + "'" for caminho in caminhos)
script = (
f"$targets=@({alvos});"
"$stopped=@();"
"Get-CimInstance Win32_Process -Filter \"Name = 'llama-server.exe'\" | "
"Where-Object { $_.ExecutablePath -and "
"($targets -contains [IO.Path]::GetFullPath($_.ExecutablePath)) } | "
"ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue; "
"$stopped += $_.ProcessId };"
"$stopped -join ','"
)
try:
resultado = subprocess.run(
["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", script],
capture_output=True,
text=True,
timeout=8,
check=False,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
)
pids = resultado.stdout.strip()
if pids:
log.info("Processos llama-server locais encerrados: %s", pids)
elif resultado.returncode != 0:
log.warning("Limpeza do llama-server retornou codigo %s.", resultado.returncode)
except Exception:
log.exception("Falha na limpeza residual do llama-server local.")
def _finalizar_desligamento() -> None:
try:
try:
from services.discord_transcription import get_transcription_service
get_transcription_service().stop(wait=True, timeout=20, reason="desligamento")
except Exception:
log.exception("Falha ao finalizar a transcricao SRT.")
try:
from services.local_transcription import get_local_transcription_service
get_local_transcription_service().stop(wait=True, timeout=20, reason="desligamento")
except Exception:
log.exception("Falha ao finalizar a transcricao local.")
try:
from services.discord_audio_monitor import obter_monitor
obter_monitor().parar()
except Exception:
log.exception("Falha ao encerrar o monitor local de voz.")
try:
from services import tts_manager
tts_manager.desligar()
except Exception:
log.exception("Falha ao encerrar o backend TTS.")
_encerrar_llama_server()
if _bot_ref is not None and _loop_ref is not None and _loop_ref.is_running():
try:
future = asyncio.run_coroutine_threadsafe(_bot_ref.close(), _loop_ref)
future.result(timeout=8)
except Exception:
log.exception("Falha ao encerrar a conexao do Discord durante o desligamento.")
finally:
os._exit(0)
def solicitar_desligamento(atraso: float = 0.8) -> None:
"""Registra o desligamento da UI e encerra todo o processo apos a resposta HTTP."""
if _shutdown_solicitado.is_set():
return
_shutdown_solicitado.set()
try:
_SHUTDOWN_FLAG.parent.mkdir(parents=True, exist_ok=True)
_SHUTDOWN_FLAG.write_text("shutdown via web ui\n", encoding="utf-8")
except Exception:
log.exception("Falha ao registrar flag de desligamento da UI.")
timer = threading.Timer(max(0.0, atraso), _finalizar_desligamento)
timer.daemon = True
timer.start()
def registrar_guild_adicionada(guild_id: int) -> None:
"""Torna uma guild recém-adicionada visível novamente na interface."""
_guilds_removidas_ui.discard(int(guild_id))
log.info("[WEB] Servidor adicionado ou reativado na interface: %s", guild_id)
def _voz_connect_lock(guild_id: int) -> asyncio.Lock:
lock = _voz_connect_locks.get(guild_id)
if lock is None:
lock = asyncio.Lock()
_voz_connect_locks[guild_id] = lock
return lock
async def _cancelar_tentativa_conexao_voz(guild_id: int, motivo: str = "") -> None:
task = _voz_connect_tasks.get(guild_id)
if task is None or task.done() or task is asyncio.current_task():
return
log.warning(
"[WEB] Cancelando tentativa de conexão de voz%s na guild %s.",
f" ({motivo})" if motivo else "",
guild_id,
)
task.cancel()
try:
await asyncio.wait_for(asyncio.shield(task), timeout=3)
except asyncio.CancelledError:
pass
except Exception:
pass
async def _limpar_conexao_voz(guild_id: int, motivo: str = "") -> dict:
"""Força a remoção do VoiceClient, inclusive quando handshake fica preso."""
if _bot_ref is None:
raise RuntimeError("Bot indisponivel")
guild = _bot_ref.get_guild(guild_id)
if not guild:
raise ValueError("Guild não encontrada")
try:
from services.discord_transcription import get_transcription_service
get_transcription_service().stop_for_guild(guild_id, wait=False)
except Exception as exc:
log.warning("[WEB] Falha ao finalizar transcricao da guild %s: %s", guild.name, exc)
try:
from services.discord_audio_monitor import obter_monitor
obter_monitor().parar_se_guild(guild_id)
except Exception as exc:
log.warning("[WEB] Falha ao encerrar monitor de voz da guild %s: %s", guild.name, exc)
vc = guild.voice_client
if vc is None:
member_voice = getattr(getattr(guild, "me", None), "voice", None)
stale_channel = getattr(member_voice, "channel", None)
if stale_channel is not None:
log.warning(
"[WEB] Limpando estado remoto de voz sem VoiceClient: guild=%s canal=%s",
guild.name,
getattr(stale_channel, "name", "?"),
)
try:
await asyncio.wait_for(guild.change_voice_state(channel=None), timeout=5)
await asyncio.sleep(0.35)
except Exception as exc:
log.warning(
"[WEB] Falha ao limpar estado remoto da guild %s: %s",
guild.name,
exc,
)
return {"ok": True, "status": "sem_conexao"}
canal = getattr(getattr(vc, "channel", None), "name", None)
log.warning(
"[WEB] Limpando conexao de voz%s: guild=%s canal=%s conectado=%s",
f" ({motivo})" if motivo else "",
guild.name,
canal,
vc.is_connected(),
)
try:
if vc.is_playing():
vc.stop()
except Exception:
pass
try:
await asyncio.wait_for(vc.disconnect(force=True), timeout=8)
except Exception as exc:
log.warning("[WEB] Falha ao limpar VoiceClient da guild %s: %s", guild.name, exc)
try:
if guild.voice_client is vc:
vc.cleanup()
except Exception as exc:
log.warning("[WEB] Falha ao executar cleanup() do VoiceClient da guild %s: %s", guild.name, exc)
try:
if guild.voice_client is not None:
_bot_ref._connection._remove_voice_client(guild_id)
except Exception as exc:
log.warning("[WEB] Falha ao remover VoiceClient do cache da guild %s: %s", guild.name, exc)
await asyncio.sleep(0.35)
return {"ok": True, "status": "removido", "canal": canal}
async def _abrir_conexao_voz(channel, guild_id: int):
"""Conecta com uma repeticao controlada quando o handshake UDP expira."""
from discord.ext import voice_recv
from services.discord_voice_receive import aplicar_compatibilidade_voice_recv
aplicar_compatibilidade_voice_recv()
for tentativa in range(1, _VOICE_CONNECT_ATTEMPTS + 1):
try:
return await asyncio.wait_for(
channel.connect(
timeout=_VOICE_CONNECT_TIMEOUT,
reconnect=True,
cls=voice_recv.VoiceRecvClient,
),
timeout=_VOICE_CONNECT_TIMEOUT + 3,
)
except asyncio.CancelledError:
raise
except Exception as exc:
if tentativa >= _VOICE_CONNECT_ATTEMPTS:
raise
log.warning(
"[WEB] Handshake de voz falhou (%s/%s, %s); repetindo uma vez.",
tentativa,
_VOICE_CONNECT_ATTEMPTS,
type(exc).__name__,
)
await _limpar_conexao_voz(guild_id, f"nova tentativa {tentativa}")
await asyncio.sleep(_VOICE_CONNECT_RETRY_DELAY)
async def garantir_conexao_voz_para_reproducao(guild_id: int):
"""Recupera automaticamente uma conexao cujo WebSocket interno morreu."""
if _bot_ref is None:
raise RuntimeError("Bot indisponivel")
guild = _bot_ref.get_guild(guild_id)
if guild is None:
raise ValueError("Guild nao encontrada")
from services.discord_voice_receive import conexao_voz_saudavel, erro_conexao_voz
vc = guild.voice_client
if conexao_voz_saudavel(vc):
return vc
async with _voz_connect_lock(guild_id):
vc = guild.voice_client
if conexao_voz_saudavel(vc):
return vc
channel = getattr(vc, "channel", None)
if channel is None:
member_voice = getattr(getattr(guild, "me", None), "voice", None)
channel = getattr(member_voice, "channel", None)
if channel is None:
raise ValueError("Bot nao esta conectado a um canal de voz nesta guild")
falha = erro_conexao_voz(vc)
log.warning(
"[WEB] Conexao de voz sem poller ativo; recuperando antes do audio: "
"guild=%s canal=%s erro=%r",
guild.name,
getattr(channel, "name", "?"),
falha,
)
await _limpar_conexao_voz(guild_id, "poller de voz inativo")
novo_vc = await _abrir_conexao_voz(channel, guild_id)
await asyncio.sleep(0)
if not conexao_voz_saudavel(novo_vc):
await _limpar_conexao_voz(guild_id, "reconexao sem poller ativo")
raise RuntimeError("A conexao de voz foi recriada, mas nao ficou operacional.")
log.info("[WEB] Conexao de voz recuperada automaticamente para reproducao.")
return novo_vc
def _agendar_reproducao_pcm(
guild_id: int,
pcm: bytes,
origem: str = "",
*,
interromper: bool = False,
sessao: int | None = None,
) -> bool:
"""Agenda reproducao no Discord sem bloquear a resposta HTTP."""
if _loop_ref is None or _bot_ref is None:
log.warning("[WEB] Nao foi possivel agendar audio%s: bot/loop indisponivel.", origem)
return False
try:
from cogs.voice_cog import reproduzir_pcm
agendado_em = time.perf_counter()
future = asyncio.run_coroutine_threadsafe(
reproduzir_pcm(
_bot_ref,
guild_id,
pcm,
interromper=interromper,
sessao=sessao,
agendado_em=agendado_em,
),
_loop_ref,
)
def _registrar_resultado(fut) -> None:
try:
fut.result()
except Exception as exc:
log.error("[WEB] ERRO ao reproduzir TTS%s: %s", origem, exc, exc_info=True)
else:
log.info("[WEB] Reproducao no Discord concluida%s.", origem)
future.add_done_callback(_registrar_resultado)
return True
except Exception as exc:
log.error("[WEB] ERRO ao agendar TTS%s: %s", origem, exc, exc_info=True)
return False
def _iniciar_sessao_tts(origem: str, guild_id: int | None = None) -> int:
global _tts_session_id
cancelados = 0
with _tts_state_lock:
_tts_session_id += 1
sessao = _tts_session_id
for futuro in list(_tts_futures):
if futuro.done():
_tts_futures.discard(futuro)
elif futuro.cancel():
cancelados += 1
_tts_futures.discard(futuro)
log.info("[WEB] Nova sessao TTS %d%s; chunks pendentes cancelados=%d", sessao, f" {origem}" if origem else "", cancelados)
if guild_id and _loop_ref is not None and _bot_ref is not None:
try:
from cogs.voice_cog import iniciar_sessao_reproducao
asyncio.run_coroutine_threadsafe(
iniciar_sessao_reproducao(_bot_ref, guild_id, sessao),
_loop_ref,
)
except Exception as exc:
log.warning("[WEB] Falha ao iniciar sessao de reproducao %d: %s", sessao, exc)
return sessao
def _sessao_tts_atual(sessao: int) -> bool:
with _tts_state_lock:
return sessao == _tts_session_id
def _duracao_pcm_ms(pcm: bytes) -> int:
# PCM bruto do Discord: 48 kHz, stereo, 16-bit = 192000 bytes/s.
return max(0, int((len(pcm) / 192000) * 1000))
def _destino_chat(valor: object) -> str:
destino = str(valor or "discord").strip().casefold()
if destino not in {"discord", "local"}:
raise ValueError("Destino de audio invalido.")
return destino
def _pcm_para_wav_base64(pcm: bytes) -> str:
buffer = io.BytesIO()
with wave.open(buffer, "wb") as wav:
wav.setnchannels(2)
wav.setsampwidth(2)
wav.setframerate(48_000)
wav.writeframes(pcm)
return base64.b64encode(buffer.getvalue()).decode("ascii")
def _corrigir_mojibake(texto: str) -> str:
if not texto or not any(marcador in texto for marcador in ("Ã", "Â", "â€", "“", "’")):
return texto
try:
return texto.encode("latin1").decode("utf-8")
except UnicodeError:
reparos = {
"á": "á", "à ": "à", "â": "â", "ã": "ã", "é": "é", "ê": "ê",
"Ã": "í", "ó": "ó", "ô": "ô", "õ": "õ", "ú": "ú", "ç": "ç",
"Ã": "Á", "À": "À", "Â": "Â", "Ã": "Ã", "É": "É", "Ê": "Ê",
"Ã": "Í", "Ó": "Ó", "Ô": "Ô", "Õ": "Õ", "Ú": "Ú", "Ç": "Ç",
"¿": "¿", "¡": "¡", "º": "º", "ª": "ª",
"–": "-", "—": "-", "…": "...", "“": '"', "â€": '"',
"‘": "'", "’": "'",
}
for errado, certo in reparos.items():
texto = texto.replace(errado, certo)
return texto
# ── Aplicação de mudanças ao bot em tempo real ────────────────────────────────
async def _aplicar_mudancas(nova_config: dict, config_antiga: dict) -> None:
"""Aplica prefix e renomes de comandos ao bot sem reiniciar."""
bot = _bot_ref
if bot is None:
return
# 1. Prefixo
novo_prefix = nova_config.get("prefix", "!")
if bot.command_prefix != novo_prefix:
bot.command_prefix = novo_prefix
log.info("Prefixo atualizado: '%s'", novo_prefix)
# 2. Nomes de comandos
# Garante que cfg._data está em sincronia (já foi salvo antes desta chamada)
cmds_novos = nova_config.get("commands", {})
cmds_antigos = config_antiga.get("commands", {})
for cmd_key, cmd_data in cmds_novos.items():
novo_nome = cmd_data.get("name", cmd_key)
nome_atual = cmds_antigos.get(cmd_key, {}).get("name", cmd_key)
if novo_nome != nome_atual:
# Tenta pelo nome atual salvo; fallback: pelo nome original do decorador (cmd_key)
cmd = bot.get_command(nome_atual) or bot.get_command(cmd_key)
if cmd is not None:
bot.remove_command(cmd.name)
cmd.name = novo_nome
bot.add_command(cmd)
log.info("Comando renomeado ao vivo: '%s' → '%s'", nome_atual, novo_nome)
else:
log.warning("Comando não encontrado para renomear: key='%s' nome_atual='%s'",
cmd_key, nome_atual)
# ── Handler HTTP ──────────────────────────────────────────────────────────────
class _Handler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args): # silencia log padrão do http.server
log.debug("HTTP %s %s", self.command, self.path)
def do_OPTIONS(self): # suporte a CORS preflight do navegador
self.send_response(204)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
self.send_header(
"Access-Control-Allow-Headers",
"Content-Type, X-File-Name, X-Session-Id, X-Sample-Rate, X-Capture-Start-Ms",
)
self.end_headers()
# ── GET ───────────────────────────────────────────────────────────────────
def do_GET(self):
if self.path in ("/", "/index.html"):
self._serve_file(_WEB_DIR / "index.html", "text/html; charset=utf-8")
elif self.path == "/app.css":
self._serve_file(_WEB_DIR / "app.css", "text/css; charset=utf-8")
elif self.path == "/logo.png":
self._serve_file(_WEB_DIR / "logo.png", "image/png")
elif self.path == "/api/config":
from config_loader import cfg
data = cfg.as_dict()
data["llm"] = config.exportar_config_llm()
modelos = sorted({
str(path.resolve())
for pasta in (config.MODELS_TEXTO_DIR, config.MODELS_DIR)
for path in pasta.glob("*.gguf")
})
atual = str(Path(config.LLM_MODEL_PATH).resolve())
if atual not in modelos:
modelos.insert(0, atual)
data["_llm_models"] = [
{"value": caminho, "label": Path(caminho).name}
for caminho in modelos
]
try:
from cogs.llm_cog import prompt_defaults
data["_prompt_defaults"] = prompt_defaults()
except Exception as exc:
log.warning("Falha ao anexar prompts padrao na config: %s", exc)
data["_prompt_defaults"] = {}
payload = json.dumps(data, ensure_ascii=False, indent=2).encode("utf-8")
self._respond(200, "application/json", payload)
elif self.path == "/api/bot/info":
info = {"id": None, "name": None, "invite_url": None, "ready": False}
if _bot_ref is not None and _bot_ref.user is not None:
import discord as _discord
permissoes = _discord.Permissions.none()
permissoes.view_channel = True
permissoes.send_messages = True
permissoes.read_message_history = True
permissoes.add_reactions = True
permissoes.connect = True
permissoes.speak = True
permissoes.use_voice_activation = True
info = {
"id": str(_bot_ref.user.id),
"name": _bot_ref.user.name,
"ready": _bot_ref.is_ready(),
"invite_url": _discord.utils.oauth_url(
_bot_ref.user.id,
permissions=permissoes,
scopes=("bot", "applications.commands"),
),
}
self._respond(
200,
"application/json",
json.dumps(info, ensure_ascii=False).encode("utf-8"),
)
elif self.path == "/api/discord/token":
token = _obter_discord_token()
self._respond(
200,
"application/json",
json.dumps({"ok": True, "configurado": bool(token), "token": token}).encode("utf-8"),
allow_cors=False,
no_store=True,
)
elif self.path == "/api/modelo/runtime":
self._handle_get_modelo_runtime()
elif self.path.startswith("/api/voz/canais"):
self._handle_get_voz_canais()
elif self.path.startswith("/api/texto/canais"):
self._handle_get_texto_canais()
elif self.path.startswith("/api/voz/monitor"):
self._handle_get_voz_monitor()
elif self.path == "/api/transcricao":
self._handle_get_transcricao()
elif self.path == "/api/transcricao/local":
self._handle_get_transcricao(local=True)
elif self.path == "/api/voz/config":
self._handle_get_voz_config()
elif self.path == "/api/voz/ptt-estado":
payload = json.dumps({"pressionado": _ptt_global_pressionado}).encode("utf-8")
self._respond(200, "application/json", payload)
elif self.path == "/api/guilds":
# Retorna lista de servidores onde o bot está instalado.
guilds = []
if _bot_ref:
for g in _bot_ref.guilds:
if g.id in _guilds_removidas_ui:
continue
vc = g.voice_client
em_voz = vc is not None and vc.is_connected()
conectando = vc is not None and not vc.is_connected()
canal = getattr(vc, "channel", None) if vc else None
guilds.append({
"id": str(g.id),
"name": g.name,
"em_voz": em_voz,
"conectando": conectando,
"canal_voz": canal.name if canal and em_voz else None,
"canal_id": str(canal.id) if canal and em_voz else None,
})
self._respond(200, "application/json",
json.dumps(guilds, ensure_ascii=False).encode("utf-8"))
else:
self._respond(404, "text/plain", b"Not found")
# ── POST ──────────────────────────────────────────────────────────────────
def do_POST(self):
log.info("[WEB] POST %s", self.path)
if self.path == "/api/shutdown":
self._respond(200, "application/json", b'{"ok": true}')
log.info("Desligamento solicitado via UI web.")
solicitar_desligamento()
return
if self.path == "/api/modelo/runtime":
self._handle_post_modelo_runtime()
return
if self.path == "/api/voz/conectar":
self._handle_voz_conectar()
return
if self.path == "/api/voz/desconectar":
self._handle_voz_desconectar()
return
if self.path == "/api/guilds/remover":
self._handle_guild_remover()
return
if self.path == "/api/discord/token":
self._handle_post_discord_token()
return
if self.path == "/api/voz/chat":
self._handle_voz_chat()
return
if self.path == "/api/voz/interromper":
self._handle_voz_interromper()
return
if self.path == "/api/voz/falar":
self._handle_voz_falar()
return
if self.path == "/api/voz/testar":
self._handle_voz_testar()
return
if self.path == "/api/voz/chat-texto":
self._handle_voz_chat_texto()
return
if self.path == "/api/voz/monitor":
self._handle_post_voz_monitor()
return
if self.path == "/api/transcricao/iniciar":
self._handle_post_transcricao_iniciar()
return
if self.path == "/api/transcricao/parar":
self._handle_post_transcricao_parar()
return
if self.path == "/api/transcricao/abrir-pasta":
self._handle_post_transcricao_abrir_pasta()
return
if self.path == "/api/voz/referencia":
self._handle_post_voz_referencia()
return
if self.path == "/api/voz/config":
self._handle_post_voz_config()
return
if self.path == "/api/voz/limpar":
with _voz_lock:
_voz_historico.clear()
self._respond(200, "application/json", b'{"ok": true}')
return
if self.path == "/api/texto/enviar":
self._handle_texto_enviar()
return
if self.path != "/api/config":
self._respond(404, "text/plain", b"Not found")
return
length = int(self.headers.get("Content-Length", 0))
body = self.rfile.read(length)
try:
nova_config = json.loads(body.decode("utf-8"))
except (json.JSONDecodeError, UnicodeDecodeError) as exc:
self._respond(400, "application/json",
json.dumps({"erro": str(exc)}).encode("utf-8"))
return
from config_loader import cfg
nova_config.pop("_prompt_defaults", None)
nova_config.pop("_llm_models", None)
try:
nova_config["llm"] = config.validar_config_llm(nova_config.get("llm", {}))
except ValueError as exc:
self._respond(
400,
"application/json",
json.dumps({"erro": str(exc)}, ensure_ascii=False).encode("utf-8"),
)
return
config_antiga = cfg.as_dict()
llm_antiga = config.exportar_config_llm()
# Salva a nova config
cfg.save(nova_config)
config.aplicar_config_llm(nova_config["llm"])
log.info("Config salva via UI web.")
parametros_reinicio = {
"model_path", "n_ctx", "n_gpu_layers", "n_batch", "n_ubatch",
"n_threads", "n_threads_batch", "kv_type", "chat_template",
}
reinicio_necessario = any(
llm_antiga.get(chave) != nova_config["llm"].get(chave)
for chave in parametros_reinicio
)
# Aplica ao bot de forma thread-safe (bot roda em event loop asyncio)
if _loop_ref is not None and _bot_ref is not None:
future = asyncio.run_coroutine_threadsafe(
_aplicar_mudancas(nova_config, config_antiga), _loop_ref
)
try:
future.result(timeout=5)
except Exception as exc:
log.warning("Falha ao aplicar mudanças ao bot: %s", exc)
self._respond(
200,
"application/json",
json.dumps({"ok": True, "reinicio_necessario": reinicio_necessario}).encode("utf-8"),
)
# ── Handlers Discord / Voz ─────────────────────────────────────────────────
def _handle_post_discord_token(self) -> None:
origin = str(self.headers.get("Origin", "") or "").strip()
host = str(self.headers.get("Host", "") or "").strip().casefold()
if origin:
from urllib.parse import urlparse
parsed = urlparse(origin)
if parsed.scheme != "http" or parsed.netloc.casefold() != host:
self._respond(403, "application/json", b'{"erro":"Origem nao permitida"}')
return
length = int(self.headers.get("Content-Length", 0) or 0)
if length <= 0 or length > 4096:
self._respond(400, "application/json", b'{"erro":"Requisicao invalida"}')
return
try:
data = json.loads(self.rfile.read(length).decode("utf-8"))
token = _validar_discord_token(data.get("token"))
reinicio_necessario = _salvar_discord_token(token)
except (json.JSONDecodeError, UnicodeDecodeError, ValueError) as exc:
self._respond(
400,
"application/json",
json.dumps({"erro": str(exc)}, ensure_ascii=False).encode("utf-8"),
)
return
except OSError:
log.exception("Falha ao salvar o token do Discord.")
self._respond(500, "application/json", b'{"erro":"Nao foi possivel salvar o token"}')
return
carregamento_iniciado = False
if (
_discord_token_activator is not None
and _loop_ref is not None
and _loop_ref.is_running()
and (_bot_ref is None or not _bot_ref.is_ready())
):
try:
future = asyncio.run_coroutine_threadsafe(
_discord_token_activator(token), _loop_ref
)
carregamento_iniciado = bool(future.result(timeout=5))
except Exception:
log.exception("Falha ao carregar o token salvo no bot em execucao.")
if carregamento_iniciado:
reinicio_necessario = False