mprobe 0.0.1__tar.gz

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.
mprobe-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,48 @@
1
+ Metadata-Version: 2.4
2
+ Name: mprobe
3
+ Version: 0.0.1
4
+ Summary: Read video and audio metadata using ffprobe or avprobe
5
+ Author-email: pi11 <webii@pm.me>
6
+ Project-URL: Homepage, https://github.com/pi11/mprobe
7
+ Project-URL: Issues, https://github.com/pi11/mprobe/issues
8
+ Keywords: video,audio,metadata,ffprobe,avprobe
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Topic :: Multimedia :: Sound/Audio
13
+ Classifier: Topic :: Multimedia :: Video
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/x-rst
16
+ License-File: THIRD_PARTY_NOTICES
17
+ Dynamic: license-file
18
+
19
+ mprobe
20
+ ======
21
+
22
+ Read video and audio metadata with Python 3.10+ and ffprobe (or avprobe).
23
+ Install `FFmpeg <https://ffmpeg.org/download.html>`_ separately and ensure
24
+ ``ffprobe`` is on your PATH; pip does not install it.
25
+
26
+ Install and use
27
+ ---------------
28
+
29
+ .. code-block:: console
30
+
31
+ python -m pip install mprobe
32
+
33
+ .. code-block:: python
34
+
35
+ from mprobe import mediainfo
36
+
37
+ info = mediainfo("video.mp4", timeout=30)
38
+ print(info.get("duration")) # seconds, as a string
39
+ print(info.get("format_name"))
40
+
41
+ Accepts strings and pathlib paths. Values are strings; ``TAG`` and
42
+ ``DISPOSITION`` contain dictionaries. Repeated fields use the last stream's
43
+ value, then the container's value. Fields vary by file and may be absent.
44
+ Missing probes raise ``FileNotFoundError``; invalid or missing media raise
45
+ ``subprocess.CalledProcessError`` (details in ``stderr``). A timeout raises
46
+ ``subprocess.TimeoutExpired``.
47
+
48
+ Inspired by `pydub <https://github.com/jiaaro/pydub>`_.
@@ -0,0 +1,30 @@
1
+ mprobe
2
+ ======
3
+
4
+ Read video and audio metadata with Python 3.10+ and ffprobe (or avprobe).
5
+ Install `FFmpeg <https://ffmpeg.org/download.html>`_ separately and ensure
6
+ ``ffprobe`` is on your PATH; pip does not install it.
7
+
8
+ Install and use
9
+ ---------------
10
+
11
+ .. code-block:: console
12
+
13
+ python -m pip install mprobe
14
+
15
+ .. code-block:: python
16
+
17
+ from mprobe import mediainfo
18
+
19
+ info = mediainfo("video.mp4", timeout=30)
20
+ print(info.get("duration")) # seconds, as a string
21
+ print(info.get("format_name"))
22
+
23
+ Accepts strings and pathlib paths. Values are strings; ``TAG`` and
24
+ ``DISPOSITION`` contain dictionaries. Repeated fields use the last stream's
25
+ value, then the container's value. Fields vary by file and may be absent.
26
+ Missing probes raise ``FileNotFoundError``; invalid or missing media raise
27
+ ``subprocess.CalledProcessError`` (details in ``stderr``). A timeout raises
28
+ ``subprocess.TimeoutExpired``.
29
+
30
+ Inspired by `pydub <https://github.com/jiaaro/pydub>`_.
@@ -0,0 +1,23 @@
1
+ The metadata parsing API was inspired by pydub:
2
+ https://github.com/jiaaro/pydub
3
+
4
+ pydub is distributed under the MIT license:
5
+
6
+ Copyright (c) 2011 James Robert, http://jiaaro.com
7
+
8
+ Permission is hereby granted, free of charge, to any person obtaining
9
+ a copy of this software and associated documentation files (the
10
+ "Software"), to deal in the Software without restriction, including
11
+ without limitation the rights to use, copy, modify, merge, publish,
12
+ distribute, sublicense, and/or sell copies of the Software, and to
13
+ permit persons to whom the Software is furnished to do so, subject to
14
+ the following conditions:
15
+ The above copyright notice and this permission notice shall be
16
+ included in all copies or substantial portions of the Software.
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,48 @@
1
+ Metadata-Version: 2.4
2
+ Name: mprobe
3
+ Version: 0.0.1
4
+ Summary: Read video and audio metadata using ffprobe or avprobe
5
+ Author-email: pi11 <webii@pm.me>
6
+ Project-URL: Homepage, https://github.com/pi11/mprobe
7
+ Project-URL: Issues, https://github.com/pi11/mprobe/issues
8
+ Keywords: video,audio,metadata,ffprobe,avprobe
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Topic :: Multimedia :: Sound/Audio
13
+ Classifier: Topic :: Multimedia :: Video
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/x-rst
16
+ License-File: THIRD_PARTY_NOTICES
17
+ Dynamic: license-file
18
+
19
+ mprobe
20
+ ======
21
+
22
+ Read video and audio metadata with Python 3.10+ and ffprobe (or avprobe).
23
+ Install `FFmpeg <https://ffmpeg.org/download.html>`_ separately and ensure
24
+ ``ffprobe`` is on your PATH; pip does not install it.
25
+
26
+ Install and use
27
+ ---------------
28
+
29
+ .. code-block:: console
30
+
31
+ python -m pip install mprobe
32
+
33
+ .. code-block:: python
34
+
35
+ from mprobe import mediainfo
36
+
37
+ info = mediainfo("video.mp4", timeout=30)
38
+ print(info.get("duration")) # seconds, as a string
39
+ print(info.get("format_name"))
40
+
41
+ Accepts strings and pathlib paths. Values are strings; ``TAG`` and
42
+ ``DISPOSITION`` contain dictionaries. Repeated fields use the last stream's
43
+ value, then the container's value. Fields vary by file and may be absent.
44
+ Missing probes raise ``FileNotFoundError``; invalid or missing media raise
45
+ ``subprocess.CalledProcessError`` (details in ``stderr``). A timeout raises
46
+ ``subprocess.TimeoutExpired``.
47
+
48
+ Inspired by `pydub <https://github.com/jiaaro/pydub>`_.
@@ -0,0 +1,10 @@
1
+ README.rst
2
+ THIRD_PARTY_NOTICES
3
+ mprobe.py
4
+ pyproject.toml
5
+ setup.py
6
+ mprobe.egg-info/PKG-INFO
7
+ mprobe.egg-info/SOURCES.txt
8
+ mprobe.egg-info/dependency_links.txt
9
+ mprobe.egg-info/top_level.txt
10
+ tests/test_mprobe.py
@@ -0,0 +1 @@
1
+ mprobe
mprobe-0.0.1/mprobe.py ADDED
@@ -0,0 +1,59 @@
1
+ """Read video/audio metadata using ffprobe or avprobe, inspired by pydub."""
2
+
3
+ import os
4
+ import shutil
5
+ import subprocess
6
+
7
+
8
+ def which(program):
9
+ """Return the executable's path, or None when it is not on PATH."""
10
+ return shutil.which(program)
11
+
12
+
13
+ def get_prober_name():
14
+ """Return an available probe executable, preferring ffprobe."""
15
+ for program in ("ffprobe", "avprobe"):
16
+ executable = which(program)
17
+ if executable:
18
+ return executable
19
+ raise FileNotFoundError("Install FFmpeg (ffprobe) or Libav (avprobe) and add it to PATH")
20
+
21
+
22
+ def mediainfo(filepath, *, timeout=None):
23
+ """Return a dictionary of media metadata with string values.
24
+
25
+ TAG and DISPOSITION fields are nested dictionaries. Repeated fields are
26
+ overwritten by later streams and then container metadata, as in the
27
+ original API. filepath may be a string or a path-like object.
28
+
29
+ Raise FileNotFoundError when no prober is installed, CalledProcessError
30
+ when probing fails (with diagnostics in stderr), or TimeoutExpired when
31
+ the optional timeout in seconds is exceeded.
32
+ """
33
+ prober = get_prober_name()
34
+ args = ["-v", "error", "-show_format", "-show_streams", "-i", os.fsdecode(filepath)]
35
+ options = dict(stdout=subprocess.PIPE, stderr=subprocess.PIPE,
36
+ encoding="utf-8", errors="replace", timeout=timeout)
37
+
38
+ if os.path.basename(prober).lower() in ("avprobe", "avprobe.exe"):
39
+ # Older Libav versions require the legacy key=value writer.
40
+ result = subprocess.run([prober, "-of", "old"] + args, **options)
41
+ if result.returncode:
42
+ result = subprocess.run([prober] + args, check=True, **options)
43
+ else:
44
+ result = subprocess.run([prober] + args, check=True, **options)
45
+
46
+ info = {}
47
+ for line in result.stdout.splitlines():
48
+ key, separator, value = line.partition("=")
49
+ if not separator:
50
+ continue
51
+ namespace, separator, nested_key = key.partition(":")
52
+ if separator:
53
+ nested = info.get(namespace)
54
+ if not isinstance(nested, dict):
55
+ nested = info[namespace] = {}
56
+ nested[nested_key] = value
57
+ else:
58
+ info[key] = value
59
+ return info
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0.3"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "mprobe"
7
+ version = "0.0.1"
8
+ description = "Read video and audio metadata using ffprobe or avprobe"
9
+ readme = "README.rst"
10
+ license-files = ["THIRD_PARTY_NOTICES"]
11
+ requires-python = ">=3.10"
12
+ authors = [{name = "pi11", email = "webii@pm.me"}]
13
+ keywords = ["video", "audio", "metadata", "ffprobe", "avprobe"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3 :: Only",
17
+ "Operating System :: OS Independent",
18
+ "Topic :: Multimedia :: Sound/Audio",
19
+ "Topic :: Multimedia :: Video",
20
+ ]
21
+
22
+ [project.urls]
23
+ Homepage = "https://github.com/pi11/mprobe"
24
+ Issues = "https://github.com/pi11/mprobe/issues"
25
+
26
+ [tool.setuptools]
27
+ py-modules = ["mprobe"]
mprobe-0.0.1/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
mprobe-0.0.1/setup.py ADDED
@@ -0,0 +1,4 @@
1
+ """Compatibility entry point; package metadata lives in pyproject.toml."""
2
+ from setuptools import setup
3
+
4
+ setup()
@@ -0,0 +1,103 @@
1
+ import os
2
+ from pathlib import Path
3
+ import shutil
4
+ import subprocess
5
+ import tempfile
6
+ import unittest
7
+ from unittest.mock import patch
8
+ import wave
9
+
10
+ import mprobe
11
+
12
+
13
+ class ProbeTests(unittest.TestCase):
14
+ def test_missing_path_does_not_raise_key_error(self):
15
+ with patch.dict(os.environ, {}, clear=True):
16
+ self.assertIsNone(mprobe.which("mprobe-nonexistent-probe"))
17
+
18
+ def test_prefers_ffprobe(self):
19
+ with patch("mprobe.which", return_value="/usr/bin/ffprobe") as which:
20
+ self.assertEqual(mprobe.get_prober_name(), "/usr/bin/ffprobe")
21
+ which.assert_called_once_with("ffprobe")
22
+
23
+ def test_avprobe_fallback(self):
24
+ with patch("mprobe.which", side_effect=[None, "/usr/bin/avprobe"]):
25
+ self.assertEqual(mprobe.get_prober_name(), "/usr/bin/avprobe")
26
+
27
+ def test_missing_probe_is_actionable(self):
28
+ with patch("mprobe.which", return_value=None):
29
+ with self.assertRaisesRegex(FileNotFoundError, "Install FFmpeg"):
30
+ mprobe.mediainfo("video.mp4")
31
+
32
+ @patch("mprobe.get_prober_name", return_value="/usr/bin/ffprobe")
33
+ @patch("mprobe.subprocess.run")
34
+ def test_parses_metadata_and_passes_path_safely(self, run, prober):
35
+ run.return_value = subprocess.CompletedProcess([], 0,
36
+ "[STREAM]\r\ncodec_name=h264\r\nTAG:title=a=b:c\r\n"
37
+ "TAG:custom:key=value\r\nDISPOSITION:default=1\r\n"
38
+ "duration=1\r\n[/STREAM]\r\n[FORMAT]\r\nduration=2\r\n", "")
39
+ info = mprobe.mediainfo(Path("-video with spaces.mp4"), timeout=10)
40
+ self.assertEqual(info, {"codec_name": "h264", "TAG": {
41
+ "title": "a=b:c", "custom:key": "value"},
42
+ "DISPOSITION": {"default": "1"}, "duration": "2"})
43
+ self.assertEqual(run.call_args.args[0][-2:], ["-i", "-video with spaces.mp4"])
44
+ self.assertTrue(run.call_args.kwargs["check"])
45
+ self.assertEqual(run.call_args.kwargs["timeout"], 10)
46
+
47
+ @patch("mprobe.get_prober_name", return_value="avprobe")
48
+ @patch("mprobe.subprocess.run")
49
+ def test_legacy_writer_falls_back(self, run, prober):
50
+ run.side_effect = [subprocess.CompletedProcess([], 1, "", "Unknown writer"),
51
+ subprocess.CompletedProcess([], 0, "duration=2\n", "")]
52
+ self.assertEqual(mprobe.mediainfo("audio.wav"), {"duration": "2"})
53
+ self.assertEqual(run.call_args_list[0].args[0][1:3], ["-of", "old"])
54
+ self.assertNotIn("-of", run.call_args.args[0])
55
+ self.assertTrue(run.call_args.kwargs["check"])
56
+
57
+ @patch("mprobe.get_prober_name", return_value="avprobe.exe")
58
+ @patch("mprobe.subprocess.run")
59
+ def test_legacy_writer_success(self, run, prober):
60
+ run.return_value = subprocess.CompletedProcess([], 0, "duration=3\n", "")
61
+ self.assertEqual(mprobe.mediainfo("audio.wav"), {"duration": "3"})
62
+ run.assert_called_once()
63
+
64
+ @patch("mprobe.get_prober_name", return_value="avprobe")
65
+ @patch("mprobe.subprocess.run")
66
+ def test_failed_fallback_raises(self, run, prober):
67
+ error = subprocess.CalledProcessError(1, ["avprobe"], stderr="bad media")
68
+ run.side_effect = [subprocess.CompletedProcess([], 1, "", "bad media"), error]
69
+ with self.assertRaises(subprocess.CalledProcessError) as raised:
70
+ mprobe.mediainfo("broken.mp4")
71
+ self.assertEqual(raised.exception.stderr, "bad media")
72
+
73
+ @patch("mprobe.get_prober_name", return_value="ffprobe")
74
+ @patch("mprobe.subprocess.run", side_effect=subprocess.TimeoutExpired("ffprobe", 1))
75
+ def test_timeout_propagates(self, run, prober):
76
+ with self.assertRaises(subprocess.TimeoutExpired):
77
+ mprobe.mediainfo("video.mp4", timeout=1)
78
+
79
+
80
+ @unittest.skipUnless(shutil.which("ffprobe"), "ffprobe is not installed")
81
+ class IntegrationTests(unittest.TestCase):
82
+ def test_real_audio_and_invalid_inputs(self):
83
+ with tempfile.TemporaryDirectory() as directory:
84
+ audio = Path(directory) / "тест audio.wav"
85
+ with wave.open(str(audio), "wb") as output:
86
+ output.setnchannels(1)
87
+ output.setsampwidth(2)
88
+ output.setframerate(8000)
89
+ output.writeframes(b"\0\0" * 8000)
90
+ info = mprobe.mediainfo(audio, timeout=10)
91
+ self.assertEqual(info["codec_name"], "pcm_s16le")
92
+ self.assertEqual(info["sample_rate"], "8000")
93
+ self.assertEqual(float(info["duration"]), 1.0)
94
+ for path in (Path(directory) / "missing.wav", Path(directory) / "invalid.wav"):
95
+ if path.name == "invalid.wav":
96
+ path.write_text("not media")
97
+ with self.assertRaises(subprocess.CalledProcessError) as raised:
98
+ mprobe.mediainfo(path, timeout=10)
99
+ self.assertTrue(raised.exception.stderr)
100
+
101
+
102
+ if __name__ == "__main__":
103
+ unittest.main()