vcbot 0.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
vcbot/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Discord voice selfbot with local Whisper streaming transcription."""
2
+
3
+ __version__ = "0.0.2"
vcbot/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Support ``python -m vcbot`` for checkouts that are not installed."""
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())
vcbot/cli.py ADDED
@@ -0,0 +1,22 @@
1
+ """Console entry point for ``vcbot``.
2
+
3
+ Argument handling happens first and the application module is imported after,
4
+ so ``vcbot --help`` and argument errors never pay for the Discord, Opus and
5
+ Whisper imports - and a broken CUDA install cannot stop them from working.
6
+ """
7
+
8
+ from . import config
9
+
10
+
11
+ def main(argv=None):
12
+ """Parse the command line, validate the model choice, then run the bot."""
13
+ parser = config.argument_parser()
14
+ token, config.settings = config.parse_startup(parser, argv)
15
+
16
+ from .main import run
17
+ from .whisper_backend import available_models
18
+
19
+ models = available_models()
20
+ if config.settings.whisper_model not in models:
21
+ parser.error(f"--whisper-model must be one of: {', '.join(models)}")
22
+ return run(token)
vcbot/config.py ADDED
@@ -0,0 +1,319 @@
1
+ """Startup settings for the selfbot."""
2
+
3
+ import argparse
4
+ import math
5
+ import os
6
+ import re
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ from . import __version__
11
+
12
+ DEFAULT_VOICE = "en-us+whisper"
13
+ VOICE_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]*(?:\+[A-Za-z0-9_-]+)?")
14
+ WHISPER_LANGUAGES = {
15
+ "af": "afrikaans",
16
+ "am": "amharic",
17
+ "ar": "arabic",
18
+ "as": "assamese",
19
+ "az": "azerbaijani",
20
+ "ba": "bashkir",
21
+ "be": "belarusian",
22
+ "bg": "bulgarian",
23
+ "bn": "bengali",
24
+ "bo": "tibetan",
25
+ "br": "breton",
26
+ "bs": "bosnian",
27
+ "ca": "catalan",
28
+ "cs": "czech",
29
+ "cy": "welsh",
30
+ "da": "danish",
31
+ "de": "german",
32
+ "el": "greek",
33
+ "en": "english",
34
+ "es": "spanish",
35
+ "et": "estonian",
36
+ "eu": "basque",
37
+ "fa": "persian",
38
+ "fi": "finnish",
39
+ "fo": "faroese",
40
+ "fr": "french",
41
+ "gl": "galician",
42
+ "gu": "gujarati",
43
+ "ha": "hausa",
44
+ "haw": "hawaiian",
45
+ "he": "hebrew",
46
+ "hi": "hindi",
47
+ "hr": "croatian",
48
+ "ht": "haitian creole",
49
+ "hu": "hungarian",
50
+ "hy": "armenian",
51
+ "id": "indonesian",
52
+ "is": "icelandic",
53
+ "it": "italian",
54
+ "ja": "japanese",
55
+ "jw": "javanese",
56
+ "ka": "georgian",
57
+ "kk": "kazakh",
58
+ "km": "khmer",
59
+ "kn": "kannada",
60
+ "ko": "korean",
61
+ "la": "latin",
62
+ "lb": "luxembourgish",
63
+ "ln": "lingala",
64
+ "lo": "lao",
65
+ "lt": "lithuanian",
66
+ "lv": "latvian",
67
+ "mg": "malagasy",
68
+ "mi": "maori",
69
+ "mk": "macedonian",
70
+ "ml": "malayalam",
71
+ "mn": "mongolian",
72
+ "mr": "marathi",
73
+ "ms": "malay",
74
+ "mt": "maltese",
75
+ "my": "myanmar",
76
+ "ne": "nepali",
77
+ "nl": "dutch",
78
+ "nn": "nynorsk",
79
+ "no": "norwegian",
80
+ "oc": "occitan",
81
+ "pa": "punjabi",
82
+ "pl": "polish",
83
+ "ps": "pashto",
84
+ "pt": "portuguese",
85
+ "ro": "romanian",
86
+ "ru": "russian",
87
+ "sa": "sanskrit",
88
+ "sd": "sindhi",
89
+ "si": "sinhala",
90
+ "sk": "slovak",
91
+ "sl": "slovenian",
92
+ "sn": "shona",
93
+ "so": "somali",
94
+ "sq": "albanian",
95
+ "sr": "serbian",
96
+ "su": "sundanese",
97
+ "sv": "swedish",
98
+ "sw": "swahili",
99
+ "ta": "tamil",
100
+ "te": "telugu",
101
+ "tg": "tajik",
102
+ "th": "thai",
103
+ "tk": "turkmen",
104
+ "tl": "tagalog",
105
+ "tr": "turkish",
106
+ "tt": "tatar",
107
+ "uk": "ukrainian",
108
+ "ur": "urdu",
109
+ "uz": "uzbek",
110
+ "vi": "vietnamese",
111
+ "yi": "yidish",
112
+ "yo": "yoruba",
113
+ "yue": "cantonese",
114
+ "zh": "chinese",
115
+ }
116
+ WHISPER_LANGUAGE_ALIASES = {
117
+ **{name: code for code, name in WHISPER_LANGUAGES.items()},
118
+ "burmese": "my",
119
+ "castilian": "es",
120
+ "flemish": "nl",
121
+ "haitian": "ht",
122
+ "letzeburgesch": "lb",
123
+ "mandarin": "zh",
124
+ "moldavian": "ro",
125
+ "moldovan": "ro",
126
+ "panjabi": "pa",
127
+ "pushto": "ps",
128
+ "sinhalese": "si",
129
+ "valencian": "ca",
130
+ "yiddish": "yi",
131
+ }
132
+
133
+
134
+ def normalize_whisper_language(value):
135
+ raw = (value or "").strip().lower()
136
+ if not raw or raw == "auto":
137
+ return "auto"
138
+ base = raw.replace("_", "-").split("-", 1)[0]
139
+ for candidate in (raw, base):
140
+ if candidate in WHISPER_LANGUAGES:
141
+ return candidate
142
+ if candidate in WHISPER_LANGUAGE_ALIASES:
143
+ return WHISPER_LANGUAGE_ALIASES[candidate]
144
+ raise ValueError(
145
+ f"Unknown Whisper language `{value}`. Use `auto` or a Whisper language code like `en`, `es`, `fr`, "
146
+ "`de`, `ja`, or `zh`."
147
+ )
148
+
149
+
150
+ @dataclass(frozen=True)
151
+ class Settings:
152
+ prefix: str = ">"
153
+ reply_delete_after: float = 60
154
+ tts_voice: str = DEFAULT_VOICE
155
+ tts_speed: int | None = None
156
+ tts_pitch: int | None = None
157
+ tts_amplitude: int | None = None
158
+ voice_timeout: float = 20
159
+ recordings_dir: Path | None = None
160
+ whisper_model: str = "large-v3-turbo"
161
+ whisper_language: str = "en"
162
+ whisper_vad: bool = False
163
+ whisper_backend: str = "auto"
164
+ whisper_streams: int | None = None
165
+ whisper_workers: int | None = None
166
+ whisper_vram_percent: int = 75
167
+ whisper_chunk_seconds: int = 2
168
+ whisper_pause_seconds: float = 1
169
+ debug: bool = False
170
+
171
+
172
+ settings = Settings()
173
+
174
+
175
+ def worker_count():
176
+ """Default to the logical CPUs available to this process, capped at 32."""
177
+ if settings.whisper_workers is not None:
178
+ return settings.whisper_workers
179
+ if hasattr(os, "process_cpu_count"):
180
+ count = os.process_cpu_count()
181
+ elif hasattr(os, "sched_getaffinity"):
182
+ count = len(os.sched_getaffinity(0))
183
+ else:
184
+ count = os.cpu_count()
185
+ return min(32, count or 1)
186
+
187
+
188
+ def _positive_int(value):
189
+ number = int(value)
190
+ if number < 1:
191
+ raise argparse.ArgumentTypeError("must be a positive whole number")
192
+ return number
193
+
194
+
195
+ def _positive_seconds(value):
196
+ seconds = float(value)
197
+ if not math.isfinite(seconds) or seconds <= 0:
198
+ raise argparse.ArgumentTypeError("must be a finite number greater than zero")
199
+ return seconds
200
+
201
+
202
+ def _bounded_int(minimum, maximum):
203
+ def parse(value):
204
+ number = int(value)
205
+ if not minimum <= number <= maximum:
206
+ raise argparse.ArgumentTypeError(f"must be a whole number from {minimum} to {maximum}")
207
+ return number
208
+ return parse
209
+
210
+
211
+ def _backend(value):
212
+ value = value.strip().lower()
213
+ if value not in ("auto", "cpu", "cuda"):
214
+ raise argparse.ArgumentTypeError("must be auto, cpu, or cuda")
215
+ return value
216
+
217
+
218
+ def _prefix(value):
219
+ if not value or not value.isprintable() or any(char.isspace() for char in value):
220
+ raise argparse.ArgumentTypeError("must be nonempty and contain no whitespace or control characters")
221
+ return value
222
+
223
+
224
+ def _voice(value):
225
+ if not VOICE_PATTERN.fullmatch(value):
226
+ raise argparse.ArgumentTypeError("must be an eSpeak voice name, optionally with +variant")
227
+ return value
228
+
229
+
230
+ def _whisper_language(value):
231
+ try:
232
+ return normalize_whisper_language(value)
233
+ except ValueError as error:
234
+ raise argparse.ArgumentTypeError(str(error)) from error
235
+
236
+
237
+ def argument_parser():
238
+ parser = argparse.ArgumentParser(
239
+ prog="vcbot",
240
+ description="Discord voice playback and local WhisperStreaming transcription.",
241
+ epilog="Command-line options override environment variables, which override built-in defaults.",
242
+ allow_abbrev=False,
243
+ )
244
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
245
+ defaults = Settings()
246
+
247
+ def add(*flags, env, dest, help, **kwargs):
248
+ env_value = os.environ.get(env)
249
+ default = env_value if env_value else getattr(defaults, dest, None)
250
+ parser.add_argument(*flags, dest=dest, default=default, help=f"{help} [{env}]", **kwargs)
251
+
252
+ add("--discord-user-token", "--token", env="DISCORD_USER_TOKEN", dest="token", metavar="TOKEN",
253
+ help="Discord user token; prefer the environment variable to keep it out of process arguments.")
254
+ add("--prefix", env="SELFBOT_PREFIX", dest="prefix", type=_prefix,
255
+ help="Chat command prefix (default: >).")
256
+ add("--reply-delete-after", env="SELFBOT_REPLY_DELETE_AFTER", dest="reply_delete_after",
257
+ type=_positive_seconds, metavar="SECONDS", help="Time before deleting replies (default: 20).")
258
+ add("--tts-voice", env="SELFBOT_TTS_VOICE", dest="tts_voice", type=_voice,
259
+ help="Default eSpeak voice (default: en-us+whisper).")
260
+ add("--tts-speed", env="SELFBOT_TTS_SPEED", dest="tts_speed", type=_bounded_int(80, 450),
261
+ metavar="80-450", help="Default TTS speed in words per minute.")
262
+ add("--tts-pitch", env="SELFBOT_TTS_PITCH", dest="tts_pitch", type=_bounded_int(0, 99),
263
+ metavar="0-99", help="Default TTS pitch.")
264
+ add("--tts-amplitude", env="SELFBOT_TTS_AMPLITUDE", dest="tts_amplitude", type=_bounded_int(0, 200),
265
+ metavar="0-200", help="Default TTS amplitude.")
266
+ add("--voice-timeout", env="SELFBOT_VOICE_TIMEOUT", dest="voice_timeout",
267
+ type=_positive_seconds, metavar="SECONDS", help="Voice connection timeout (default: 20).")
268
+ add("--recordings-dir", env="SELFBOT_RECORDINGS_DIR", dest="recordings_dir", type=Path,
269
+ metavar="PATH", help="Recording and transcript directory (default: ./recordings).")
270
+ add("--whisper-model", env="WHISPER_MODEL", dest="whisper_model",
271
+ type=lambda value: value.strip().lower() or defaults.whisper_model,
272
+ help="Default transcription model (default: turbo).")
273
+ add("--whisper-language", "--whisper-lang", env="WHISPER_LANGUAGE", dest="whisper_language",
274
+ type=_whisper_language, metavar="CODE|auto",
275
+ help="Default Whisper language code to skip per-chunk detection, or auto (default: en).")
276
+ vad_env = os.getenv("WHISPER_VAD")
277
+ parser.add_argument(
278
+ "--whisper-vad", action=argparse.BooleanOptionalAction,
279
+ default=defaults.whisper_vad if not vad_env else vad_env == "1",
280
+ help="Run Silero VAD over each chunk to drop non-speech before transcription [WHISPER_VAD=1].",
281
+ )
282
+ add("--whisper-backend", "--whisper-device", env="WHISPER_BACKEND", dest="whisper_backend",
283
+ type=_backend, metavar="{auto,cpu,cuda}", help="Local faster-whisper device (default: auto).")
284
+ add("--whisper-streams", env="WHISPER_STREAMS", dest="whisper_streams", type=_positive_int,
285
+ metavar="COUNT", help="Maximum loaded or loading Whisper instances (default: 2 CPU / 4 CUDA).")
286
+ add("--whisper-workers", env="WHISPER_WORKERS", dest="whisper_workers", type=_positive_int,
287
+ metavar="COUNT", help="Transcription worker threads (default: available logical CPUs, up to 32).")
288
+ add("--whisper-vram-percent", env="WHISPER_VRAM_PERCENT", dest="whisper_vram_percent",
289
+ type=_bounded_int(1, 100), metavar="1-100", help="CUDA VRAM budget percentage (default: 75).")
290
+ add("--whisper-chunk-seconds", env="WHISPER_CHUNK_SECONDS", dest="whisper_chunk_seconds",
291
+ type=_bounded_int(1, 10), metavar="1-10", help="Seconds per streaming audio chunk (default: 2).")
292
+ add("--whisper-pause-seconds", env="WHISPER_PAUSE_SECONDS", dest="whisper_pause_seconds",
293
+ type=_positive_seconds, metavar="SECONDS", help="Silence before flushing a speaker (default: 1).")
294
+ parser.add_argument(
295
+ "--debug", action=argparse.BooleanOptionalAction, default=os.getenv("SELFBOT_DEBUG") == "1",
296
+ help="Enable local command and voice debug logging [SELFBOT_DEBUG=1].",
297
+ )
298
+ return parser
299
+
300
+
301
+ def parse_startup(parser, argv=None):
302
+ values = vars(parser.parse_args(argv))
303
+ token = (values.pop("token") or "").strip()
304
+ if not token:
305
+ parser.error("set DISCORD_USER_TOKEN or pass --discord-user-token")
306
+ # An installed console script has no "beside the code" directory to fall back
307
+ # on, so an unset --recordings-dir means ./recordings in the working directory.
308
+ recordings_dir = values["recordings_dir"] or Path.cwd() / "recordings"
309
+ try:
310
+ values["recordings_dir"] = Path(recordings_dir).expanduser().absolute()
311
+ except RuntimeError as error:
312
+ parser.error(f"--recordings-dir: {error}")
313
+ # argparse only applies `type` to command-line values, not to environment
314
+ # defaults, so validate and canonicalize the language here as well.
315
+ try:
316
+ values["whisper_language"] = normalize_whisper_language(values["whisper_language"])
317
+ except ValueError as error:
318
+ parser.error(f"--whisper-language: {error}")
319
+ return token, Settings(**values)