py-termcam 0.2.0__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.
@@ -0,0 +1,172 @@
1
+ Metadata-Version: 2.4
2
+ Name: py-termcam
3
+ Version: 0.2.0
4
+ Summary: Live webcam → terminal art in 8 styles, with a virtual camera for OBS. Works without a camera too.
5
+ Author: termcam contributors
6
+ License: MIT
7
+ Keywords: webcam,terminal,ascii-art,creative-coding,cli,virtual-camera,obs
8
+ Classifier: Environment :: Console
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Multimedia :: Video :: Capture
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: opencv-python>=4.8
15
+ Provides-Extra: dev
16
+ Requires-Dist: pytest>=8.0; extra == "dev"
17
+ Provides-Extra: webcam
18
+ Requires-Dist: pyvirtualcam>=0.12; extra == "webcam"
19
+ Requires-Dist: numpy>=1.24; extra == "webcam"
20
+ Dynamic: license-file
21
+
22
+ # termcam
23
+
24
+ Your webcam — live — rendered in the terminal as ASCII, neon, dither or
25
+ glitch art. One keystroke changes the style. No GUI windows, no browser, just
26
+ the console and you.
27
+
28
+ No webcam? **termcam** generates a procedural plasma that still reacts to
29
+ your keystrokes and serves as a screensaver-style demo.
30
+
31
+ ## Install
32
+
33
+ ```bash
34
+ pip install termcam # terminal + window art
35
+ pip install "termcam[webcam]" # + virtual camera (--out webcam)
36
+ ```
37
+
38
+ ## Quick start
39
+
40
+ ```bash
41
+ termcam # uses webcam, ascii style, 24 fps
42
+ termcam --source synth # no webcam needed — procedural plasma
43
+ termcam --source url --url "http://192.168.1.5:8080/video" # phone via IP Webcam
44
+ termcam --out webcam --source synth # art becomes a virtual camera device
45
+ termcam --out window --source synth # art in a GUI window (OBS Window Capture)
46
+ ```
47
+
48
+ ### Hotkeys (while running)
49
+
50
+ | Key | Action |
51
+ |-----|---------------------------|
52
+ | a | ASCII (luminance → chars) |
53
+ | s | Neon (color gradient) |
54
+ | d | Dither (pixel noise) |
55
+ | g | Glitch (sparkling) |
56
+ | e | Sketch (edge detection) |
57
+ | h | Halftone (newsprint) |
58
+ | t | Thermal (heatmap) |
59
+ | x | Negative (film invert) |
60
+ | m | Mirror / un-mirror |
61
+ | q | Quit |
62
+
63
+ Press the style key repeatedly for palette variants.
64
+
65
+ ## Styles
66
+
67
+ - **ASCII** — classic monochrome luminance ramp (`" .:-=+*#%@"`)
68
+ - **Neon** — full color, mapped through an ANSI 256 palette
69
+ - **Dither** — 4×4 Bayer matrix noise, retro pixel look
70
+ - **Glitch** — per-frame hash sparkle, chaotic but alive
71
+ - **Sketch** — edge detection (Sobel-like), pencil-look line art, light/dark paper
72
+ - **Halftone** — newspaper print: ink shades on paper-color background
73
+ - **Thermal** — heatmap palettes (fire, inferno, deep water, lava-pink)
74
+ - **Negative** — film negative, posterized, cyan/magenta/warm X-ray tints
75
+
76
+ Every style has palette/param variants — keep pressing its key to cycle.
77
+
78
+ ## CLI options
79
+
80
+ ```
81
+ termcam
82
+ --source {camera,synth,url} input source (default: camera)
83
+ --style {ascii,neon,dith,glitch,sketch,halftone,thermal,negative} (default: ascii)
84
+ --out {terminal,webcam,window,both} (default: terminal)
85
+ --fps N frames per second (default: 24)
86
+ --cols N terminal width hint (auto-detected)
87
+ --device N camera device index (default: 0)
88
+ --url URL MJPEG stream for --source url
89
+ --backend {auto,obs,unitycapture} virtual camera backend (default: auto)
90
+ --webcam-size WxH virtual camera resolution (default: 1280x720)
91
+ --mirror flip horizontally
92
+ ```
93
+
94
+ ## Virtual camera & OBS
95
+
96
+ You can turn the art itself into a webcam device.
97
+
98
+ **As a real webcam in ANY app including OBS** (best: no OBS dependency):
99
+
100
+ ```bash
101
+ pip install "termcam[webcam]"
102
+ termcam --source synth --out webcam --backend unitycapture
103
+ ```
104
+
105
+ This uses the free, open-source [UnityCapture](https://github.com/schellingb/UnityCapture)
106
+ DirectShow filter as the virtual camera device **`Unity Video Capture`**. Install it
107
+ once as administrator:
108
+
109
+ 1. Clone/download [UnityCapture](https://github.com/schellingb/UnityCapture).
110
+ 2. From `UnityCapture/Install` run `Install.bat` as administrator (registers two
111
+ DLLs via `regsvr32`). Keep that folder in place while installed.
112
+ 3. In OBS: **Sources → + → Video Capture Device → Unity Video Capture**.
113
+ The device appears even while termcam runs without OBS active.
114
+
115
+ Remove it later with `Uninstall.bat` (as administrator).
116
+
117
+ **As a webcam in other apps** (Zoom, Discord, …), using OBS's own virtual camera:
118
+
119
+ ```bash
120
+ termcam --out webcam --source synth
121
+ ```
122
+
123
+ With the `obs` backend, start **OBS Studio → Start Virtual Camera** once, then pick
124
+ `OBS Virtual Camera` as the camera in any other app. Cannot be consumed as an
125
+ input inside the same OBS instance.
126
+
127
+ **Preview window** (for OBS Window Capture if you prefer):
128
+
129
+ ```bash
130
+ termcam --out window --source synth
131
+ ```
132
+
133
+ A window titled `termcam` opens; in OBS add **Sources → Window Capture →
134
+ termcam**.
135
+
136
+ Hotkeys work in every output mode (`a/s/d/g/e/h/t/x`, `m`, `q`).
137
+
138
+ ## Phone as a webcam
139
+
140
+ No USB webcam? Any Android phone with a WiFi connection works — termcam just
141
+ needs a URL. Tested target: a 2016 Samsung Galaxy J1 Mini (Android 5.1).
142
+
143
+ 1. Install the free app **IP Webcam** on the phone (Play Store; works on
144
+ Android 5.0+).
145
+ 2. Connect the phone and your PC to the **same WiFi** network.
146
+ 3. Open IP Webcam → tap **Start server** at the bottom. The app shows an
147
+ address like `http://192.168.1.5:8080`.
148
+ 4. Verify on the PC in a browser: open that address — you should see the
149
+ camera preview. (Phone as a hotspot also works: connect the PC to the
150
+ phone's hotspot instead.)
151
+ 5. Point termcam at the MJPEG stream:
152
+
153
+ ```bash
154
+ termcam --source url --url "http://192.168.1.5:8080/video"
155
+ ```
156
+
157
+ 6. Hotkeys are the same — `a/s/d/g` switches styles, so the low-res J1 Mini
158
+ camera becomes lo-fi neon/dither art.
159
+
160
+ If IP Webcam has a password set (Settings → Login), embed it in the URL:
161
+ `http://user:pass@192.168.1.5:8080/video`.
162
+
163
+ ## Development
164
+
165
+ ```bash
166
+ pip install -e ".[dev]"
167
+ pytest
168
+ ```
169
+
170
+ ## License
171
+
172
+ MIT
@@ -0,0 +1,28 @@
1
+ py_termcam-0.2.0.dist-info/licenses/LICENSE,sha256=rE-db79bRxOsTi24b_Ftl_88x1942KjSRHl3ytqGcPc,1076
2
+ termcam/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ termcam/__main__.py,sha256=PsGuEvRs1Sc3IsQLg89axd3jBAHqlEHvmEJ16WlFOCU,84
4
+ termcam/camera.py,sha256=zgNOLj3UVE-ut4iyCFKnqsGM7cmkpc29Aq8mEZ1C3Bk,1675
5
+ termcam/cli.py,sha256=113R6AZtczl8CRv8ikWnIXqmbodtxW7MOaogubQhlvc,3491
6
+ termcam/colors.py,sha256=8qJ68-wp9ofIcDurcP6r8u_X5pZupy-ewZEyGj3S-8w,1256
7
+ termcam/engine.py,sha256=p2NOCtlsbf_mAHhCbb_Qy52irPZ1hmIItqEB7ge3pFo,5987
8
+ termcam/font.py,sha256=iLbmBHYZDWnyHze2yQrWWF8omL79CAHKBmev8Tai8LA,6987
9
+ termcam/frame.py,sha256=HsJ2cWHAPgx7sjaPOtvJxsyL7Bev6fbCgGLXF1R3puI,964
10
+ termcam/keys.py,sha256=7j54ua7_L76dG1XH54ejBEO6uaQ6wPyheq5Rvkx9BvY,1705
11
+ termcam/renderer.py,sha256=zGzfd0ZIRusrqqGkJIX3ObnXqzHlIepogCVuWnx0XLg,754
12
+ termcam/sources.py,sha256=ro9ho0UqcpDCU_DgYEOi2qFjzP7ZVbU5SreWVKc8joY,1018
13
+ termcam/webcam.py,sha256=ZHufHtWZYFJQLafbFVyZLwqr75riugR8gubUy77DNDQ,5010
14
+ termcam/styles/__init__.py,sha256=jH3jW8pTTsRrpC_VYSjGN1myRm8QUDYvrKcqnLXiWQY,507
15
+ termcam/styles/ascii.py,sha256=sH2QoKrLW7VqYj-Ae-IX-oo3dAe51a8T2rq_yfBDJg0,1044
16
+ termcam/styles/base.py,sha256=zn__8NGrr8pdQuB8qg53t5WLiex4zmBVqj2uqbJWmjQ,375
17
+ termcam/styles/dither.py,sha256=Ey_7HeovUeIFO-MsPToTCWhQQIIx2UlnTF7DvNrisfw,1550
18
+ termcam/styles/glitch.py,sha256=hnJYg8NTTuRbsza5N_HBb-XkFNC-7oyzdYyuBa6FrUA,1077
19
+ termcam/styles/halftone.py,sha256=H78kXOxdht1ElJk2GGMdQfgKHv1BrAiqF7Ua8dktPbE,1119
20
+ termcam/styles/negative.py,sha256=Bb0x_x7aj62_lRHnyaog05RtZyse4MYq_2wViZzGesc,1337
21
+ termcam/styles/neon.py,sha256=LIshntk5x_yJsxq8-s77d7Gv_yTBZV1IKi0p-V8YsxY,1324
22
+ termcam/styles/sketch.py,sha256=CJJOR5tYPwhar6YY45Xlr-6ki0AzLO-1nVKtkMbFk3g,1817
23
+ termcam/styles/thermal.py,sha256=Ui9K0up1lP5uU5eF77GwRezXcFxSeugh78Wlh9H16eA,1593
24
+ py_termcam-0.2.0.dist-info/METADATA,sha256=QhCbeg9R6peyYT7vQgtOhUfMyCxuelVRqM6TqyUYZZI,6194
25
+ py_termcam-0.2.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
26
+ py_termcam-0.2.0.dist-info/entry_points.txt,sha256=HDUl6WFEcV6ypYg7UIinWseF0NQfaE7TM8HMx_PK6L0,45
27
+ py_termcam-0.2.0.dist-info/top_level.txt,sha256=n_XNV7ddUcAGfKAcx1wjmx7F3YwZK2FHXD5Wr4-ll1o,8
28
+ py_termcam-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ termcam = termcam.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 termcam contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ termcam
termcam/__init__.py ADDED
File without changes
termcam/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main(sys.argv[1:])
termcam/camera.py ADDED
@@ -0,0 +1,58 @@
1
+ from __future__ import annotations
2
+
3
+ import cv2
4
+
5
+ from .frame import Frame
6
+
7
+
8
+ def _read_and_resize(cap, cols: int, rows: int) -> Frame:
9
+ ok, frame = cap.read()
10
+ if not ok:
11
+ raise RuntimeError("Source returned no frame")
12
+ resized = cv2.resize(
13
+ frame,
14
+ (cols, rows * 2),
15
+ interpolation=cv2.INTER_AREA,
16
+ )
17
+ pixels = [
18
+ [(int(p[2]), int(p[1]), int(p[0])) for p in row] for row in resized
19
+ ]
20
+ return Frame(cols, rows * 2, pixels)
21
+
22
+
23
+ class CameraSource:
24
+ def __init__(self, device: int = 0, cols: int = 80, rows: int = 40) -> None:
25
+ self.device = device
26
+ self.cols = cols
27
+ self.rows = rows
28
+ self._cap = cv2.VideoCapture(device)
29
+ if not self._cap.isOpened():
30
+ raise RuntimeError(f"Could not open camera device {device}")
31
+
32
+ def read(self) -> Frame:
33
+ try:
34
+ return _read_and_resize(self._cap, self.cols, self.rows)
35
+ except RuntimeError:
36
+ raise RuntimeError("Camera returned no frame") from None
37
+
38
+ def close(self) -> None:
39
+ self._cap.release()
40
+
41
+
42
+ class UrlSource:
43
+ def __init__(self, url: str, cols: int = 80, rows: int = 40) -> None:
44
+ self.url = url
45
+ self.cols = cols
46
+ self.rows = rows
47
+ self._cap = cv2.VideoCapture(url)
48
+ if not self._cap.isOpened():
49
+ raise RuntimeError(f"Could not open stream at {url}")
50
+
51
+ def read(self) -> Frame:
52
+ try:
53
+ return _read_and_resize(self._cap, self.cols, self.rows)
54
+ except RuntimeError:
55
+ raise RuntimeError(f"Stream returned no frame: {self.url}") from None
56
+
57
+ def close(self) -> None:
58
+ self._cap.release()
termcam/cli.py ADDED
@@ -0,0 +1,102 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+
6
+ from .engine import DEFAULT_STYLE, STYLES, _use_utf8, build_source, run
7
+
8
+
9
+ def _build_parser() -> argparse.ArgumentParser:
10
+ parser = argparse.ArgumentParser(
11
+ prog="termcam",
12
+ description=(
13
+ "Live webcam → terminal art. Keystrokes: a/s/d/g/e/h/t/x styles, "
14
+ "m mirror, q quit."
15
+ ),
16
+ )
17
+ parser.add_argument(
18
+ "--source", choices=("camera", "synth", "url"), default="camera",
19
+ help="input source (default: camera)",
20
+ )
21
+ parser.add_argument(
22
+ "--style", choices=tuple(STYLES), default=DEFAULT_STYLE,
23
+ help=f"initial style (default: {DEFAULT_STYLE})",
24
+ )
25
+ parser.add_argument(
26
+ "--out",
27
+ choices=("terminal", "webcam", "window", "both"),
28
+ default="terminal",
29
+ help="where to show art: terminal, virtual camera (webcam), preview window, or both",
30
+ )
31
+ parser.add_argument(
32
+ "--backend",
33
+ choices=("auto", "obs", "unitycapture"),
34
+ default="auto",
35
+ help="virtual camera backend (default: auto)",
36
+ )
37
+ parser.add_argument(
38
+ "--webcam-size",
39
+ default="1280x720",
40
+ metavar="WxH",
41
+ help="virtual camera resolution (default: 1280x720)",
42
+ )
43
+ parser.add_argument("--fps", type=int, default=24, help="frames per second (default: 24)")
44
+ parser.add_argument("--device", type=int, default=0, help="camera device index (default: 0)")
45
+ parser.add_argument(
46
+ "--url", default="",
47
+ help="MJPEG stream URL for --source url (e.g. http://192.168.1.5:8080/video)",
48
+ )
49
+ parser.add_argument("--cols", type=int, default=0, help="horizontal cells (0 = auto-detect)")
50
+ parser.add_argument("--mirror", action="store_true", help="start mirrored")
51
+ return parser
52
+
53
+
54
+ def main(argv: list[str] | None = None) -> None:
55
+ _use_utf8()
56
+ args = _build_parser().parse_args(argv)
57
+
58
+ if args.source == "url" and not args.url:
59
+ print("--source url requires --url http://<host>:<port>/video", file=sys.stderr)
60
+ sys.exit(1)
61
+
62
+ try:
63
+ width_s, height_s = args.webcam_size.lower().split("x", 1)
64
+ webcam_size = (int(width_s), int(height_s))
65
+ except (ValueError, IndexError):
66
+ print(f"Bad --webcam-size {args.webcam_size!r}; expected WxH like 1280x720", file=sys.stderr)
67
+ sys.exit(1)
68
+ if webcam_size[0] <= 0 or webcam_size[1] <= 0:
69
+ print("Bad --webcam-size; width and height must be positive", file=sys.stderr)
70
+ sys.exit(1)
71
+
72
+ try:
73
+ source = build_source(args.source, args.device, args.cols or 80, 40, args.url)
74
+ except RuntimeError as exc:
75
+ if args.source == "camera":
76
+ print(f"Camera unavailable ({exc}). Falling back to synth.", file=sys.stderr)
77
+ source = build_source("synth", 0, args.cols or 80, 40)
78
+ else:
79
+ print(f"{exc}. Try --source synth as a demo.", file=sys.stderr)
80
+ sys.exit(1)
81
+
82
+ print(
83
+ "a/s/d/g/e/h/t/x = styles, m = mirror, q = quit. Pressing a style key again cycles variants.",
84
+ file=sys.stderr,
85
+ )
86
+ try:
87
+ run(
88
+ source,
89
+ fps=args.fps,
90
+ initial_style=args.style,
91
+ mirror=args.mirror,
92
+ out=args.out,
93
+ webcam_size=webcam_size,
94
+ backend=args.backend,
95
+ )
96
+ except RuntimeError as exc:
97
+ print(str(exc), file=sys.stderr)
98
+ sys.exit(1)
99
+
100
+
101
+ if __name__ == "__main__":
102
+ main()
termcam/colors.py ADDED
@@ -0,0 +1,59 @@
1
+ from __future__ import annotations
2
+
3
+ RGB = tuple[int, int, int]
4
+
5
+
6
+ def luminance(r: int, g: int, b: int) -> float:
7
+ return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255.0
8
+
9
+
10
+ def clamp(v: int) -> int:
11
+ return max(0, min(255, v))
12
+
13
+
14
+ def to_ansi256(r: int, g: int, b: int) -> int:
15
+ r, g, b = clamp(r), clamp(g), clamp(b)
16
+ if r == g == b:
17
+ if r < 8:
18
+ return 16
19
+ if r > 248:
20
+ return 231
21
+ return round((r - 8) / 10) * 36 + 232
22
+ r_i = round(r / 51)
23
+ g_i = round(g / 51)
24
+ b_i = round(b / 51)
25
+ return 16 + 36 * r_i + 6 * g_i + b_i
26
+
27
+
28
+ def lerp(a: RGB, b: RGB, t: float) -> RGB:
29
+ t = max(0.0, min(1.0, t))
30
+ return (
31
+ round(a[0] + (b[0] - a[0]) * t),
32
+ round(a[1] + (b[1] - a[1]) * t),
33
+ round(a[2] + (b[2] - a[2]) * t),
34
+ )
35
+
36
+
37
+ NEON_STOPS = [
38
+ (12, 12, 60),
39
+ (0, 255, 255),
40
+ (255, 0, 255),
41
+ (255, 255, 0),
42
+ (255, 255, 255),
43
+ ]
44
+
45
+ NEON_ALT_STOPS = [
46
+ (0, 0, 0),
47
+ (255, 0, 128),
48
+ (255, 140, 0),
49
+ (255, 255, 255),
50
+ ]
51
+
52
+
53
+ def gradient(stops: list[RGB], t: float) -> RGB:
54
+ t = max(0.0, min(1.0, t))
55
+ if t >= 1.0:
56
+ return stops[-1]
57
+ scaled = t * (len(stops) - 1)
58
+ index = int(scaled)
59
+ return lerp(stops[index], stops[index + 1], scaled - index)
termcam/engine.py ADDED
@@ -0,0 +1,207 @@
1
+ from __future__ import annotations
2
+
3
+ import ctypes
4
+ import os
5
+ import sys
6
+ import time
7
+
8
+ from .camera import CameraSource, UrlSource
9
+ from .keys import KeyReader, enable_raw_input, restore_terminal
10
+ from .renderer import HIDE_CURSOR, HOME, SHOW_CURSOR, render
11
+ from .sources import SynthSource
12
+ from .styles import (
13
+ AsciiStyle,
14
+ DitherStyle,
15
+ GlitchStyle,
16
+ HalftoneStyle,
17
+ NegativeStyle,
18
+ NeonStyle,
19
+ SketchStyle,
20
+ Style,
21
+ ThermalStyle,
22
+ )
23
+
24
+ STYLES: dict[str, type[Style]] = {
25
+ "ascii": AsciiStyle,
26
+ "neon": NeonStyle,
27
+ "dither": DitherStyle,
28
+ "glitch": GlitchStyle,
29
+ "sketch": SketchStyle,
30
+ "halftone": HalftoneStyle,
31
+ "thermal": ThermalStyle,
32
+ "negative": NegativeStyle,
33
+ }
34
+ DEFAULT_STYLE = "ascii"
35
+
36
+ KEY_MAP = {
37
+ "a": "ascii",
38
+ "s": "neon",
39
+ "d": "dither",
40
+ "g": "glitch",
41
+ "e": "sketch",
42
+ "h": "halftone",
43
+ "t": "thermal",
44
+ "x": "negative",
45
+ }
46
+
47
+ ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
48
+
49
+
50
+ def _enable_vt() -> None:
51
+ if os.name != "nt":
52
+ return
53
+ try:
54
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
55
+ handle = kernel32.GetStdHandle(-11)
56
+ mode = ctypes.c_uint32()
57
+ if kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
58
+ kernel32.SetConsoleMode(handle, mode.value | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
59
+ except OSError:
60
+ pass
61
+
62
+
63
+ def _use_utf8() -> None:
64
+ for stream in (sys.stdout, sys.stderr):
65
+ if hasattr(stream, "reconfigure"):
66
+ try:
67
+ stream.reconfigure(encoding="utf-8", errors="replace")
68
+ except (OSError, ValueError):
69
+ pass
70
+
71
+
72
+ def build_source(kind: str, device: int, cols: int, rows: int, url: str = ""):
73
+ if kind == "synth":
74
+ return SynthSource(cols, rows)
75
+ if kind == "url":
76
+ return UrlSource(url, cols, rows)
77
+ return CameraSource(device, cols, rows)
78
+
79
+
80
+ def _resized(source, cols: int, rows: int):
81
+ if isinstance(source, SynthSource):
82
+ return SynthSource(cols, rows)
83
+ if isinstance(source, UrlSource):
84
+ return UrlSource(source.url, cols, rows)
85
+ return CameraSource(source.device, cols, rows)
86
+
87
+
88
+ def run(
89
+ source,
90
+ fps: int = 24,
91
+ initial_style: str = DEFAULT_STYLE,
92
+ mirror: bool = False,
93
+ out: str = "terminal",
94
+ webcam_size: tuple[int, int] = (1280, 720),
95
+ backend: str | None = "auto",
96
+ ) -> None:
97
+ _use_utf8()
98
+ _enable_vt()
99
+
100
+ cam = None
101
+ _cv2 = None
102
+ if out in ("webcam", "both"):
103
+ from .webcam import VirtualCamera, rasterize
104
+
105
+ cam = VirtualCamera(webcam_size[0], webcam_size[1], fps, backend=backend)
106
+ try:
107
+ cam.open()
108
+ except RuntimeError as exc:
109
+ if out == "webcam":
110
+ raise
111
+ print(str(exc), file=sys.stderr)
112
+ print("Falling back to terminal output.", file=sys.stderr)
113
+ out = "terminal"
114
+ cam = None
115
+ elif out == "window":
116
+ try:
117
+ import cv2 as _cv2
118
+
119
+ from .webcam import rasterize
120
+
121
+ _cv2.namedWindow("termcam")
122
+ _cv2.destroyWindow("termcam")
123
+ except ImportError as exc:
124
+ raise RuntimeError("Window output needs OpenCV: pip install 'termcam'") from exc
125
+ except Exception as exc:
126
+ raise RuntimeError(
127
+ "OpenCV GUI is unavailable (a headless build is installed). "
128
+ "Reinstall with: pip install --force-reinstall opencv-python"
129
+ ) from exc
130
+
131
+ show_terminal = out in ("terminal", "both")
132
+ show_window = out == "window"
133
+ webcam_output = cam is not None
134
+
135
+ try:
136
+ cols, rows = os.get_terminal_size()
137
+ except (OSError, ValueError):
138
+ cols, rows = 80, 24
139
+ rows = max(2, int(rows) - 1)
140
+ if source.cols != cols or source.rows != rows:
141
+ source = _resized(source, cols, rows)
142
+
143
+ enable_raw_input()
144
+ keys = KeyReader()
145
+ keys.start()
146
+
147
+ style_key = initial_style if initial_style in STYLES else DEFAULT_STYLE
148
+ style = STYLES[style_key]()
149
+ variant = 0
150
+ flip = mirror
151
+
152
+ frame_interval = 1.0 / max(1, fps)
153
+ frame = None
154
+ sys.stdout.write(HIDE_CURSOR)
155
+ sys.stdout.flush()
156
+
157
+ try:
158
+ while True:
159
+ started = time.perf_counter()
160
+ frame = source.read()
161
+ if flip:
162
+ frame = frame.flip_h()
163
+ clock = time.perf_counter()
164
+ surface = style.process(frame, variant=variant, t=clock)
165
+ if webcam_output:
166
+ cam.send(rasterize(surface, webcam_size[0], webcam_size[1]))
167
+ if show_window:
168
+ _cv2.imshow("termcam", rasterize(surface, webcam_size[0], webcam_size[1]))
169
+ if _cv2.waitKey(1) & 0xFF == 27:
170
+ break
171
+ if show_terminal:
172
+ sys.stdout.write(HOME)
173
+ sys.stdout.write(render(surface))
174
+ sys.stdout.flush()
175
+
176
+ key = keys.poll()
177
+ if key is not None:
178
+ key = key.lower()
179
+ if key in KEY_MAP:
180
+ target = KEY_MAP[key]
181
+ if target == style.name:
182
+ variant = (variant + 1) % style.variants
183
+ else:
184
+ style = STYLES[target]()
185
+ variant = 0
186
+ elif key == "m":
187
+ flip = not flip
188
+ elif key in ("q", "\x1b"):
189
+ break
190
+
191
+ elapsed = time.perf_counter() - started
192
+ remaining = frame_interval - elapsed
193
+ if remaining > 0:
194
+ time.sleep(remaining)
195
+ except (KeyboardInterrupt, RuntimeError, OSError):
196
+ pass
197
+ finally:
198
+ sys.stdout.write(SHOW_CURSOR + "\x1b[0m")
199
+ sys.stdout.flush()
200
+ if _cv2 is not None:
201
+ _cv2.destroyAllWindows()
202
+ if cam is not None:
203
+ cam.close()
204
+ close = getattr(source, "close", None)
205
+ if close is not None:
206
+ close()
207
+ restore_terminal()