transcript 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.
- transcript/__init__.py +112 -0
- transcript/builders/__init__.py +1 -0
- transcript/builders/html/__init__.py +6 -0
- transcript/builders/html/__init__.pyi +796 -0
- transcript/builders/html/args.py +25 -0
- transcript/builders/html/attrs.py +189 -0
- transcript/builders/html/html.py +81 -0
- transcript/builders/jinja.py +228 -0
- transcript/builders/js.py +280 -0
- transcript/builders/scss.py +393 -0
- transcript/builders/xml.py +166 -0
- transcript/core/__init__.py +14 -0
- transcript/core/ai.py +116 -0
- transcript/core/config.py +29 -0
- transcript/core/container.py +120 -0
- transcript/core/factory.py +180 -0
- transcript/core/fingerprint.py +265 -0
- transcript/core/meta.py +41 -0
- transcript/core/registers.py +53 -0
- transcript/core/stubs.py +19 -0
- transcript/io/__init__.py +12 -0
- transcript/io/file.py +40 -0
- transcript/io/hub.py +191 -0
- transcript/io/json_data.py +185 -0
- transcript/io/load.py +154 -0
- transcript/io/renderer.py +49 -0
- transcript/presets/__init__.py +63 -0
- transcript/presets/forms.py +108 -0
- transcript/presets/html.py +247 -0
- transcript/presets/jinja.py +119 -0
- transcript/presets/scss.py +221 -0
- transcript/presets/tailwind.py +392 -0
- transcript/project.py +223 -0
- transcript/purge.py +171 -0
- transcript/py.typed +0 -0
- transcript-0.4.0.dist-info/METADATA +201 -0
- transcript-0.4.0.dist-info/RECORD +40 -0
- transcript-0.4.0.dist-info/WHEEL +5 -0
- transcript-0.4.0.dist-info/licenses/LICENSE +21 -0
- transcript-0.4.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, List
|
|
4
|
+
|
|
5
|
+
from transcript.core.container import ContainerBase
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def normalize_attr_name(name: str) -> str:
|
|
9
|
+
aliases = {
|
|
10
|
+
'class_': 'class',
|
|
11
|
+
'for_': 'for',
|
|
12
|
+
'id_': 'id',
|
|
13
|
+
'http_equiv': 'http-equiv',
|
|
14
|
+
'accept_charset': 'accept-charset',
|
|
15
|
+
'charset': 'charset',
|
|
16
|
+
}
|
|
17
|
+
if name in aliases:
|
|
18
|
+
return aliases[name]
|
|
19
|
+
if name.endswith('_'):
|
|
20
|
+
return name[:-1].replace('_', '-')
|
|
21
|
+
return name.replace('_', '-')
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class XMLArg:
|
|
25
|
+
"""Argument znacznika w formacie XML/HTML: ``name="value"``."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, name: str, *values: Any, separator: str = ' '):
|
|
28
|
+
self.name = normalize_attr_name(name)
|
|
29
|
+
self.separator = separator
|
|
30
|
+
self._boolean = len(values) == 0
|
|
31
|
+
self.values: List[Any] = []
|
|
32
|
+
for value in values:
|
|
33
|
+
self._extend(value)
|
|
34
|
+
|
|
35
|
+
def _extend(self, value: Any) -> None:
|
|
36
|
+
if value is None:
|
|
37
|
+
return
|
|
38
|
+
if isinstance(value, (list, tuple)) and not isinstance(value, (str, bytes)):
|
|
39
|
+
for item in value:
|
|
40
|
+
self._extend(item)
|
|
41
|
+
return
|
|
42
|
+
self.values.append(value)
|
|
43
|
+
if value is not True:
|
|
44
|
+
self._boolean = False
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def value(self) -> str | bool | None:
|
|
48
|
+
if self._boolean:
|
|
49
|
+
return True
|
|
50
|
+
rendered = [str(item) for item in self.values if item is not True and item is not False]
|
|
51
|
+
if not rendered:
|
|
52
|
+
return True if True in self.values else None
|
|
53
|
+
return self.separator.join(rendered)
|
|
54
|
+
|
|
55
|
+
def merge(self, other: XMLArg) -> None:
|
|
56
|
+
if other._boolean:
|
|
57
|
+
self._boolean = self._boolean or not self.values
|
|
58
|
+
return
|
|
59
|
+
self._boolean = False
|
|
60
|
+
self.values.extend(other.values)
|
|
61
|
+
|
|
62
|
+
def __bool__(self) -> bool:
|
|
63
|
+
if self._boolean:
|
|
64
|
+
return False not in self.values
|
|
65
|
+
if False in self.values and len(self.values) == 1:
|
|
66
|
+
return False
|
|
67
|
+
return any(item is not None and item is not False for item in self.values)
|
|
68
|
+
|
|
69
|
+
def build(self) -> str:
|
|
70
|
+
if not self:
|
|
71
|
+
return ''
|
|
72
|
+
if self._boolean or self.values == [True]:
|
|
73
|
+
return f'{self.name}="{self.name}"'
|
|
74
|
+
raw = self.separator.join(
|
|
75
|
+
str(item) for item in self.values if item is not True and item is not False
|
|
76
|
+
)
|
|
77
|
+
escaped = raw.replace('&', '&').replace('"', '"')
|
|
78
|
+
return f'{self.name}="{escaped}"'
|
|
79
|
+
|
|
80
|
+
def __repr__(self) -> str:
|
|
81
|
+
return f'{self.__class__.__name__}({self.build()!r})'
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
XMLAttr = XMLArg
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class XMLTagBase(ContainerBase):
|
|
88
|
+
|
|
89
|
+
self_closing: bool = True
|
|
90
|
+
cl: str = ' /'
|
|
91
|
+
|
|
92
|
+
def __init__(self, *contents: Any, **kwargs: Any):
|
|
93
|
+
self.attrs: List[XMLArg] = []
|
|
94
|
+
super().__init__(*contents)
|
|
95
|
+
for key, value in kwargs.items():
|
|
96
|
+
self._add_arg(XMLArg(key, value))
|
|
97
|
+
|
|
98
|
+
def _inject(self, data: Any) -> None:
|
|
99
|
+
inject_into = getattr(data, 'inject_into', None)
|
|
100
|
+
if callable(inject_into):
|
|
101
|
+
inject_into(self)
|
|
102
|
+
return
|
|
103
|
+
if isinstance(data, XMLArg):
|
|
104
|
+
self._add_arg(data)
|
|
105
|
+
return
|
|
106
|
+
if isinstance(data, dict):
|
|
107
|
+
for key, value in data.items():
|
|
108
|
+
self._add_arg(XMLArg(key, value))
|
|
109
|
+
return
|
|
110
|
+
if isinstance(data, tuple):
|
|
111
|
+
if (
|
|
112
|
+
len(data) == 2
|
|
113
|
+
and isinstance(data[0], str)
|
|
114
|
+
and not isinstance(data[0], ContainerBase)
|
|
115
|
+
):
|
|
116
|
+
self._add_arg(XMLArg(data[0], data[1]))
|
|
117
|
+
return
|
|
118
|
+
for item in data:
|
|
119
|
+
self._inject(item)
|
|
120
|
+
return
|
|
121
|
+
super()._inject(data)
|
|
122
|
+
|
|
123
|
+
def _add_arg(self, arg: XMLArg) -> None:
|
|
124
|
+
if not arg:
|
|
125
|
+
return
|
|
126
|
+
for existing in self.attrs:
|
|
127
|
+
if existing.name == arg.name:
|
|
128
|
+
existing.merge(arg)
|
|
129
|
+
return
|
|
130
|
+
self.attrs.append(arg)
|
|
131
|
+
|
|
132
|
+
def _open_tag(self) -> str:
|
|
133
|
+
open_tag = f'<{self.name}'
|
|
134
|
+
attrs = [attr.build() for attr in self.attrs if attr]
|
|
135
|
+
if attrs:
|
|
136
|
+
open_tag += ' ' + self.separator.join(attrs)
|
|
137
|
+
return open_tag
|
|
138
|
+
|
|
139
|
+
def build(self, depth: int = 0) -> str:
|
|
140
|
+
indent = self._indent(depth)
|
|
141
|
+
open_tag = self._open_tag()
|
|
142
|
+
|
|
143
|
+
if self.self_closing and not self.content:
|
|
144
|
+
return f'{indent}{open_tag}{self.cl}>'
|
|
145
|
+
|
|
146
|
+
open_tag += '>'
|
|
147
|
+
close_tag = f'</{self.name}>'
|
|
148
|
+
|
|
149
|
+
if not self.content:
|
|
150
|
+
return f'{indent}{open_tag}{close_tag}'
|
|
151
|
+
|
|
152
|
+
if (
|
|
153
|
+
len(self.content) == 1
|
|
154
|
+
and not isinstance(self.content[0], ContainerBase)
|
|
155
|
+
and '\n' not in str(self.content[0])
|
|
156
|
+
):
|
|
157
|
+
return f'{indent}{open_tag}{self.content[0]}{close_tag}'
|
|
158
|
+
|
|
159
|
+
inner_parts = [self._render_child(element, depth + 1) for element in self.content]
|
|
160
|
+
inner = '\n'.join(part for part in inner_parts if part != '')
|
|
161
|
+
return f'{indent}{open_tag}\n{inner}\n{indent}{close_tag}'
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class XMLTag(XMLTagBase):
|
|
165
|
+
|
|
166
|
+
name: str = 'tag'
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from transcript.core.container import ContainerBase, Fragment
|
|
2
|
+
from transcript.core.config import Config, get_config, init
|
|
3
|
+
from transcript.core.fingerprint import (
|
|
4
|
+
content_id,
|
|
5
|
+
element_code,
|
|
6
|
+
element_prime,
|
|
7
|
+
short_uuid,
|
|
8
|
+
structural_fingerprint,
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
'ContainerBase', 'Fragment', 'Config', 'get_config', 'init',
|
|
13
|
+
'content_id', 'element_code', 'element_prime', 'short_uuid', 'structural_fingerprint',
|
|
14
|
+
]
|
transcript/core/ai.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
from langchain_openai import ChatOpenAI
|
|
2
|
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
|
3
|
+
from langchain_ollama import ChatOllama
|
|
4
|
+
from langchain.tools import StructuredTool
|
|
5
|
+
from langchain_core.messages import HumanMessage, SystemMessage, AIMessage
|
|
6
|
+
from langchain.agents import initialize_agent, AgentType
|
|
7
|
+
from typing import List, TypedDict, Dict, get_type_hints
|
|
8
|
+
from collections.abc import Callable
|
|
9
|
+
from pydantic import BaseModel
|
|
10
|
+
from functools import partial, update_wrapper
|
|
11
|
+
from copy import deepcopy
|
|
12
|
+
import inspect
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ToolConfig(TypedDict):
|
|
16
|
+
fn: Callable
|
|
17
|
+
args_schema: BaseModel
|
|
18
|
+
properties: Dict
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
MODEL_VENDOR_MAP: Dict[str, str] = {
|
|
22
|
+
'gpt-': 'openai',
|
|
23
|
+
'o1-': 'openai',
|
|
24
|
+
'o3-': 'openai',
|
|
25
|
+
'o4-': 'openai',
|
|
26
|
+
'openai-': 'openai',
|
|
27
|
+
'codex-': 'openai',
|
|
28
|
+
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
DEFAULT_MODELS = {
|
|
32
|
+
'openai': 'gpt-5-nano',
|
|
33
|
+
'google': 'gemini-2.5-flash'
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class LLM:
|
|
38
|
+
|
|
39
|
+
def __init__(self, model:str='openai', temperature:float=0.0, max_tokens:int=256, tools:List[ToolConfig]=[]):
|
|
40
|
+
model_lower:str = model.lower()
|
|
41
|
+
_vendor:str = ''
|
|
42
|
+
_model:str = ''
|
|
43
|
+
if model in DEFAULT_MODELS:
|
|
44
|
+
_vendor=model
|
|
45
|
+
_model=DEFAULT_MODELS[model]
|
|
46
|
+
else:
|
|
47
|
+
for prefix, vendor in MODEL_VENDOR_MAP.items():
|
|
48
|
+
if model_lower.startswith(prefix):
|
|
49
|
+
_vendor=vendor
|
|
50
|
+
_model=model
|
|
51
|
+
break
|
|
52
|
+
else:
|
|
53
|
+
raise ValueError(f'Unknown vendor for model: {model}')
|
|
54
|
+
|
|
55
|
+
match _vendor:
|
|
56
|
+
case 'ollama':
|
|
57
|
+
self.llm = ChatOllama(model=_model, base_url='http://localhost:11434', temperature=temperature)
|
|
58
|
+
case 'google':
|
|
59
|
+
self.llm = ChatGoogleGenerativeAI(model=_model, temperature=0, max_tokens=max_tokens)
|
|
60
|
+
case _:
|
|
61
|
+
self.llm = ChatOpenAI(model=_model, temperature=temperature, max_completion_tokens=max_tokens)
|
|
62
|
+
|
|
63
|
+
self.tools:list[StructuredTool] = []
|
|
64
|
+
|
|
65
|
+
for tool in tools:
|
|
66
|
+
self.add_tool(**tool)
|
|
67
|
+
|
|
68
|
+
self.system_message:str|SystemMessage = ''
|
|
69
|
+
|
|
70
|
+
def _clean_memory(self):
|
|
71
|
+
self.messages = []
|
|
72
|
+
self.messages.append(self.system_message)
|
|
73
|
+
|
|
74
|
+
def add_system_messages(self, *messages:str):
|
|
75
|
+
self.system_message = SystemMessage(content='\n'.join(messages))
|
|
76
|
+
self._clean_memory()
|
|
77
|
+
|
|
78
|
+
def add_tool(self, fn:Callable, args_schema:BaseModel|None=None, properties:Dict={}):
|
|
79
|
+
if properties:
|
|
80
|
+
sig = inspect.signature(fn)
|
|
81
|
+
hints = get_type_hints(fn)
|
|
82
|
+
for key, val in properties.items():
|
|
83
|
+
if key not in sig.parameters:
|
|
84
|
+
raise TypeError(f"Argument '{key}' nie istnieje w funkcji '{fn.__name__}'.")
|
|
85
|
+
if key in hints:
|
|
86
|
+
expected_type = hints[key]
|
|
87
|
+
if not isinstance(val, expected_type):
|
|
88
|
+
raise TypeError(
|
|
89
|
+
f"Argument '{key}' ma wartość typu {type(val).__name__}, "
|
|
90
|
+
f"ale oczekiwano {expected_type.__name__}"
|
|
91
|
+
)
|
|
92
|
+
func = partial(fn, **deepcopy(properties))
|
|
93
|
+
update_wrapper(func, fn)
|
|
94
|
+
else:
|
|
95
|
+
func = fn
|
|
96
|
+
if args_schema:
|
|
97
|
+
self.tools.append(StructuredTool.from_function(func, args_schema=args_schema.model_json_schema()))
|
|
98
|
+
else:
|
|
99
|
+
self.tools.append(StructuredTool.from_function(func))
|
|
100
|
+
|
|
101
|
+
def add_human_message(self, message:str):
|
|
102
|
+
self.messages.append(HumanMessage(content=message))
|
|
103
|
+
|
|
104
|
+
def query(self, message:str):
|
|
105
|
+
return self.llm.invoke([self.system_message, message])
|
|
106
|
+
|
|
107
|
+
def chat(self, message:str):
|
|
108
|
+
if message != '/bye':
|
|
109
|
+
self.add_human_message(message)
|
|
110
|
+
ai_response = AIMessage(self.llm.invoke(self.messages).content)
|
|
111
|
+
self.messages.append(ai_response)
|
|
112
|
+
return ai_response
|
|
113
|
+
return 'bye'
|
|
114
|
+
|
|
115
|
+
def create_agent(self, agent_type:AgentType = AgentType.OPENAI_FUNCTIONS, verbose:bool=True):
|
|
116
|
+
return initialize_agent(llm=self.llm, agent=agent_type, tools=self.tools, verbose=verbose, handle_parsing_errors=True)
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
class Config:
|
|
2
|
+
def __init__(
|
|
3
|
+
self,
|
|
4
|
+
templates_dir: str = 'templates',
|
|
5
|
+
scss_dir: str = 'scss',
|
|
6
|
+
js_dir: str = 'js',
|
|
7
|
+
static_dir: str = 'static',
|
|
8
|
+
css_dir: str = 'css',
|
|
9
|
+
graphics_dir: str = 'graphics',
|
|
10
|
+
):
|
|
11
|
+
self.templates_dir = templates_dir
|
|
12
|
+
self.scss_dir = scss_dir
|
|
13
|
+
self.js_dir = js_dir
|
|
14
|
+
self.static_dir = static_dir
|
|
15
|
+
self.css_dir = css_dir
|
|
16
|
+
self.graphics_dir = graphics_dir
|
|
17
|
+
self.context = {}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
_current_config:Config | None = None
|
|
21
|
+
|
|
22
|
+
def init(config: Config):
|
|
23
|
+
global _current_config
|
|
24
|
+
_current_config = config
|
|
25
|
+
|
|
26
|
+
def get_config() -> Config:
|
|
27
|
+
if _current_config is None:
|
|
28
|
+
raise RuntimeError('Config not initialized')
|
|
29
|
+
return _current_config
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, List
|
|
6
|
+
|
|
7
|
+
from transcript.core.fingerprint import content_id, short_uuid, structural_fingerprint
|
|
8
|
+
from transcript.core.meta import ContainerMeta, ContainerProtocol
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ContainerBase(ABC, metaclass=ContainerMeta):
|
|
12
|
+
"""Blok kodu. ``build()`` zwraca tekst, ``<<`` wstrzykuje bloki, ``>>`` eksportuje.
|
|
13
|
+
|
|
14
|
+
``uuid`` to deterministyczny odcisk treści (nie losowy):
|
|
15
|
+
atomowy element → 2 znaki; z zawartością → kod z mieszania liczb pierwszych.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
name: str = ''
|
|
19
|
+
_TAB: str = ' '
|
|
20
|
+
separator: str = ' '
|
|
21
|
+
|
|
22
|
+
def __init__(self, *contents: Any, **kwargs: Any):
|
|
23
|
+
self.content: List[Any] = []
|
|
24
|
+
for item in contents:
|
|
25
|
+
self._inject(item)
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def uuid(self) -> str:
|
|
29
|
+
return content_id(self)
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def fingerprint(self) -> int:
|
|
33
|
+
return structural_fingerprint(self)
|
|
34
|
+
|
|
35
|
+
def _inject(self, data: Any) -> None:
|
|
36
|
+
if data is None:
|
|
37
|
+
return
|
|
38
|
+
inject_into = getattr(data, 'inject_into', None)
|
|
39
|
+
if callable(inject_into):
|
|
40
|
+
inject_into(self)
|
|
41
|
+
return
|
|
42
|
+
if isinstance(data, dict):
|
|
43
|
+
for key, value in data.items():
|
|
44
|
+
self._inject_mapping(key, value)
|
|
45
|
+
return
|
|
46
|
+
if isinstance(data, list):
|
|
47
|
+
for item in data:
|
|
48
|
+
self._inject(item)
|
|
49
|
+
return
|
|
50
|
+
self.content.append(data)
|
|
51
|
+
|
|
52
|
+
def _inject_mapping(self, key: Any, value: Any) -> None:
|
|
53
|
+
self.content.append((key, value))
|
|
54
|
+
|
|
55
|
+
def _indent(self, depth: int) -> str:
|
|
56
|
+
return self._TAB * depth
|
|
57
|
+
|
|
58
|
+
def _render_child(self, element: Any, depth: int) -> str:
|
|
59
|
+
if isinstance(element, ContainerBase):
|
|
60
|
+
return element.build(depth=depth)
|
|
61
|
+
build = getattr(element, 'build', None)
|
|
62
|
+
if callable(build):
|
|
63
|
+
try:
|
|
64
|
+
return build(depth=depth)
|
|
65
|
+
except TypeError:
|
|
66
|
+
return f'{self._indent(depth)}{build()}'
|
|
67
|
+
return f'{self._indent(depth)}{element}'
|
|
68
|
+
|
|
69
|
+
@abstractmethod
|
|
70
|
+
def build(self, depth: int = 0) -> str:
|
|
71
|
+
return ''
|
|
72
|
+
|
|
73
|
+
def __lshift__(self, data: Any) -> ContainerBase:
|
|
74
|
+
self._inject(data)
|
|
75
|
+
return self
|
|
76
|
+
|
|
77
|
+
def __rshift__(self, dest: Any) -> str:
|
|
78
|
+
code = self.build()
|
|
79
|
+
if dest is str or dest is None:
|
|
80
|
+
return code
|
|
81
|
+
export_from = getattr(dest, 'export_from', None)
|
|
82
|
+
if callable(export_from):
|
|
83
|
+
return export_from(self, code)
|
|
84
|
+
path = Path(dest)
|
|
85
|
+
if path.parent.as_posix() not in ('', '.'):
|
|
86
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
87
|
+
path.write_text(code, encoding='utf-8')
|
|
88
|
+
return code
|
|
89
|
+
|
|
90
|
+
def __str__(self) -> str:
|
|
91
|
+
return self.build()
|
|
92
|
+
|
|
93
|
+
def __repr__(self) -> str:
|
|
94
|
+
return (
|
|
95
|
+
f'{self.__class__.__name__}(uuid={self.uuid!r}, '
|
|
96
|
+
f'name={self.name!r}, children={len(self.content)})'
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
def __eq__(self, value: object) -> bool:
|
|
100
|
+
if isinstance(value, ContainerBase):
|
|
101
|
+
return self.build() == value.build()
|
|
102
|
+
if isinstance(value, str):
|
|
103
|
+
return self.build() == value
|
|
104
|
+
return NotImplemented
|
|
105
|
+
|
|
106
|
+
def __bool__(self) -> bool:
|
|
107
|
+
return True
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class Fragment(ContainerBase):
|
|
111
|
+
"""Blok bez własnego znacznika — skleja potomków w jedną treść."""
|
|
112
|
+
|
|
113
|
+
name: str = 'fragment'
|
|
114
|
+
|
|
115
|
+
def build(self, depth: int = 0) -> str:
|
|
116
|
+
parts = [self._render_child(element, depth) for element in self.content]
|
|
117
|
+
return '\n'.join(part for part in parts if part != '')
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
__all__ = ['ContainerBase', 'Fragment', 'short_uuid']
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
from transcript.core.container import ContainerBase
|
|
2
|
+
from transcript.core.meta import ContainerProtocol
|
|
3
|
+
from typing import List, Dict, Any, Type, Set, TypedDict, get_args, get_origin
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ContainerConfigBase(TypedDict):
|
|
9
|
+
|
|
10
|
+
base: Type[ContainerBase]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ContainerConfig(ContainerConfigBase, total=False):
|
|
14
|
+
|
|
15
|
+
doc:str
|
|
16
|
+
attrs:Dict[str, type]
|
|
17
|
+
unit:str
|
|
18
|
+
supported: List[str]
|
|
19
|
+
self_closing: bool
|
|
20
|
+
system_name: str
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Stubs:
|
|
24
|
+
|
|
25
|
+
def __init__(self, pyi_path: Path, pyi_file_name: str, write_init: bool = False):
|
|
26
|
+
self.init_imports: Dict[str, Set[str]] = {}
|
|
27
|
+
self.make_init: bool = False
|
|
28
|
+
stub_dir = pyi_path if pyi_path.is_dir() else pyi_path.parent
|
|
29
|
+
self.pyi_path = stub_dir / f'{pyi_file_name}.pyi'
|
|
30
|
+
if pyi_file_name == '__init__' and write_init:
|
|
31
|
+
self.make_init = True
|
|
32
|
+
init_import_path: re.Match | None = re.search(r'src\\[\w\\]+', str(pyi_path))
|
|
33
|
+
if init_import_path is not None:
|
|
34
|
+
init_import_path = init_import_path.group()
|
|
35
|
+
self.init_imports[str(init_import_path).replace('\\', '.')] = set()
|
|
36
|
+
self.init_path = stub_dir / f'{pyi_file_name}.py'
|
|
37
|
+
self.imports:Dict[str, Set[str]] = {}
|
|
38
|
+
self.classes:Dict[str, Dict[str, str|Dict[str, type]]] = {}
|
|
39
|
+
self._classes:Set[str] = set()
|
|
40
|
+
|
|
41
|
+
def add(self, _class:type, parent:type|None = None, doc:str = '', attrs:Dict[str,type]={}):
|
|
42
|
+
import_class:type = _class if parent is None else parent
|
|
43
|
+
key = str(import_class.__module__).replace('.', '_')
|
|
44
|
+
if key not in self.imports:
|
|
45
|
+
self.imports[key] = set()
|
|
46
|
+
self.imports[key].add(import_class.__name__)
|
|
47
|
+
if parent:
|
|
48
|
+
self.classes[_class.__name__] = {'parent': f'{parent.__name__}', 'doc': doc, 'attrs': attrs}
|
|
49
|
+
self._classes.add(_class.__name__)
|
|
50
|
+
|
|
51
|
+
def _is_abstract(self, name:str):
|
|
52
|
+
return name.endswith(('Base', 'Abstract', 'Mixin')) and name not in ("Base", "Abstract")
|
|
53
|
+
|
|
54
|
+
def generate(self):
|
|
55
|
+
stub_lines:List[str] = []
|
|
56
|
+
init_lines:List[str] = []
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
for module, import_classes in self.imports.items():
|
|
60
|
+
stub_lines.append(f'from {module.replace('_', '.')} import ' + ', '.join(import_classes))
|
|
61
|
+
if self.make_init:
|
|
62
|
+
_cls_list:List[str] = [_cls for _cls in import_classes if not self._is_abstract(_cls)]
|
|
63
|
+
if _cls_list:
|
|
64
|
+
init_lines.append(f'from {module.replace('_', '.')} import ' + ', '.join(_cls_list))
|
|
65
|
+
|
|
66
|
+
stub_lines.extend(['', ''])
|
|
67
|
+
if self.make_init:
|
|
68
|
+
init_lines.extend(['', ''])
|
|
69
|
+
|
|
70
|
+
for class_name, data in self.classes.items():
|
|
71
|
+
_doc:str = str(data['doc'])
|
|
72
|
+
_attrs:str = '\n\t'.join(f'{name}:{_type._name}' for name, _type in data['attrs'].items()) if isinstance(data['attrs'], dict) else '...'
|
|
73
|
+
stub_lines.append(f'class {class_name}({data['parent']}):\n\t"""\n\t{'\n\t'.join(_doc.split('\n'))}\n\t"""\n\t{_attrs}\n\n')
|
|
74
|
+
self._classes.add(class_name)
|
|
75
|
+
|
|
76
|
+
stub_lines.append('__all__ = [' + ', '.join([f'\"{_class}\"' for _class in self._classes]) + ']')
|
|
77
|
+
|
|
78
|
+
Path(self.pyi_path).write_text("\n".join(stub_lines) + "\n", encoding="utf-8")
|
|
79
|
+
|
|
80
|
+
if self.make_init:
|
|
81
|
+
init_lines.append('__all__ = [' + ', '.join([f'\"{_class}\"' for _class in self._classes if not self._is_abstract(_class)]) + ']')
|
|
82
|
+
Path(self.init_path).write_text("\n".join(init_lines) + "\n", encoding="utf-8")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class ContainerFactory:
|
|
86
|
+
"""
|
|
87
|
+
Fabryka klas pochodnych od ContainerBase jako główny argument przyjmuje słownik products_data,
|
|
88
|
+
który jako klucze przyjmuje wartość name przyszłych contenerów. Ze względu na to, że kontenerów została opracowana przede wszystkim
|
|
89
|
+
na potrzeby generowania plików frontendowych klucze powinny mieć myślniki zamiast spacji.
|
|
90
|
+
Fabryka automatycznie na podstawie klucza wygeneruje nazwę nowej klasy zgodną z zasadami nazewnictwa obowiązującymi w języku Python.
|
|
91
|
+
Wartości słownika products_data to również słowniki, które muszą zawierać klucz base, do którego jest przypisana
|
|
92
|
+
klasa bazowa potomna po ContainerBase zawierająca zdefiniowaną metodę build. Pozostałe klucze są opcjonalne i powinny zawierać atrybuty dla nowej klasy.
|
|
93
|
+
Ze względu na analizę statyczną działającą w większości edytorów kodu wszelkie atrybuty powinny być zdefiniowane w klasie bazowej,
|
|
94
|
+
a wartości przekazywane w słowniku tylko ustawiać ich wartość.
|
|
95
|
+
Klasa bazowa nie powinna zawierać metody __init__ ponieważ to może wpłynąć na prawidłowe działanie fabryki.
|
|
96
|
+
Fabryka domyślnie modyfikuje metodę __init__ klasy ContainerBase.
|
|
97
|
+
Fabryka może automatycznie wygenerować plik pyi potrzebny do prawidłowego rozpoznawania wygenerowanych klas przez analizę statyczną.
|
|
98
|
+
W tym celu należy zdefiniować ścieżkę dla pliku pyi (stubs).
|
|
99
|
+
Jeśli prócz dynamicznie tworzonych przez fabrykę klas potrzeba w pliku pyi inne klasy to należy je dodać w argumencie extra_classes.
|
|
100
|
+
Jeśli w atrybutach zostanie zdefiniowa dokumentacja w atrybucie __doc__ zostanie ona automatycznie dodana dla analizy statycznej w stubs
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
def __init__(
|
|
104
|
+
self,
|
|
105
|
+
products_data: Dict[str, ContainerConfig] = {},
|
|
106
|
+
pyi_path: str | Path | None = None,
|
|
107
|
+
pyi_file_name: str = '__init__',
|
|
108
|
+
extra_classes: List[type] = [],
|
|
109
|
+
write_init: bool = False,
|
|
110
|
+
):
|
|
111
|
+
self._stubs: bool = False
|
|
112
|
+
if pyi_path:
|
|
113
|
+
self._stubs = True
|
|
114
|
+
self.stubs = Stubs(Path(pyi_path), pyi_file_name, write_init=write_init)
|
|
115
|
+
for _class in extra_classes:
|
|
116
|
+
self.stubs.add(_class)
|
|
117
|
+
self.products_data: Dict[str, ContainerConfig] = products_data
|
|
118
|
+
self.generated_classes: Dict[str, type] = {}
|
|
119
|
+
self._validate_config()
|
|
120
|
+
|
|
121
|
+
def make(self) -> Dict[str, type]:
|
|
122
|
+
|
|
123
|
+
for name, config in self.products_data.items():
|
|
124
|
+
_name:str = config['system_name'] if 'system_name' in config else name
|
|
125
|
+
class_name = ''.join([name_part.capitalize() for name_part in _name.split('-')])
|
|
126
|
+
base = config['base']
|
|
127
|
+
doc:str = ''
|
|
128
|
+
def __new_init__(self, *contents:str|ContainerProtocol, **kwargs:Any):
|
|
129
|
+
base.__init__(self, *contents, **kwargs)
|
|
130
|
+
if '__post_init__' in self.__dict__:
|
|
131
|
+
self.__post_init__()
|
|
132
|
+
namespace: dict[str, Any] = {"name": name, "__init__": __new_init__}
|
|
133
|
+
if 'doc' in config:
|
|
134
|
+
doc = config['doc']
|
|
135
|
+
namespace['__doc__'] = doc
|
|
136
|
+
_attrs:Dict[str, type] = config['attrs'] if 'attrs' in config else {}
|
|
137
|
+
for key, value in config.items():
|
|
138
|
+
if key not in ('name', 'base', 'doc', '__init__', 'attrs'):
|
|
139
|
+
namespace[key] = value
|
|
140
|
+
new_class = type(class_name, (base, ), namespace)
|
|
141
|
+
|
|
142
|
+
self.generated_classes[class_name] = new_class
|
|
143
|
+
if self._stubs:
|
|
144
|
+
self.stubs.add(new_class, base, doc, _attrs)
|
|
145
|
+
if self._stubs:
|
|
146
|
+
self.stubs.generate()
|
|
147
|
+
return self.generated_classes
|
|
148
|
+
|
|
149
|
+
def _validate_config(self):
|
|
150
|
+
annotations = ContainerConfig.__annotations__
|
|
151
|
+
|
|
152
|
+
for class_name, config in self.products_data.items():
|
|
153
|
+
for key, expected_type in annotations.items():
|
|
154
|
+
if key not in config:
|
|
155
|
+
continue
|
|
156
|
+
|
|
157
|
+
value = config[key]
|
|
158
|
+
|
|
159
|
+
# Obsługa Type[ContainerBase]
|
|
160
|
+
if expected_type == type[ContainerBase] or get_origin(expected_type) is type:
|
|
161
|
+
if not isinstance(value, type) or not issubclass(value, ContainerBase):
|
|
162
|
+
raise TypeError(
|
|
163
|
+
f"Config dla '{class_name}': '{key}' musi być klasą potomną ContainerBase"
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
# Obsługa list[str]
|
|
167
|
+
elif get_origin(expected_type) is list:
|
|
168
|
+
arg = get_args(expected_type)[0]
|
|
169
|
+
if not isinstance(value, list) or not all(isinstance(v, arg) for v in value):
|
|
170
|
+
raise TypeError(
|
|
171
|
+
f"Config dla '{class_name}': '{key}' musi być listą {arg.__name__}"
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
# Proste typy (str, int, itp.)
|
|
175
|
+
else:
|
|
176
|
+
if not isinstance(value, expected_type):
|
|
177
|
+
raise TypeError(
|
|
178
|
+
f"Config dla '{class_name}': '{key}' musi być {expected_type}"
|
|
179
|
+
)
|
|
180
|
+
|