zebkit 0.4.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.
zebkit/media_tap.py ADDED
@@ -0,0 +1,109 @@
1
+ """Native media packets, RGBA frames, PCM and optional file recording.
2
+
3
+ All calls and callbacks run on the engine thread. Example::
4
+
5
+ from zebkit.media_tap import MediaTap, list_media
6
+ list_media(view, lambda media, error: start(media[0]['id']))
7
+ tap = MediaTap(view, media_id, on_data, path='/tmp/movie.mp4', maxFps=5)
8
+ # on_data(metadata: dict, payload: bytes); payload is an owned copy.
9
+ tap.stop() # Continue pumping until tap.done, then tap.close().
10
+
11
+ For MediaStream use packets=False (no path): its original demuxed packets
12
+ are unavailable. Video samples are displayed frames, not a decode-all API.
13
+ """
14
+ import ctypes
15
+ import json
16
+ import weakref
17
+
18
+ from . import Error, _declare, _P, _S, _Z, _EP, _RESULT, _string
19
+
20
+ _EVENT = ctypes.CFUNCTYPE(None, _P, _S, _P, _Z, _P)
21
+ _start = _declare('zebkit_media_tap_start', _P, _P, _S, _S, _EVENT, _P, _EP)
22
+ _stop = _declare('zebkit_media_tap_stop', None, _P)
23
+ _free = _declare('zebkit_media_tap_free', None, _P)
24
+ _list = _declare('zebkit_view_media_list', None, _P, _RESULT, _P)
25
+ _active = set()
26
+ _pending_lists = {}
27
+
28
+
29
+ def list_media(view, callback):
30
+ """Call callback(list_or_none, error_or_none) with every frame's media."""
31
+ @_RESULT
32
+ def result(_view, value, error, _data):
33
+ _pending_lists.pop(id(result), None)
34
+ callback(json.loads(value) if value else None,
35
+ error.decode() if error else None)
36
+ handle = view._check()
37
+ _pending_lists[id(result)] = result
38
+ _list(handle, result, None)
39
+
40
+
41
+ class MediaTap:
42
+ """Active taps stay alive until done or close; explicitly stop/close them.
43
+
44
+ Callback exceptions are stored in callback_error and stop the tap. File
45
+ finalization remains asynchronous. close() suppresses subsequent events.
46
+ """
47
+ def __init__(self, view, media_id, callback, **options):
48
+ self._handle = None
49
+ if not callable(callback):
50
+ raise TypeError('callback must be callable')
51
+ self._handle = None
52
+ self._callback = callback
53
+ self.done = None
54
+ self.callback_error = None
55
+ owner = weakref.ref(self)
56
+
57
+ @_EVENT
58
+ def event(_tap, text, pointer, size, _data):
59
+ current = owner()
60
+ if current is None:
61
+ return
62
+ metadata = json.loads(text)
63
+ for key in ('ptsUs', 'dtsUs', 'durationUs'):
64
+ if key in metadata:
65
+ metadata[key] = int(metadata[key])
66
+ payload = ctypes.string_at(pointer, size) if size else b''
67
+ terminal = metadata.get('type') == 'done'
68
+ if terminal:
69
+ current.done = metadata
70
+ try:
71
+ if current._callback:
72
+ current._callback(metadata, payload)
73
+ except Exception as exc:
74
+ current.callback_error = exc
75
+ current.stop()
76
+ finally:
77
+ if terminal:
78
+ _active.discard(current)
79
+
80
+ self._event = event
81
+ error = ctypes.c_void_p()
82
+ self._handle = _start(view._check(), str(media_id).encode(),
83
+ json.dumps(options, allow_nan=False).encode(),
84
+ event, None, ctypes.byref(error))
85
+ if not self._handle:
86
+ raise Error(_string(error.value) or 'media tap did not start')
87
+ _active.add(self)
88
+
89
+ def stop(self):
90
+ """Stop receiving samples; done follows when any file is finalized."""
91
+ if self._handle:
92
+ _stop(self._handle)
93
+
94
+ def close(self):
95
+ """Release the handle and suppress callbacks; safe inside a callback."""
96
+ handle, self._handle = getattr(self, "_handle", None), None
97
+ if handle:
98
+ _free(handle)
99
+ _active.discard(self)
100
+ self._callback = None
101
+
102
+ def __enter__(self):
103
+ return self
104
+
105
+ def __exit__(self, *_):
106
+ self.close()
107
+
108
+ def __del__(self):
109
+ self.close()
zebkit/media_tools.py ADDED
@@ -0,0 +1,123 @@
1
+ """Synchronous media tools using zebkit's FFmpeg; no engine loop required.
2
+
3
+ Run long calls in an application worker thread. argv is a sequence of strings,
4
+ without an executable name or shell quoting. See docs/MEDIA_TOOLS.md for the
5
+ supported CLI subset. Unsupported codecs/options raise Error.
6
+ """
7
+ import ctypes
8
+ import json
9
+ import os
10
+
11
+ from . import Error, _declare, _P, _S, _string
12
+
13
+ _PROGRESS = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int64, ctypes.c_int64, _P)
14
+ _probe = _declare('zebkit_ffprobe', ctypes.c_int, ctypes.c_int,
15
+ ctypes.POINTER(_S), ctypes.POINTER(_P), ctypes.POINTER(_P))
16
+ _process = _declare('zebkit_ffmpeg', ctypes.c_int, ctypes.c_int,
17
+ ctypes.POINTER(_S), _PROGRESS, _P, ctypes.POINTER(_P))
18
+
19
+
20
+ class Cancelled(Error):
21
+ """Processing was cancelled; the destination was not changed."""
22
+
23
+
24
+ def _args(argv):
25
+ if isinstance(argv, (str, bytes)):
26
+ raise TypeError('argv must be a sequence, not a shell command')
27
+ values = [os.fsencode(arg) for arg in argv]
28
+ if any(not arg or b'\0' in arg for arg in values):
29
+ raise ValueError('arguments must be nonempty and contain no NUL')
30
+ return (_S * len(values))(*values)
31
+
32
+
33
+ def ffprobe(argv):
34
+ """Return format/streams as a dict (JSON-compatible ffprobe subset)."""
35
+ args = _args(argv)
36
+ result, error = _P(), _P()
37
+ code = _probe(len(args), args, ctypes.byref(result), ctypes.byref(error))
38
+ message = _string(error)
39
+ value = _string(result)
40
+ if code:
41
+ raise Error(message or 'media probe failed')
42
+ return json.loads(value)
43
+
44
+
45
+ def probe(path):
46
+ """Inspect a local media file; return format and stream metadata."""
47
+ return ffprobe(['-i', path])
48
+
49
+
50
+ def ffmpeg(argv, *, progress=None):
51
+ """Process a local file. progress(packets, time_us_or_None) returns bool.
52
+
53
+ Return False to cancel; callback exceptions are re-raised after native
54
+ cleanup. A callback runs synchronously on the calling thread.
55
+ """
56
+ args = _args(argv)
57
+ if progress is not None and not callable(progress):
58
+ raise TypeError('progress must be callable')
59
+ failure = []
60
+
61
+ @_PROGRESS
62
+ def callback(packets, time_us, _data):
63
+ if progress is None:
64
+ return 1
65
+ try:
66
+ return int(bool(progress(packets, None if time_us == -(1 << 63) else time_us)))
67
+ except BaseException as exc:
68
+ failure.append(exc)
69
+ return 0
70
+
71
+ error = _P()
72
+ code = _process(len(args), args, callback, None, ctypes.byref(error))
73
+ message = _string(error)
74
+ if failure:
75
+ raise failure[0]
76
+ if code == 1:
77
+ raise Cancelled(message or 'cancelled')
78
+ if code:
79
+ raise Error(message or 'media processing failed')
80
+
81
+
82
+ def remux(source, destination, *, streams=None, format=None, overwrite=False, progress=None):
83
+ """Copy encoded streams without quality loss; default selects audio/video."""
84
+ args = ['-y' if overwrite else '-n', '-i', source, '-c', 'copy']
85
+ if streams is not None:
86
+ streams = list(streams)
87
+ if not streams:
88
+ raise ValueError('streams must not be empty')
89
+ for stream in streams:
90
+ if type(stream) is not int or stream < 0:
91
+ raise ValueError('stream indices must be nonnegative integers')
92
+ args += ['-map', f'0:{stream}']
93
+ if format:
94
+ args += ['-f', format]
95
+ ffmpeg(args + ['--', destination], progress=progress)
96
+
97
+
98
+ def extract_audio(source, destination, *, sample_rate=16000, channels=1,
99
+ stream=None, raw=False, overwrite=False, progress=None):
100
+ """Decode to WAV or raw interleaved s16le, resampling as requested."""
101
+ args = ['-y' if overwrite else '-n', '-i', source, '-c:a', 'pcm_s16le',
102
+ '-ar', str(sample_rate), '-ac', str(channels), '-f', 's16le' if raw else 'wav']
103
+ if stream is not None:
104
+ args += ['-map', f'0:{stream}']
105
+ ffmpeg(args + ['--', destination], progress=progress)
106
+
107
+
108
+ def extract_video(source, destination, *, size=None, frames=None, stream=None,
109
+ overwrite=False, progress=None):
110
+ """Decode to packed RGBA frames. No headers; use probe() for source size.
111
+
112
+ size=(width,height) scales every frame. frames limits the output count.
113
+ Rotation/display matrices and HDR tone mapping are not applied.
114
+ """
115
+ args = ['-y' if overwrite else '-n', '-i', source, '-c:v', 'rawvideo', '-f', 'rawvideo']
116
+ if size is not None:
117
+ width, height = size
118
+ args += ['-s', f'{width}x{height}']
119
+ if frames is not None:
120
+ args += ['-frames:v', str(frames)]
121
+ if stream is not None:
122
+ args += ['-map', f'0:{stream}']
123
+ ffmpeg(args + ['--', destination], progress=progress)
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.4
2
+ Name: zebkit
3
+ Version: 0.4.0
4
+ Summary: Chromium's engine as a library, from Python: web views, PDF, media, Playwright's API natively, and the libraries inside the engine
5
+ Keywords: chromium,browser,webview,pdf,playwright,automation
6
+ License-Expression: LGPL-2.1-or-later
7
+ Classifier: Operating System :: POSIX :: Linux
8
+ Classifier: Operating System :: MacOS
9
+ Classifier: Operating System :: Microsoft :: Windows
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Internet :: WWW/HTTP :: Browsers
12
+ Requires-Python: >=3.8
13
+ Project-URL: Homepage, https://github.com/ikey4u/zebkit
14
+ Project-URL: Documentation, https://github.com/ikey4u/zebkit/blob/main/docs/API.md
15
+ Project-URL: Releases, https://github.com/ikey4u/zebkit/releases
16
+ Description-Content-Type: text/markdown
17
+
18
+ # zebkit for Python
19
+
20
+ Chromium's engine as a library: web views in your own windows or off-screen,
21
+ a full PDF API on PDFium, media, compression, crypto, Playwright's API run
22
+ inside the engine, and the C libraries inside it. Pure Python on `ctypes`,
23
+ nothing to compile.
24
+
25
+ ```python
26
+ import zebkit
27
+
28
+ def ready():
29
+ view = zebkit.View("https://example.com/")
30
+ view.on_load(lambda event, url: event == zebkit.LOAD_FINISHED and
31
+ view.evaluate("document.title", lambda title, error: print(title)))
32
+
33
+ zebkit.main(ready)
34
+ ```
35
+
36
+ The package is the binding; the engine is a separate download. Unpack the
37
+ archive for your system from the [releases](https://github.com/ikey4u/zebkit/releases)
38
+ of the same version (Linux x86-64, macOS on Apple silicon, Windows x64) and
39
+ point `ZEBKIT_DIR` at it:
40
+
41
+ ```sh
42
+ pip install zebkit
43
+ export ZEBKIT_DIR=/path/to/zebkit-<version>-<target>
44
+ ```
45
+
46
+ Everything the binding offers is in
47
+ [docs/API.md](https://github.com/ikey4u/zebkit/blob/main/docs/API.md), and
48
+ Playwright's API from Python (`zebkit.automation`) in
49
+ [docs/AUTOMATION.md](https://github.com/ikey4u/zebkit/blob/main/docs/AUTOMATION.md).
@@ -0,0 +1,7 @@
1
+ zebkit/__init__.py,sha256=zhv5LAfSRIMKS8TM9UMHcQUHRCjZ7k-87FCuWMz7uaA,122704
2
+ zebkit/automation.py,sha256=1F4zBQ4I4E-lP5uysYnakvmIxu7TxPXPb3SmQcX1eeE,66536
3
+ zebkit/media_tap.py,sha256=Qp0v3-5r-LolPfPhb15DJ591Fiwwp9duSnxUB0vbNO4,3915
4
+ zebkit/media_tools.py,sha256=6jtAQYhIlhhQceEIJBAJPaFp95EcHDrbpiHLXHoZxJ8,4678
5
+ zebkit-0.4.0.dist-info/WHEEL,sha256=MWx7psoF7KNST9G72pGtiBYuaXRXQXBk9pw5R6FzYko,80
6
+ zebkit-0.4.0.dist-info/METADATA,sha256=quUT29ihph88chdtaPGZkWDYXzk3mee0vAb35eFuihI,1928
7
+ zebkit-0.4.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.7
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any