twat 1.6.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.
twat/__init__.py ADDED
@@ -0,0 +1,77 @@
1
+ """twat plugin host"""
2
+
3
+ import sys
4
+ from importlib import metadata
5
+ from typing import Any
6
+
7
+ __version__ = metadata.version(__name__)
8
+
9
+ # Enable package-style imports for plugins
10
+ __path__ = []
11
+ __package__ = "twat"
12
+
13
+
14
+ class PluginFinder:
15
+ """Finder for twat plugins to enable package-style imports."""
16
+
17
+ @classmethod
18
+ def find_spec(cls, fullname, path, target=None):
19
+ if not fullname.startswith("twat."):
20
+ return None
21
+
22
+ plugin_name = fullname.split(".")[-1]
23
+ try:
24
+ eps = metadata.entry_points(group="twat.plugins")
25
+ for ep in eps:
26
+ if ep.name == plugin_name:
27
+ # Create a spec that will load the plugin module
28
+ from importlib.machinery import ModuleSpec
29
+ from importlib.util import module_from_spec, spec_from_loader
30
+
31
+ plugin_module = ep.load()
32
+
33
+ class Loader:
34
+ @staticmethod
35
+ def create_module(spec):
36
+ return plugin_module
37
+
38
+ @staticmethod
39
+ def exec_module(module):
40
+ pass
41
+
42
+ return ModuleSpec(fullname, Loader())
43
+ except Exception:
44
+ return None
45
+ return None
46
+
47
+
48
+ # Register the finder
49
+ sys.meta_path.insert(0, PluginFinder())
50
+
51
+
52
+ def __getattr__(name: str) -> Any:
53
+ """Dynamic attribute lookup for plugins.
54
+
55
+ To register a plugin, add the following to your pyproject.toml:
56
+
57
+ [project.entry-points."twat.plugins"]
58
+ hatch = "twat_hatch" # Just point to the module
59
+
60
+ Args:
61
+ name: Name of plugin to load
62
+
63
+ Returns:
64
+ Loaded plugin module
65
+
66
+ Raises:
67
+ AttributeError: If plugin cannot be found or loaded
68
+ """
69
+ try:
70
+ eps = metadata.entry_points(group="twat.plugins")
71
+ for ep in eps:
72
+ if ep.name == name:
73
+ return ep.load()
74
+ except Exception as e:
75
+ raise AttributeError(f"Failed to load plugin '{name}': {e}") from e
76
+
77
+ raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
twat/__version__.py ADDED
@@ -0,0 +1,16 @@
1
+ # file generated by setuptools_scm
2
+ # don't change, don't track in version control
3
+ TYPE_CHECKING = False
4
+ if TYPE_CHECKING:
5
+ from typing import Tuple, Union
6
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
7
+ else:
8
+ VERSION_TUPLE = object
9
+
10
+ version: str
11
+ __version__: str
12
+ __version_tuple__: VERSION_TUPLE
13
+ version_tuple: VERSION_TUPLE
14
+
15
+ __version__ = version = '1.6.0'
16
+ __version_tuple__ = version_tuple = (1, 6, 0)
twat/paths.py ADDED
@@ -0,0 +1,233 @@
1
+ #!/usr/bin/env -S uv run
2
+ # /// script
3
+ # dependencies = ["pydantic", "platformdirs"]
4
+ # ///
5
+ """Path management for twat packages.
6
+
7
+ This module provides a centralized way to manage paths for various twat packages.
8
+ It handles path resolution, validation, and creation of directories as needed.
9
+ """
10
+
11
+ import os
12
+ from pathlib import Path
13
+ from typing import Any, Dict, Optional, Self, Union
14
+
15
+ import platformdirs
16
+ import tomli
17
+ from pydantic import BaseModel, Field, field_validator, model_validator
18
+
19
+ # Load default paths from TOML
20
+ PATHS_TOML = Path(__file__).parent / "paths.toml"
21
+ DEFAULT_PATHS = tomli.loads(PATHS_TOML.read_text())
22
+
23
+
24
+ class PathConfig(BaseModel):
25
+ """Base configuration for path settings."""
26
+
27
+ base_dir: Path
28
+ package_dir: Optional[Path] = None
29
+ create_if_missing: bool = True
30
+
31
+ @field_validator("base_dir", "package_dir")
32
+ @classmethod
33
+ def expand_path(cls, v: Optional[Union[str, Path]]) -> Optional[Path]:
34
+ """Expand user and environment variables in paths."""
35
+ if v is None:
36
+ return None
37
+ if isinstance(v, str):
38
+ # Expand both ~ and environment variables
39
+ expanded = os.path.expandvars(os.path.expanduser(v))
40
+ return Path(expanded)
41
+ return v
42
+
43
+ @model_validator(mode="after")
44
+ def validate_and_create_dirs(self) -> Self:
45
+ """Create directories if they don't exist and creation is enabled."""
46
+ if self.create_if_missing:
47
+ self.base_dir.mkdir(parents=True, exist_ok=True)
48
+ if self.package_dir:
49
+ self.package_dir.mkdir(parents=True, exist_ok=True)
50
+ return self
51
+
52
+
53
+ class CacheConfig(PathConfig):
54
+ """Configuration for cache directories."""
55
+
56
+ base_dir: Path = Field(
57
+ default_factory=lambda: Path(platformdirs.user_cache_dir()) / "twat"
58
+ )
59
+
60
+
61
+ class ConfigDirConfig(PathConfig):
62
+ """Configuration for config directories."""
63
+
64
+ base_dir: Path = Field(
65
+ default_factory=lambda: Path(platformdirs.user_config_dir()) / "twat"
66
+ )
67
+
68
+
69
+ class DataDirConfig(PathConfig):
70
+ """Configuration for data directories."""
71
+
72
+ base_dir: Path = Field(
73
+ default_factory=lambda: Path(platformdirs.user_data_dir()) / "twat"
74
+ )
75
+
76
+
77
+ class TempDirConfig(PathConfig):
78
+ """Configuration for temporary directories."""
79
+
80
+ base_dir: Path = Field(
81
+ default_factory=lambda: Path(platformdirs.user_runtime_dir()) / "twat"
82
+ )
83
+
84
+
85
+ class GenAIConfig(PathConfig):
86
+ """Configuration for GenAI-specific paths."""
87
+
88
+ lora_dir: Path = Field(
89
+ default_factory=lambda: Path(platformdirs.user_data_dir()) / "twat/genai/loras"
90
+ )
91
+ model_dir: Path = Field(
92
+ default_factory=lambda: Path(platformdirs.user_data_dir()) / "twat/genai/models"
93
+ )
94
+ output_dir: Path = Field(
95
+ default_factory=lambda: Path.home() / "Pictures/twat_genai"
96
+ )
97
+
98
+ @model_validator(mode="after")
99
+ def validate_and_create_all_dirs(self) -> Self:
100
+ """Create all GenAI directories if enabled."""
101
+ if self.create_if_missing:
102
+ self.base_dir.mkdir(parents=True, exist_ok=True)
103
+ self.lora_dir.mkdir(parents=True, exist_ok=True)
104
+ self.model_dir.mkdir(parents=True, exist_ok=True)
105
+ self.output_dir.mkdir(parents=True, exist_ok=True)
106
+ return self
107
+
108
+
109
+ class LogConfig(PathConfig):
110
+ """Configuration for log directories."""
111
+
112
+ base_dir: Path = Field(
113
+ default_factory=lambda: Path(platformdirs.user_state_dir()) / "twat/logs"
114
+ )
115
+
116
+
117
+ class PathManager:
118
+ """Central manager for all path configurations."""
119
+
120
+ def __init__(
121
+ self,
122
+ package_name: Optional[str] = None,
123
+ config_file: Optional[Union[str, Path]] = None,
124
+ create_dirs: bool = True,
125
+ ) -> None:
126
+ """Initialize path manager.
127
+
128
+ Args:
129
+ package_name: Optional package name for package-specific paths
130
+ config_file: Optional path to custom config file
131
+ create_dirs: Whether to create directories if they don't exist
132
+ """
133
+ self.package_name = package_name
134
+ self.create_dirs = create_dirs
135
+
136
+ # Load config
137
+ if config_file:
138
+ config_path = Path(config_file)
139
+ if not config_path.exists():
140
+ raise FileNotFoundError(f"Config file not found: {config_file}")
141
+ self.config = tomli.loads(config_path.read_text())
142
+ else:
143
+ self.config = DEFAULT_PATHS
144
+
145
+ # Initialize path configurations
146
+ self._init_paths()
147
+
148
+ def _init_paths(self) -> None:
149
+ """Initialize all path configurations."""
150
+
151
+ # Helper to format package-specific paths
152
+ def format_path(path_str: str) -> Optional[Path]:
153
+ if not self.package_name:
154
+ return None
155
+ expanded = os.path.expandvars(os.path.expanduser(path_str))
156
+ return Path(expanded.format(package_name=self.package_name))
157
+
158
+ # Initialize configurations
159
+ self.cache = CacheConfig(
160
+ base_dir=self.config["cache"]["base_dir"],
161
+ package_dir=format_path(self.config["cache"]["package_dir"]),
162
+ create_if_missing=self.create_dirs,
163
+ )
164
+
165
+ self.config_dir = ConfigDirConfig(
166
+ base_dir=self.config["config"]["base_dir"],
167
+ package_dir=format_path(self.config["config"]["package_dir"]),
168
+ create_if_missing=self.create_dirs,
169
+ )
170
+
171
+ self.data = DataDirConfig(
172
+ base_dir=self.config["data"]["base_dir"],
173
+ package_dir=format_path(self.config["data"]["package_dir"]),
174
+ create_if_missing=self.create_dirs,
175
+ )
176
+
177
+ self.temp = TempDirConfig(
178
+ base_dir=self.config["temp"]["base_dir"],
179
+ package_dir=format_path(self.config["temp"]["package_dir"]),
180
+ create_if_missing=self.create_dirs,
181
+ )
182
+
183
+ self.genai = GenAIConfig(
184
+ base_dir=self.config["data"]["base_dir"],
185
+ lora_dir=self.config["genai"]["lora_dir"],
186
+ model_dir=self.config["genai"]["model_dir"],
187
+ output_dir=self.config["genai"]["output_dir"],
188
+ create_if_missing=self.create_dirs,
189
+ )
190
+
191
+ self.logs = LogConfig(
192
+ base_dir=self.config["logs"]["base_dir"],
193
+ package_dir=format_path(self.config["logs"]["package_dir"]),
194
+ create_if_missing=self.create_dirs,
195
+ )
196
+
197
+ def get_path(self, category: str, key: str = "base_dir") -> Path:
198
+ """Get a specific path by category and key.
199
+
200
+ Args:
201
+ category: Path category (cache, config, data, temp, genai, logs)
202
+ key: Path key within the category (base_dir, package_dir, etc.)
203
+
204
+ Returns:
205
+ Resolved path
206
+
207
+ Raises:
208
+ AttributeError: If category or key doesn't exist
209
+ """
210
+ config = getattr(self, category)
211
+ return getattr(config, key)
212
+
213
+ @classmethod
214
+ def for_package(
215
+ cls, package_name: str, config_file: Optional[Union[str, Path]] = None
216
+ ) -> "PathManager":
217
+ """Create a PathManager instance for a specific package.
218
+
219
+ Args:
220
+ package_name: Package name
221
+ config_file: Optional path to custom config file
222
+
223
+ Returns:
224
+ PathManager instance configured for the package
225
+ """
226
+ return cls(package_name=package_name, config_file=config_file)
227
+
228
+ def __repr__(self) -> str:
229
+ """Return string representation of PathManager."""
230
+ package_info = (
231
+ f" for package '{self.package_name}'" if self.package_name else ""
232
+ )
233
+ return f"PathManager{package_info}"
twat/paths.toml ADDED
@@ -0,0 +1,37 @@
1
+ [cache]
2
+ # Base directory for all cache operations
3
+ base_dir = "~/.cache/twat"
4
+ # Directory for storing package-specific cache data
5
+ package_dir = "~/.cache/twat/{package_name}"
6
+
7
+ [config]
8
+ # Base directory for configuration files
9
+ base_dir = "~/.config/twat"
10
+ # Directory for package-specific configuration
11
+ package_dir = "~/.config/twat/{package_name}"
12
+
13
+ [data]
14
+ # Base directory for user data
15
+ base_dir = "~/.local/share/twat"
16
+ # Directory for package-specific data
17
+ package_dir = "~/.local/share/twat/{package_name}"
18
+
19
+ [temp]
20
+ # Base directory for temporary files
21
+ base_dir = "~/tmp/twat"
22
+ # Directory for package-specific temporary files
23
+ package_dir = "~/tmp/twat/{package_name}"
24
+
25
+ [genai]
26
+ # Directory for storing LoRA files
27
+ lora_dir = "~/.local/share/twat/genai/loras"
28
+ # Directory for model weights
29
+ model_dir = "~/.local/share/twat/genai/models"
30
+ # Directory for generated images
31
+ output_dir = "~/Pictures/twat_genai"
32
+
33
+ [logs]
34
+ # Base directory for log files
35
+ base_dir = "~/.local/state/twat/logs"
36
+ # Directory for package-specific logs
37
+ package_dir = "~/.local/state/twat/logs/{package_name}"
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: twat
3
+ Version: 1.6.0
4
+ Project-URL: Documentation, https://github.com/twardoch/twat#readme
5
+ Project-URL: Issues, https://github.com/twardoch/twat/issues
6
+ Project-URL: Source, https://github.com/twardoch/twat
7
+ Author-email: Adam Twardoch <adam+github@twardoch.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Programming Language :: Python
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: Implementation :: CPython
16
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: importlib-metadata>=6.0.0
19
+ Requires-Dist: importlib-resources>=5.0.0
20
+ Requires-Dist: pydantic>=2.0.0
21
+ Requires-Dist: twat
22
+ Requires-Dist: typing-extensions>=4.0.0; python_version < '3.10'
23
+ Provides-Extra: all
24
+ Requires-Dist: mypy>=1.0.0; extra == 'all'
25
+ Requires-Dist: pre-commit>=3.6.0; extra == 'all'
26
+ Requires-Dist: pytest-benchmark[histogram]>=4.0.0; extra == 'all'
27
+ Requires-Dist: pytest-cov>=4.0.0; extra == 'all'
28
+ Requires-Dist: pytest-xdist>=3.5.0; extra == 'all'
29
+ Requires-Dist: pytest>=7.0.0; extra == 'all'
30
+ Requires-Dist: ruff>=0.1.0; extra == 'all'
31
+ Provides-Extra: dev
32
+ Requires-Dist: mypy>=1.0.0; extra == 'dev'
33
+ Requires-Dist: pre-commit>=3.6.0; extra == 'dev'
34
+ Requires-Dist: ruff>=0.1.0; extra == 'dev'
35
+ Provides-Extra: test
36
+ Requires-Dist: pytest-benchmark[histogram]>=4.0.0; extra == 'test'
37
+ Requires-Dist: pytest-cov>=4.0.0; extra == 'test'
38
+ Requires-Dist: pytest-xdist>=3.5.0; extra == 'test'
39
+ Requires-Dist: pytest>=7.0.0; extra == 'test'
40
+ Description-Content-Type: text/markdown
41
+
42
+ # twat
43
+
44
+ (work in progress)
45
+
46
+ ## Features
47
+
48
+ - Plugin system for Python packages
49
+ - Dynamic plugin loading and discovery
50
+ - Modern Python packaging with PEP 621 compliance
51
+ - Type hints and runtime type checking
52
+ - Comprehensive test suite and documentation
53
+ - CI/CD ready configuration
54
+
55
+ ## Installation
56
+
57
+ ```bash
58
+ pip install twat
59
+ ```
60
+
61
+ ## Usage
62
+
63
+ ```python
64
+ import twat
65
+
66
+ # Load a plugin
67
+ plugin = twat.plugin_name
68
+
69
+ # List available plugins
70
+ from importlib.metadata import entry_points
71
+ plugins = entry_points(group="twat.plugins")
72
+ ```
73
+
74
+ ## Development
75
+
76
+ This project uses [Hatch](https://hatch.pypa.io/) for development workflow management.
77
+
78
+ ### Setup Development Environment
79
+
80
+ ```bash
81
+ # Install hatch if you haven't already
82
+ pip install hatch
83
+
84
+ # Create and activate development environment
85
+ hatch shell
86
+
87
+ # Run tests
88
+ hatch run test
89
+
90
+ # Run tests with coverage
91
+ hatch run test-cov
92
+
93
+ # Run linting
94
+ hatch run lint
95
+
96
+ # Format code
97
+ hatch run format
98
+ ```
99
+
100
+ ## License
101
+
102
+ MIT License
@@ -0,0 +1,8 @@
1
+ twat/__init__.py,sha256=AtD9M6zeQ9_npWf6lnTafb4QaOxpR0aaIt6rRe3PqR4,2130
2
+ twat/__version__.py,sha256=Ry70pc5l-IBhT9gahlkNwZPp4g0CzVEWqsat9H-UASY,411
3
+ twat/paths.py,sha256=FCtBe3TDQNeRFXkseg0eMiV9pLv1t8wbPHY2veSiqCg,7597
4
+ twat/paths.toml,sha256=1T3y7-DeQJ9uKYW98WQ6eyYeM3CJv9nsv_IS_zLrrPk,1074
5
+ twat-1.6.0.dist-info/METADATA,sha256=FM__h_AeBYHD41NpBSur5YSKlyTpysGycnLFCJyjChU,2682
6
+ twat-1.6.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
7
+ twat-1.6.0.dist-info/licenses/LICENSE,sha256=owbwpVdTHiU18mRyRzvr1DDQe_Rjs1FCkEdzMGJIU9U,1069
8
+ twat-1.6.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Adam Twardoch
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.