pyspectools2 1.0.2__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.
@@ -0,0 +1,162 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) [year] [Your Name]
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,107 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyspectools2
3
+ Version: 1.0.2
4
+ Summary: A library for recording and plotting spectrograms from audio data.
5
+ Author-email: "Sviatoslav Z." <slawekzhukovski@gmail.com>
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python :: 3
11
+ Requires-Python: >=3.10
12
+ Requires-Dist: matplotlib
13
+ Requires-Dist: numpy
14
+ Requires-Dist: sounddevice
15
+ Description-Content-Type: text/markdown
16
+
17
+ # Spectrogram Recorder Library
18
+
19
+ A Python library for recording audio, generating spectrograms, and managing session data.
20
+
21
+ ## Features
22
+
23
+ - Record audio from your default input device (`sounddevice`).
24
+ - Plot and save spectrograms (`matplotlib`).
25
+ - Create numbered session folders (`session_1`, `session_2`, ...).
26
+ - Delete the latest session and inspect folder sizes.
27
+ - Cross-platform default save location based on the current user's home directory.
28
+
29
+ ## Installation
30
+
31
+ ```bash
32
+ pip install py-spectrogram-tools
33
+ ```
34
+
35
+ Or from source:
36
+
37
+ ```bash
38
+ git clone https://github.com/Ampter/py-spectrogram-tools
39
+ cd py-spectrogram-tools
40
+ pip install .
41
+ ```
42
+
43
+ ## Dependencies
44
+
45
+ - numpy
46
+ - sounddevice
47
+ - matplotlib
48
+
49
+ ## Import
50
+
51
+ ```python
52
+ import pyspectools as pst
53
+ ```
54
+
55
+ ## API
56
+
57
+ ### `pst.get_default_directory()`
58
+ Returns the default directory for spectrogram sessions:
59
+
60
+ - Windows: `C:\Users\<username>\SOUNDS\spectrograms`
61
+ - macOS: `/Users/<username>/SOUNDS/spectrograms`
62
+ - Linux: `/home/<username>/SOUNDS/spectrograms`
63
+
64
+ ### `pst.create_session_folder(directory=None)`
65
+ Creates a new folder such as `session_5` and returns its path.
66
+
67
+ ### `pst.get_latest_session_folder(directory=None)`
68
+ Returns the highest numbered session folder path, or `None`.
69
+
70
+ ### `pst.record_audio(duration=3, rate=44100, channels=1)`
71
+ Records audio and returns a flattened NumPy array.
72
+
73
+ ### `pst.plot_spectrogram(audio_data, rate=44100)`
74
+ Returns `(fig, ax)` for the generated spectrogram.
75
+
76
+ ### `pst.save_spectrogram(fig, session_folder)`
77
+ Saves a PNG in the target session folder and returns the output file path.
78
+
79
+ ### `pst.delete_latest_session_folder(directory=None)`
80
+ Deletes the latest session folder.
81
+
82
+ ### `pst.get_folder_size(directory=None)`
83
+ Returns folder size in bytes.
84
+
85
+ ### `pst.print_folder_size(directory=None)`
86
+ Prints the total size of the latest session folder.
87
+
88
+ ## Usage Example
89
+
90
+ ```python
91
+ import pyspectools as pst
92
+
93
+ session_folder = pst.create_session_folder()
94
+ audio_data = pst.record_audio(duration=5)
95
+ fig, _ = pst.plot_spectrogram(audio_data)
96
+ output_file = pst.save_spectrogram(fig, session_folder)
97
+
98
+ print(f"Saved spectrogram: {output_file}")
99
+ ```
100
+
101
+ ## Contributing
102
+
103
+ Contributions are welcome.
104
+
105
+ ## License
106
+
107
+ This project is licensed under the MIT License. See `LICENSE` for details.
@@ -0,0 +1,91 @@
1
+ # Spectrogram Recorder Library
2
+
3
+ A Python library for recording audio, generating spectrograms, and managing session data.
4
+
5
+ ## Features
6
+
7
+ - Record audio from your default input device (`sounddevice`).
8
+ - Plot and save spectrograms (`matplotlib`).
9
+ - Create numbered session folders (`session_1`, `session_2`, ...).
10
+ - Delete the latest session and inspect folder sizes.
11
+ - Cross-platform default save location based on the current user's home directory.
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ pip install py-spectrogram-tools
17
+ ```
18
+
19
+ Or from source:
20
+
21
+ ```bash
22
+ git clone https://github.com/Ampter/py-spectrogram-tools
23
+ cd py-spectrogram-tools
24
+ pip install .
25
+ ```
26
+
27
+ ## Dependencies
28
+
29
+ - numpy
30
+ - sounddevice
31
+ - matplotlib
32
+
33
+ ## Import
34
+
35
+ ```python
36
+ import pyspectools as pst
37
+ ```
38
+
39
+ ## API
40
+
41
+ ### `pst.get_default_directory()`
42
+ Returns the default directory for spectrogram sessions:
43
+
44
+ - Windows: `C:\Users\<username>\SOUNDS\spectrograms`
45
+ - macOS: `/Users/<username>/SOUNDS/spectrograms`
46
+ - Linux: `/home/<username>/SOUNDS/spectrograms`
47
+
48
+ ### `pst.create_session_folder(directory=None)`
49
+ Creates a new folder such as `session_5` and returns its path.
50
+
51
+ ### `pst.get_latest_session_folder(directory=None)`
52
+ Returns the highest numbered session folder path, or `None`.
53
+
54
+ ### `pst.record_audio(duration=3, rate=44100, channels=1)`
55
+ Records audio and returns a flattened NumPy array.
56
+
57
+ ### `pst.plot_spectrogram(audio_data, rate=44100)`
58
+ Returns `(fig, ax)` for the generated spectrogram.
59
+
60
+ ### `pst.save_spectrogram(fig, session_folder)`
61
+ Saves a PNG in the target session folder and returns the output file path.
62
+
63
+ ### `pst.delete_latest_session_folder(directory=None)`
64
+ Deletes the latest session folder.
65
+
66
+ ### `pst.get_folder_size(directory=None)`
67
+ Returns folder size in bytes.
68
+
69
+ ### `pst.print_folder_size(directory=None)`
70
+ Prints the total size of the latest session folder.
71
+
72
+ ## Usage Example
73
+
74
+ ```python
75
+ import pyspectools as pst
76
+
77
+ session_folder = pst.create_session_folder()
78
+ audio_data = pst.record_audio(duration=5)
79
+ fig, _ = pst.plot_spectrogram(audio_data)
80
+ output_file = pst.save_spectrogram(fig, session_folder)
81
+
82
+ print(f"Saved spectrogram: {output_file}")
83
+ ```
84
+
85
+ ## Contributing
86
+
87
+ Contributions are welcome.
88
+
89
+ ## License
90
+
91
+ This project is licensed under the MIT License. See `LICENSE` for details.
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "pyspectools2"
7
+ dynamic = ["version"]
8
+ description = "A library for recording and plotting spectrograms from audio data."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.10"
12
+ authors = [
13
+ { name = "Sviatoslav Z.", email = "slawekzhukovski@gmail.com" },
14
+ ]
15
+ classifiers = [
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ "Programming Language :: Python :: 3",
19
+ ]
20
+ dependencies = [
21
+ "matplotlib",
22
+ "numpy",
23
+ "sounddevice",
24
+ ]
25
+
26
+ [tool.hatch.version]
27
+ path = "pyspectools2/__init__.py"
28
+
29
+ [tool.hatch.build.targets.sdist]
30
+ include = [
31
+ "/pyspectools2",
32
+ ]
@@ -0,0 +1,27 @@
1
+ """Public package API for py-spectrogram-tools."""
2
+
3
+ __version__ = "1.0.2"
4
+
5
+ from .spectrogram import (
6
+ create_session_folder,
7
+ delete_latest_session_folder,
8
+ get_default_directory,
9
+ get_folder_size,
10
+ get_latest_session_folder,
11
+ plot_spectrogram,
12
+ print_folder_size,
13
+ record_audio,
14
+ save_spectrogram,
15
+ )
16
+
17
+ __all__ = [
18
+ "create_session_folder",
19
+ "delete_latest_session_folder",
20
+ "get_default_directory",
21
+ "get_folder_size",
22
+ "get_latest_session_folder",
23
+ "plot_spectrogram",
24
+ "print_folder_size",
25
+ "record_audio",
26
+ "save_spectrogram",
27
+ ]
@@ -0,0 +1,146 @@
1
+ import os
2
+ import platform
3
+ import re
4
+ import shutil
5
+ import time
6
+ from pathlib import Path
7
+
8
+ import matplotlib.pyplot as plt
9
+ import sounddevice as sd
10
+
11
+ _SESSION_PATTERN = re.compile(r"^session_(\d+)$")
12
+
13
+
14
+ def get_default_directory() -> str:
15
+ """Return the default directory based on the operating system."""
16
+ system = platform.system().lower()
17
+ home_dir = Path.home()
18
+
19
+ if system in {"windows", "darwin", "linux"}:
20
+ return str(home_dir / "SOUNDS" / "spectrograms")
21
+
22
+ raise OSError("Unsupported operating system")
23
+
24
+
25
+ def _get_session_numbers(directory: str) -> list[int]:
26
+ """Collect valid session numbers from directory entries."""
27
+ session_numbers: list[int] = []
28
+ for entry in os.listdir(directory):
29
+ full_path = os.path.join(directory, entry)
30
+ if not os.path.isdir(full_path):
31
+ continue
32
+
33
+ match = _SESSION_PATTERN.match(entry)
34
+ if match:
35
+ session_numbers.append(int(match.group(1)))
36
+
37
+ return session_numbers
38
+
39
+
40
+ def create_session_folder(directory=None) -> str:
41
+ """Create a new session folder inside the provided directory."""
42
+ if directory is None:
43
+ directory = get_default_directory()
44
+
45
+ os.makedirs(directory, exist_ok=True)
46
+
47
+ next_number = max(_get_session_numbers(directory), default=0) + 1
48
+ while True:
49
+ session_folder = os.path.join(directory, f"session_{next_number}")
50
+ try:
51
+ os.makedirs(session_folder, exist_ok=False)
52
+ print(f"Created new session: {session_folder}")
53
+ return session_folder
54
+ except FileExistsError:
55
+ next_number += 1
56
+
57
+
58
+ def get_latest_session_folder(directory=None) -> str | None:
59
+ """Find the session folder with the highest number and return its path."""
60
+ if directory is None:
61
+ directory = get_default_directory()
62
+
63
+ if not os.path.exists(directory):
64
+ return None
65
+
66
+ session_numbers = _get_session_numbers(directory)
67
+ if not session_numbers:
68
+ return None
69
+
70
+ latest_session = max(session_numbers)
71
+ return os.path.join(directory, f"session_{latest_session}")
72
+
73
+
74
+ def plot_spectrogram(audio_data, rate=44100) -> tuple:
75
+ """Plot the spectrogram of the given audio data."""
76
+ fig, ax = plt.subplots()
77
+ ax.set_title("Spectrogram")
78
+ ax.set_xlabel("Time (s)")
79
+ ax.set_ylabel("Frequency (Hz)")
80
+ ax.specgram(audio_data, NFFT=256, Fs=rate, noverlap=128)
81
+ return fig, ax
82
+
83
+
84
+ def save_spectrogram(fig, session_folder) -> str:
85
+ """Save the generated spectrogram plot to the session folder."""
86
+ timestamp = time.ctime().replace(" ", "_").replace(":", "-")
87
+ filename = os.path.join(session_folder, f"spectrogram_{timestamp}.png")
88
+ fig.savefig(filename)
89
+ plt.close(fig)
90
+ return filename
91
+
92
+
93
+ def record_audio(duration=3, rate=44100, channels=1):
94
+ """Record audio data and return it as a flattened array."""
95
+ print("Starting recording...")
96
+ audio_data = sd.rec(int(rate * duration),
97
+ samplerate=rate, channels=channels)
98
+ sd.wait()
99
+ print("Recording finished.")
100
+ return audio_data.flatten()
101
+
102
+
103
+ def delete_latest_session_folder(directory=None):
104
+ """Delete the latest session folder."""
105
+ if directory is None:
106
+ directory = get_default_directory()
107
+
108
+ latest_session_folder = get_latest_session_folder(directory)
109
+ if latest_session_folder is None:
110
+ print("No session folders found to delete.")
111
+ return
112
+
113
+ try:
114
+ shutil.rmtree(latest_session_folder)
115
+ print(f"Deleted the latest session folder: {latest_session_folder}")
116
+ except Exception as exc:
117
+ print(f"Error deleting the folder: {exc}")
118
+
119
+
120
+ def get_folder_size(directory=None):
121
+ """Calculate the total size of a directory."""
122
+ if directory is None:
123
+ directory = get_default_directory()
124
+
125
+ total_size = 0
126
+ for dirpath, _, filenames in os.walk(directory):
127
+ for filename in filenames:
128
+ file_path = os.path.join(dirpath, filename)
129
+ total_size += os.path.getsize(file_path)
130
+ return total_size
131
+
132
+
133
+ def print_folder_size(directory=None):
134
+ """Print the total size of the latest session folder."""
135
+ if directory is None:
136
+ directory = get_default_directory()
137
+
138
+ latest_session_folder = get_latest_session_folder(directory)
139
+ if latest_session_folder is None:
140
+ print("No session folder found.")
141
+ return
142
+
143
+ total_size = get_folder_size(latest_session_folder)
144
+ print(
145
+ f"Total size of folder {latest_session_folder}: {total_size / (1024 * 1024):.2f} MB"
146
+ )