index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
726,284 | penne.delegates | update_client_view | Notify the server of an area of interest for the client | def update_client_view(self, direction: Vec3, angle: float):
"""Notify the server of an area of interest for the client"""
self.client_view(direction, angle)
| (self, direction: List[float], angle: float) |
726,285 | penne.delegates | Entity | Container for other entities, possibly renderable, has associated methods and signals
Can reference other entities, geometry, plots, and lights. It can be rendered, if it has a render rep.
It may have associated methods and signals. The transform is relative to the parent entity. In other contexts
it may be called a node.
Attributes:
id: ID for the entity
name: Name of the entity
parent: Parent entity
transform: Local transform for the entity
text_rep: Text representation for the entity
web_rep: Web representation for the entity
render_rep: Render representation for the entity
lights: List of lights attached to the entity
tables: List of tables attached to the entity
plots: List of plots attached to the entity
tags: List of tags for the entity
methods_list: List of methods attached to the entity
signals_list: List of signals attached to the entity
influence: Bounding box for the entity
| class Entity(Delegate):
"""Container for other entities, possibly renderable, has associated methods and signals
Can reference other entities, geometry, plots, and lights. It can be rendered, if it has a render rep.
It may have associated methods and signals. The transform is relative to the parent entity. In other contexts
it may be called a node.
Attributes:
id: ID for the entity
name: Name of the entity
parent: Parent entity
transform: Local transform for the entity
text_rep: Text representation for the entity
web_rep: Web representation for the entity
render_rep: Render representation for the entity
lights: List of lights attached to the entity
tables: List of tables attached to the entity
plots: List of plots attached to the entity
tags: List of tags for the entity
methods_list: List of methods attached to the entity
signals_list: List of signals attached to the entity
influence: Bounding box for the entity
"""
id: EntityID
name: Optional[str] = "Unnamed Entity Delegate"
parent: Optional[EntityID] = None
transform: Optional[Mat4] = None
null_rep: Optional[Any] = None
text_rep: Optional[TextRepresentation] = None
web_rep: Optional[WebRepresentation] = None
render_rep: Optional[RenderRepresentation] = None
lights: Optional[List[LightID]] = None
tables: Optional[List[TableID]] = None
plots: Optional[List[PlotID]] = None
tags: Optional[List[str]] = None
methods_list: Optional[List[MethodID]] = None
signals_list: Optional[List[SignalID]] = None
influence: Optional[BoundingBox] = None
# Injected methods
set_position: Optional[InjectedMethod] = None
set_rotation: Optional[InjectedMethod] = None
set_scale: Optional[InjectedMethod] = None
activate: Optional[InjectedMethod] = None
get_activation_choices: Optional[InjectedMethod] = None
get_var_keys: Optional[InjectedMethod] = None
get_var_options: Optional[InjectedMethod] = None
get_var_value: Optional[InjectedMethod] = None
set_var_value: Optional[InjectedMethod] = None
select_region: Optional[InjectedMethod] = None
select_sphere: Optional[InjectedMethod] = None
select_half_plane: Optional[InjectedMethod] = None
select_hull: Optional[InjectedMethod] = None
probe_at: Optional[InjectedMethod] = None
def on_new(self, message: dict):
# Inject methods and signals if applicable
if self.methods_list:
inject_methods(self, self.methods_list)
if self.signals_list:
inject_signals(self, self.signals_list)
def on_update(self, message: dict):
# Inject methods and signals if applicable
if self.methods_list:
inject_methods(self, self.methods_list)
if self.signals_list:
inject_signals(self, self.signals_list)
def request_set_position(self, position: Vec3):
"""Request to set the position of the entity
Args:
position (Vec3): Position to set
"""
self.set_position(position)
def request_set_rotation(self, rotation: Vec4):
"""Request to set the rotation of the entity
Args:
rotation (Vec4): Rotation to set
"""
self.set_rotation(rotation)
def request_set_scale(self, scale: Vec3):
"""Request to set the scale of the entity
Args:
scale (Vec3): Scale to set
"""
self.set_scale(scale)
def show_methods(self):
"""Show methods available on the entity"""
if self.methods_list is None:
message = "No methods available"
else:
message = f"-- Methods on {self.name} --\n--------------------------------------\n"
for method_id in self.methods_list:
method = self.client.get_delegate(method_id)
message += f">> {method}"
print(message)
return message
| (*, client: object = None, id: penne.delegates.EntityID, name: Optional[str] = 'Unnamed Entity Delegate', signals: Optional[dict] = {}, parent: Optional[penne.delegates.EntityID] = None, transform: Optional[List[float]] = None, null_rep: Optional[Any] = None, text_rep: Optional[penne.delegates.TextRepresentation] = None, web_rep: Optional[penne.delegates.WebRepresentation] = None, render_rep: Optional[penne.delegates.RenderRepresentation] = None, lights: Optional[List[penne.delegates.LightID]] = None, tables: Optional[List[penne.delegates.TableID]] = None, plots: Optional[List[penne.delegates.PlotID]] = None, tags: Optional[List[str]] = None, methods_list: Optional[List[penne.delegates.MethodID]] = None, signals_list: Optional[List[penne.delegates.SignalID]] = None, influence: Optional[penne.delegates.BoundingBox] = None, set_position: Optional[penne.delegates.InjectedMethod] = None, set_rotation: Optional[penne.delegates.InjectedMethod] = None, set_scale: Optional[penne.delegates.InjectedMethod] = None, activate: Optional[penne.delegates.InjectedMethod] = None, get_activation_choices: Optional[penne.delegates.InjectedMethod] = None, get_var_keys: Optional[penne.delegates.InjectedMethod] = None, get_var_options: Optional[penne.delegates.InjectedMethod] = None, get_var_value: Optional[penne.delegates.InjectedMethod] = None, set_var_value: Optional[penne.delegates.InjectedMethod] = None, select_region: Optional[penne.delegates.InjectedMethod] = None, select_sphere: Optional[penne.delegates.InjectedMethod] = None, select_half_plane: Optional[penne.delegates.InjectedMethod] = None, select_hull: Optional[penne.delegates.InjectedMethod] = None, probe_at: Optional[penne.delegates.InjectedMethod] = None, **extra_data: Any) -> None |
726,313 | penne.delegates | on_new | null | def on_new(self, message: dict):
# Inject methods and signals if applicable
if self.methods_list:
inject_methods(self, self.methods_list)
if self.signals_list:
inject_signals(self, self.signals_list)
| (self, message: dict) |
726,315 | penne.delegates | on_update | null | def on_update(self, message: dict):
# Inject methods and signals if applicable
if self.methods_list:
inject_methods(self, self.methods_list)
if self.signals_list:
inject_signals(self, self.signals_list)
| (self, message: dict) |
726,316 | penne.delegates | request_set_position | Request to set the position of the entity
Args:
position (Vec3): Position to set
| def request_set_position(self, position: Vec3):
"""Request to set the position of the entity
Args:
position (Vec3): Position to set
"""
self.set_position(position)
| (self, position: List[float]) |
726,317 | penne.delegates | request_set_rotation | Request to set the rotation of the entity
Args:
rotation (Vec4): Rotation to set
| def request_set_rotation(self, rotation: Vec4):
"""Request to set the rotation of the entity
Args:
rotation (Vec4): Rotation to set
"""
self.set_rotation(rotation)
| (self, rotation: List[float]) |
726,318 | penne.delegates | request_set_scale | Request to set the scale of the entity
Args:
scale (Vec3): Scale to set
| def request_set_scale(self, scale: Vec3):
"""Request to set the scale of the entity
Args:
scale (Vec3): Scale to set
"""
self.set_scale(scale)
| (self, scale: List[float]) |
726,319 | penne.delegates | show_methods | Show methods available on the entity | def show_methods(self):
"""Show methods available on the entity"""
if self.methods_list is None:
message = "No methods available"
else:
message = f"-- Methods on {self.name} --\n--------------------------------------\n"
for method_id in self.methods_list:
method = self.client.get_delegate(method_id)
message += f">> {method}"
print(message)
return message
| (self) |
726,320 | penne.delegates | EntityID | ID specific to entities | class EntityID(ID):
"""ID specific to entities"""
pass
| (slot: int, gen: int) |
726,333 | penne.delegates | Format | String indicating format of byte data for an attribute
Used in Attribute inside of geometry patch. Takes value of either U8, U16, U32, U8VEC4, U16VEC2,
VEC2, VEC3, VEC4, MAT3, or MAT4
| class Format(Enum):
"""String indicating format of byte data for an attribute
Used in Attribute inside of geometry patch. Takes value of either U8, U16, U32, U8VEC4, U16VEC2,
VEC2, VEC3, VEC4, MAT3, or MAT4
"""
u8 = "U8"
u16 = "U16"
u32 = "U32"
u8vec4 = "U8VEC4"
u16vec2 = "U16VEC2"
vec2 = "VEC2"
vec3 = "VEC3"
vec4 = "VEC4"
mat3 = "MAT3"
mat4 = "MAT4"
| (value, names=None, *, module=None, qualname=None, type=None, start=1) |
726,334 | penne.delegates | Geometry | Represents geometry in the scene and can be used for meshes
This is more of a collection of patches, but each patch will contain the geometry information to render a mesh.
The patch references buffer views and buffers for each attribute, and a material to use for rendering. Instances
are stored in a separate buffer that is referenced at the entity level.
Attributes:
id: ID for the geometry
name: Name of the geometry
patches: Patches that make up the geometry
| class Geometry(Delegate):
"""Represents geometry in the scene and can be used for meshes
This is more of a collection of patches, but each patch will contain the geometry information to render a mesh.
The patch references buffer views and buffers for each attribute, and a material to use for rendering. Instances
are stored in a separate buffer that is referenced at the entity level.
Attributes:
id: ID for the geometry
name: Name of the geometry
patches: Patches that make up the geometry
"""
id: GeometryID
name: Optional[str] = "Unnamed Geometry Delegate"
patches: List[GeometryPatch]
| (*, client: object = None, id: penne.delegates.GeometryID, name: Optional[str] = 'Unnamed Geometry Delegate', signals: Optional[dict] = {}, patches: List[penne.delegates.GeometryPatch], **extra_data: Any) -> None |
726,365 | penne.delegates | GeometryID | ID specific to geometries | class GeometryID(ID):
"""ID specific to geometries"""
pass
| (slot: int, gen: int) |
726,377 | penne.delegates | GeometryPatch | Geometry patch for a mesh
Principle object used in geometry delegates. A geometry patch combines vertex data from attributes and index data
from indices.
Attributes:
attributes (List[Attribute]): List of attributes storing vertex data for the mesh
vertex_count (int): Number of vertices in the mesh
indices (Optional[Index]): Indices for the mesh
type (PrimitiveType): Type of primitive to render
material (MaterialID): Material to use for rendering
| class GeometryPatch(NoodleObject):
"""Geometry patch for a mesh
Principle object used in geometry delegates. A geometry patch combines vertex data from attributes and index data
from indices.
Attributes:
attributes (List[Attribute]): List of attributes storing vertex data for the mesh
vertex_count (int): Number of vertices in the mesh
indices (Optional[Index]): Indices for the mesh
type (PrimitiveType): Type of primitive to render
material (MaterialID): Material to use for rendering
"""
attributes: List[Attribute]
vertex_count: int
indices: Optional[Index] = None
type: PrimitiveType
material: MaterialID # Material ID
| (*, attributes: List[penne.delegates.Attribute], vertex_count: int, indices: Optional[penne.delegates.Index] = None, type: penne.delegates.PrimitiveType, material: penne.delegates.MaterialID, **extra_data: Any) -> None |
726,405 | penne.delegates | ID | Base class for all ID's
Each ID is composed of a slot and a generation, resulting in a tuple like id ex. (0, 0). Both are positive
integers that are filled in increasing order. Slots are taken first, but once the slot is freed, it can be used
with a new generation. For example, a method is created -> (0, 0), then another is created -> (1, 0), then method
(0, 0) is deleted. Now, the next method created will be (0, 1).
Attributes:
slot (int): Slot of the ID
gen (int): Generation of the ID
| class ID(NamedTuple):
"""Base class for all ID's
Each ID is composed of a slot and a generation, resulting in a tuple like id ex. (0, 0). Both are positive
integers that are filled in increasing order. Slots are taken first, but once the slot is freed, it can be used
with a new generation. For example, a method is created -> (0, 0), then another is created -> (1, 0), then method
(0, 0) is deleted. Now, the next method created will be (0, 1).
Attributes:
slot (int): Slot of the ID
gen (int): Generation of the ID
"""
slot: int
gen: int
def compact_str(self):
return f"|{self.slot}/{self.gen}|"
def __str__(self):
return f"{type(self).__name__}{self.compact_str()}"
def __key(self):
return type(self), self.slot, self.gen
def __eq__(self, other: object) -> bool:
if type(other) is type(self):
return self.__key() == other.__key()
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash(self.__key())
| (slot: int, gen: int) |
726,417 | penne.delegates | Image | An image, can be used for a texture
Like a buffer, an image can be stored in a URI to reduce the size of messages. To obtain the bytes, you would
have to make an HTTP request to the URI.
Attributes:
id: ID for the image
name: Name of the image
buffer_source: Buffer that the image is stored in
uri_source: URI for the bytes if they are hosted externally
| class Image(Delegate):
"""An image, can be used for a texture
Like a buffer, an image can be stored in a URI to reduce the size of messages. To obtain the bytes, you would
have to make an HTTP request to the URI.
Attributes:
id: ID for the image
name: Name of the image
buffer_source: Buffer that the image is stored in
uri_source: URI for the bytes if they are hosted externally
"""
id: ImageID
name: Optional[str] = "Unnamed Image Delegate"
buffer_source: Optional[BufferID] = None
uri_source: Optional[str] = None
@model_validator(mode="after")
def one_of(cls, model):
if bool(model.buffer_source) != bool(model.uri_source):
return model
else:
raise ValueError("One plot type must be specified")
| (*, client: object = None, id: penne.delegates.ImageID, name: Optional[str] = 'Unnamed Image Delegate', signals: Optional[dict] = {}, buffer_source: Optional[penne.delegates.BufferID] = None, uri_source: Optional[str] = None, **extra_data: Any) -> None |
726,448 | penne.delegates | ImageID | ID specific to images | class ImageID(ID):
"""ID specific to images"""
pass
| (slot: int, gen: int) |
726,460 | penne.delegates | Index | Index for a geometry patch
The index is a view into a buffer that corresponds to the indices of the mesh. The index allows the mesh to
connect vertices and render triangles, lines, or points.
Attributes:
view (BufferViewID): View of the buffer storing the data
count (int): Number of indices
offset (Optional[int]): Offset into buffer
stride (Optional[int]): Distance, in bytes, between data for two elements in the buffer
format (IndexFormat): How many bytes per element, how to decode the bytes
| class Index(NoodleObject):
"""Index for a geometry patch
The index is a view into a buffer that corresponds to the indices of the mesh. The index allows the mesh to
connect vertices and render triangles, lines, or points.
Attributes:
view (BufferViewID): View of the buffer storing the data
count (int): Number of indices
offset (Optional[int]): Offset into buffer
stride (Optional[int]): Distance, in bytes, between data for two elements in the buffer
format (IndexFormat): How many bytes per element, how to decode the bytes
"""
view: BufferViewID
count: int
offset: Optional[int] = 0
stride: Optional[int] = 0
format: IndexFormat
| (*, view: penne.delegates.BufferViewID, count: int, offset: Optional[int] = 0, stride: Optional[int] = 0, format: penne.delegates.IndexFormat, **extra_data: Any) -> None |
726,488 | penne.delegates | IndexFormat | String indicating format of byte data for an index
Used in Index inside of geometry patch. Takes value of either U8, U16, or U32
| class IndexFormat(str, Enum):
"""String indicating format of byte data for an index
Used in Index inside of geometry patch. Takes value of either U8, U16, or U32
"""
u8 = "U8"
u16 = "U16"
u32 = "U32"
| (value, names=None, *, module=None, qualname=None, type=None, start=1) |
726,489 | penne.delegates | InjectedMethod | Class for representing injected method in delegate
The context is automatically set when invoked. This object is callable and is what is actually called when the
injected method is called.
Attributes:
method (Callable): method to be called
injected (bool): attribute marking method as injected, useful for clearing out old injected methods
| class InjectedMethod(object):
"""Class for representing injected method in delegate
The context is automatically set when invoked. This object is callable and is what is actually called when the
injected method is called.
Attributes:
method (Callable): method to be called
injected (bool): attribute marking method as injected, useful for clearing out old injected methods
"""
def __init__(self, method_obj) -> None:
self.method = method_obj
self.injected = True
def __call__(self, *args, **kwargs):
self.method(*args, **kwargs)
| (method_obj) -> 'None' |
726,490 | penne.delegates | __call__ | null | def __call__(self, *args, **kwargs):
self.method(*args, **kwargs)
| (self, *args, **kwargs) |
726,491 | penne.delegates | __init__ | null | def __init__(self, method_obj) -> None:
self.method = method_obj
self.injected = True
| (self, method_obj) -> NoneType |
726,492 | penne.delegates | InstanceSource | Source of instances for a geometry patch
Attributes:
view (BufferViewID): View of mat4
stride (int): Stride for buffer, defaults to tightly packed
bb (BoundingBox): Bounding box of instances
| class InstanceSource(NoodleObject):
"""Source of instances for a geometry patch
Attributes:
view (BufferViewID): View of mat4
stride (int): Stride for buffer, defaults to tightly packed
bb (BoundingBox): Bounding box of instances
"""
view: BufferViewID
stride: Optional[int] = 0
bb: Optional[BoundingBox] = None
| (*, view: penne.delegates.BufferViewID, stride: Optional[int] = 0, bb: Optional[penne.delegates.BoundingBox] = None, **extra_data: Any) -> None |
726,520 | penne.delegates | Invoke | null | class Invoke(NoodleObject):
id: SignalID
context: Optional[InvokeIDType] = None # if empty - document
signal_data: List[Any]
| (*, id: penne.delegates.SignalID, context: Optional[penne.delegates.InvokeIDType] = None, signal_data: List[Any], **extra_data: Any) -> None |
726,548 | penne.delegates | InvokeIDType | Context for invoking a signal
Attributes:
entity (Optional[EntityID]): Entity to invoke signal on
table (Optional[TableID]): Table to invoke signal on
plot (Optional[PlotID]): Plot to invoke signal on
| class InvokeIDType(NoodleObject):
"""Context for invoking a signal
Attributes:
entity (Optional[EntityID]): Entity to invoke signal on
table (Optional[TableID]): Table to invoke signal on
plot (Optional[PlotID]): Plot to invoke signal on
"""
entity: Optional[EntityID] = None
table: Optional[TableID] = None
plot: Optional[PlotID] = None
@model_validator(mode="after")
def one_of_three(cls, model):
num_set = bool(model.entity) + bool(model.table) + bool(model.plot)
if num_set != 1:
raise ValueError("Must set exactly one of entity, table, or plot")
return model
| (*, entity: Optional[penne.delegates.EntityID] = None, table: Optional[penne.delegates.TableID] = None, plot: Optional[penne.delegates.PlotID] = None, **extra_data: Any) -> None |
726,576 | penne.delegates | Light | Represents a light in the scene
For these purposes, a light is just a couple of properties like color, intensity, and light type. The entity
that stores the light will dictate position and direction with its transform. The client application is then
responsible for using this information to render the light. The light is either a point light, a spotlight, or
a directional light.
Attributes:
id: ID for the light
name: Name of the light
color: Color of the light
intensity: Intensity of the light
point: Point light information
spot: Spotlight information
directional: Directional light information
| class Light(Delegate):
"""Represents a light in the scene
For these purposes, a light is just a couple of properties like color, intensity, and light type. The entity
that stores the light will dictate position and direction with its transform. The client application is then
responsible for using this information to render the light. The light is either a point light, a spotlight, or
a directional light.
Attributes:
id: ID for the light
name: Name of the light
color: Color of the light
intensity: Intensity of the light
point: Point light information
spot: Spotlight information
directional: Directional light information
"""
id: LightID
name: Optional[str] = "Unnamed Light Delegate"
color: Optional[Color] = Color('white')
intensity: Optional[float] = 1.0
point: Optional[PointLight] = None
spot: Optional[SpotLight] = None
directional: Optional[DirectionalLight] = None
@field_validator("color", mode='before')
def check_color_rgb(cls, value):
# Raise warning if format is wrong
if len(value) != 3:
logging.warning(f"Color is not RGB in Light: {value}")
return value
@model_validator(mode="after")
def one_of(cls, model):
num_selected = bool(model.point) + bool(model.spot) + bool(model.directional)
if num_selected > 1:
raise ValueError("Only one light type can be selected")
elif num_selected == 0:
raise ValueError("No light type selected")
else:
return model
| (*, client: object = None, id: penne.delegates.LightID, name: Optional[str] = 'Unnamed Light Delegate', signals: Optional[dict] = {}, color: Optional[pydantic_extra_types.color.Color] = Color('white', rgb=(255, 255, 255)), intensity: Optional[float] = 1.0, point: Optional[penne.delegates.PointLight] = None, spot: Optional[penne.delegates.SpotLight] = None, directional: Optional[penne.delegates.DirectionalLight] = None, **extra_data: Any) -> None |
726,607 | penne.delegates | LightID | ID specific to lights | class LightID(ID):
"""ID specific to lights"""
pass
| (slot: int, gen: int) |
726,619 | penne.delegates | LinkedMethod | Class linking target delegate and method's delegate
Make a cleaner function call in injected method, it's like setting the context automatically
This is what actually gets called for the injected method
Attributes:
_obj_delegate (Delegate):
delegate method is being linked to
_method_delegate (MethodDelegate):
the method's delegate
| class LinkedMethod(object):
"""Class linking target delegate and method's delegate
Make a cleaner function call in injected method, it's like setting the context automatically
This is what actually gets called for the injected method
Attributes:
_obj_delegate (Delegate):
delegate method is being linked to
_method_delegate (MethodDelegate):
the method's delegate
"""
def __init__(self, object_delegate: Delegate, method_delegate: Method):
self._obj_delegate = object_delegate
self._method_delegate = method_delegate
def __call__(self, *args, **kwargs):
callback = kwargs.pop("callback", None)
self._method_delegate.invoke(self._obj_delegate, list(args), callback=callback)
| (object_delegate: 'Delegate', method_delegate: 'Method') |
726,620 | penne.delegates | __call__ | null | def __call__(self, *args, **kwargs):
callback = kwargs.pop("callback", None)
self._method_delegate.invoke(self._obj_delegate, list(args), callback=callback)
| (self, *args, **kwargs) |
726,621 | penne.delegates | __init__ | null | def __init__(self, object_delegate: Delegate, method_delegate: Method):
self._obj_delegate = object_delegate
self._method_delegate = method_delegate
| (self, object_delegate: penne.delegates.Delegate, method_delegate: penne.delegates.Method) |
726,622 | penne.delegates | MagFilterTypes | Options for magnification filter type
Used in Sampler. Takes value of either NEAREST or LINEAR
| class MagFilterTypes(Enum):
"""Options for magnification filter type
Used in Sampler. Takes value of either NEAREST or LINEAR
"""
nearest = "NEAREST"
linear = "LINEAR"
| (value, names=None, *, module=None, qualname=None, type=None, start=1) |
726,623 | penne.delegates | Material | A material that can be applied to a mesh.
The material is a collection of textures and factors that are used to render the mesh.
Attributes:
id: ID for the material
name: Name of the material
pbr_info: Information for physically based rendering
normal_texture: Texture for normals
occlusion_texture: Texture for occlusion
occlusion_texture_factor: Factor for occlusion
emissive_texture: Texture for emissive
emissive_factor: Factor for emissive
use_alpha: Whether to use alpha
alpha_cutoff: Alpha cutoff
double_sided: Whether the material is double-sided
| class Material(Delegate):
"""A material that can be applied to a mesh.
The material is a collection of textures and factors that are used to render the mesh.
Attributes:
id: ID for the material
name: Name of the material
pbr_info: Information for physically based rendering
normal_texture: Texture for normals
occlusion_texture: Texture for occlusion
occlusion_texture_factor: Factor for occlusion
emissive_texture: Texture for emissive
emissive_factor: Factor for emissive
use_alpha: Whether to use alpha
alpha_cutoff: Alpha cutoff
double_sided: Whether the material is double-sided
"""
id: MaterialID
name: Optional[str] = "Unnamed Material Delegate"
pbr_info: Optional[PBRInfo] = PBRInfo()
normal_texture: Optional[TextureRef] = None
occlusion_texture: Optional[TextureRef] = None # assumed to be linear, ONLY R used
occlusion_texture_factor: Optional[float] = 1.0
emissive_texture: Optional[TextureRef] = None # assumed to be SRGB, ignore A
emissive_factor: Optional[Vec3] = [1.0, 1.0, 1.0]
use_alpha: Optional[bool] = False
alpha_cutoff: Optional[float] = .5
double_sided: Optional[bool] = False
| (*, client: object = None, id: penne.delegates.MaterialID, name: Optional[str] = 'Unnamed Material Delegate', signals: Optional[dict] = {}, pbr_info: Optional[penne.delegates.PBRInfo] = PBRInfo(base_color=Color('white', rgb=(255, 255, 255)), base_color_texture=None, metallic=1.0, roughness=1.0, metal_rough_texture=None), normal_texture: Optional[penne.delegates.TextureRef] = None, occlusion_texture: Optional[penne.delegates.TextureRef] = None, occlusion_texture_factor: Optional[float] = 1.0, emissive_texture: Optional[penne.delegates.TextureRef] = None, emissive_factor: Optional[List[float]] = [1.0, 1.0, 1.0], use_alpha: Optional[bool] = False, alpha_cutoff: Optional[float] = 0.5, double_sided: Optional[bool] = False, **extra_data: Any) -> None |
726,654 | penne.delegates | MaterialID | ID specific to materials | class MaterialID(ID):
"""ID specific to materials"""
pass
| (slot: int, gen: int) |
726,666 | penne.delegates | Method | A method that clients can request the server to call.
Attributes:
id: ID for the method
name: Name of the method
doc: Documentation for the method
return_doc: Documentation for the return value
arg_doc: Documentation for the arguments
| class Method(Delegate):
"""A method that clients can request the server to call.
Attributes:
id: ID for the method
name: Name of the method
doc: Documentation for the method
return_doc: Documentation for the return value
arg_doc: Documentation for the arguments
"""
id: MethodID
name: str
doc: Optional[str] = None
return_doc: Optional[str] = None
arg_doc: List[MethodArg] = []
def invoke(self, on_delegate: Delegate, args=None, callback=None):
"""Invoke this delegate's method
Args:
on_delegate (Delegate):
delegate method is being invoked on
used to get context
args (list, optional):
args for the method
callback (function):
function to be called when complete
Raises:
ValueError: Invalid delegate context
"""
if isinstance(on_delegate, Table):
kind = "table"
elif isinstance(on_delegate, Plot):
kind = "plot"
elif isinstance(on_delegate, Entity):
kind = "entity"
else:
raise ValueError("Invalid delegate context")
context = {kind: on_delegate.id}
self.client.invoke_method(self.id, args, context=context, callback=callback)
def __str__(self) -> str:
"""Custom string representation for methods"""
rep = f"{self.name}:\n\t{self.doc}\n\tReturns: {self.return_doc}\n\tArgs:"
for arg in self.arg_doc:
rep += f"\n\t\t{arg.name}: {arg.doc}"
return rep
| (*, client: object = None, id: penne.delegates.MethodID, name: str, signals: Optional[dict] = {}, doc: Optional[str] = None, return_doc: Optional[str] = None, arg_doc: List[penne.delegates.MethodArg] = [], **extra_data: Any) -> None |
726,683 | penne.delegates | __str__ | Custom string representation for methods | def __str__(self) -> str:
"""Custom string representation for methods"""
rep = f"{self.name}:\n\t{self.doc}\n\tReturns: {self.return_doc}\n\tArgs:"
for arg in self.arg_doc:
rep += f"\n\t\t{arg.name}: {arg.doc}"
return rep
| (self) -> str |
726,689 | penne.delegates | invoke | Invoke this delegate's method
Args:
on_delegate (Delegate):
delegate method is being invoked on
used to get context
args (list, optional):
args for the method
callback (function):
function to be called when complete
Raises:
ValueError: Invalid delegate context
| def invoke(self, on_delegate: Delegate, args=None, callback=None):
"""Invoke this delegate's method
Args:
on_delegate (Delegate):
delegate method is being invoked on
used to get context
args (list, optional):
args for the method
callback (function):
function to be called when complete
Raises:
ValueError: Invalid delegate context
"""
if isinstance(on_delegate, Table):
kind = "table"
elif isinstance(on_delegate, Plot):
kind = "plot"
elif isinstance(on_delegate, Entity):
kind = "entity"
else:
raise ValueError("Invalid delegate context")
context = {kind: on_delegate.id}
self.client.invoke_method(self.id, args, context=context, callback=callback)
| (self, on_delegate: penne.delegates.Delegate, args=None, callback=None) |
726,698 | penne.delegates | MethodArg | Argument for a method
Attributes:
name (str): Name of argument
doc (str): Documentation for argument
editor_hint (str): Hint for editor, refer to message spec for hint options
| class MethodArg(NoodleObject):
"""Argument for a method
Attributes:
name (str): Name of argument
doc (str): Documentation for argument
editor_hint (str): Hint for editor, refer to message spec for hint options
"""
name: str
doc: Optional[str] = None
editor_hint: Optional[str] = None
| (*, name: str, doc: Optional[str] = None, editor_hint: Optional[str] = None, **extra_data: Any) -> None |
726,726 | penne.delegates | MethodException | Exception raised when invoking a method
Will be sent as part of a reply message
Attributes:
code (int): error code
message (str): error message
data (Any): data associated with the error
| class MethodException(NoodleObject):
"""Exception raised when invoking a method
Will be sent as part of a reply message
Attributes:
code (int): error code
message (str): error message
data (Any): data associated with the error
"""
code: int
message: Optional[str] = None
data: Optional[Any] = None
| (*, code: int, message: Optional[str] = None, data: Optional[Any] = None, **extra_data: Any) -> None |
726,754 | penne.delegates | MethodID | ID specific to methods | class MethodID(ID):
"""ID specific to methods"""
pass
| (slot: int, gen: int) |
726,766 | penne.delegates | MinFilterTypes | Options for minification filter type
Used in Sampler. Takes value of either NEAREST, LINEAR, or LINEAR_MIPMAP_LINEAR
| class MinFilterTypes(Enum):
"""Options for minification filter type
Used in Sampler. Takes value of either NEAREST, LINEAR, or LINEAR_MIPMAP_LINEAR
"""
nearest = "NEAREST"
linear = "LINEAR"
linear_mipmap_linear = "LINEAR_MIPMAP_LINEAR"
| (value, names=None, *, module=None, qualname=None, type=None, start=1) |
726,768 | penne.delegates | NoodleObject | Parent Class for all noodle objects | class NoodleObject(BaseModel):
"""Parent Class for all noodle objects"""
model_config = ConfigDict(arbitrary_types_allowed=True, use_enum_values=True, extra="allow", frozen=False)
| (**extra_data: Any) -> None |
726,796 | penne.delegates | PBRInfo | Physically based rendering information for a material
Attributes:
base_color (Optional[RGBA]): Base color of material
base_color_texture (Optional[TextureRef]): Texture to use for base color
metallic (Optional[float]): Metallic value of material
roughness (Optional[float]): Roughness value of material
metal_rough_texture (Optional[TextureRef]): Texture to use for metallic and roughness
| class PBRInfo(NoodleObject):
"""Physically based rendering information for a material
Attributes:
base_color (Optional[RGBA]): Base color of material
base_color_texture (Optional[TextureRef]): Texture to use for base color
metallic (Optional[float]): Metallic value of material
roughness (Optional[float]): Roughness value of material
metal_rough_texture (Optional[TextureRef]): Texture to use for metallic and roughness
"""
base_color: Optional[Color] = Color('white')
base_color_texture: Optional[TextureRef] = None # assume SRGB, no premult alpha
metallic: Optional[float] = 1.0
roughness: Optional[float] = 1.0
metal_rough_texture: Optional[TextureRef] = None # assume linear, ONLY RG used
@field_validator("base_color", mode='before')
def check_color_rgba(cls, value):
# Raise warning if format is wrong from server
if len(value) != 4:
logging.warning(f"Base Color is Wrong Color Format: {value}")
return value
| (*, base_color: Optional[pydantic_extra_types.color.Color] = Color('white', rgb=(255, 255, 255)), base_color_texture: Optional[penne.delegates.TextureRef] = None, metallic: Optional[float] = 1.0, roughness: Optional[float] = 1.0, metal_rough_texture: Optional[penne.delegates.TextureRef] = None, **extra_data: Any) -> None |
726,824 | penne.delegates | Plot | An abstract plot object.
Attributes:
id: ID for the plot
name: Name of the plot
table: Table to plot
simple_plot: Simple plot to render
url_plot: URL for plot to render
methods_list: List of methods attached to the plot
signals_list: List of signals attached to the plot
| class Plot(Delegate):
"""An abstract plot object.
Attributes:
id: ID for the plot
name: Name of the plot
table: Table to plot
simple_plot: Simple plot to render
url_plot: URL for plot to render
methods_list: List of methods attached to the plot
signals_list: List of signals attached to the plot
"""
id: PlotID
name: Optional[str] = "Unnamed Plot Delegate"
table: Optional[TableID] = None
simple_plot: Optional[str] = None
url_plot: Optional[str] = None
methods_list: Optional[List[MethodID]] = None
signals_list: Optional[List[SignalID]] = None
@model_validator(mode="after")
def one_of(cls, model):
if bool(model.simple_plot) != bool(model.url_plot):
return model
else:
raise ValueError("One plot type must be specified")
def show_methods(self):
"""Show methods available on the entity"""
if self.methods_list is None:
message = "No methods available"
else:
message = f"-- Methods on {self.name} --\n--------------------------------------\n"
for method_id in self.methods_list:
method = self.client.get_delegate(method_id)
message += f">> {method}"
print(message)
return message
| (*, client: object = None, id: penne.delegates.PlotID, name: Optional[str] = 'Unnamed Plot Delegate', signals: Optional[dict] = {}, table: Optional[penne.delegates.TableID] = None, simple_plot: Optional[str] = None, url_plot: Optional[str] = None, methods_list: Optional[List[penne.delegates.MethodID]] = None, signals_list: Optional[List[penne.delegates.SignalID]] = None, **extra_data: Any) -> None |
726,856 | penne.delegates | PlotID | ID specific to plots | class PlotID(ID):
"""ID specific to plots"""
pass
| (slot: int, gen: int) |
726,868 | penne.delegates | PointLight | Point light information for a light delegate
Attributes:
range (float): Range of light, -1 defaults to infinite
| class PointLight(NoodleObject):
"""Point light information for a light delegate
Attributes:
range (float): Range of light, -1 defaults to infinite
"""
range: float = -1.0
| (*, range: float = -1.0, **extra_data: Any) -> None |
726,896 | penne.delegates | PrimitiveType | String indicating type of primitive used in a geometry patch
Takes value of either POINTS, LINES, LINE_LOOP, LINE_STRIP, TRIANGLES, or TRIANGLE_STRIP
| class PrimitiveType(Enum):
"""String indicating type of primitive used in a geometry patch
Takes value of either POINTS, LINES, LINE_LOOP, LINE_STRIP, TRIANGLES, or TRIANGLE_STRIP
"""
points = "POINTS"
lines = "LINES"
line_loop = "LINE_LOOP"
line_strip = "LINE_STRIP"
triangles = "TRIANGLES"
triangle_strip = "TRIANGLE_STRIP"
| (value, names=None, *, module=None, qualname=None, type=None, start=1) |
726,897 | penne.delegates | RenderRepresentation | Render representation for an entity
Attributes:
mesh (GeometryID): Mesh to render
instances (Optional[InstanceSource]): Source of instances for mesh
| class RenderRepresentation(NoodleObject):
"""Render representation for an entity
Attributes:
mesh (GeometryID): Mesh to render
instances (Optional[InstanceSource]): Source of instances for mesh
"""
mesh: GeometryID
instances: Optional[InstanceSource] = None
| (*, mesh: penne.delegates.GeometryID, instances: Optional[penne.delegates.InstanceSource] = None, **extra_data: Any) -> None |
726,925 | penne.delegates | Reply | Reply message sent from server in response to method invocation
Will either contain resulting data, or an exception
Attributes:
invoke_id (str): id of the invoke message that this is a reply to
result (Any): result of the method invocation
method_exception (MethodException): exception raised when invoking method
| class Reply(NoodleObject):
"""Reply message sent from server in response to method invocation
Will either contain resulting data, or an exception
Attributes:
invoke_id (str): id of the invoke message that this is a reply to
result (Any): result of the method invocation
method_exception (MethodException): exception raised when invoking method
"""
invoke_id: str
result: Optional[Any] = None
method_exception: Optional[MethodException] = None
| (*, invoke_id: str, result: Optional[Any] = None, method_exception: Optional[penne.delegates.MethodException] = None, **extra_data: Any) -> None |
726,953 | penne.delegates | Sampler | A sampler to use for a texture
A sampler specifies how to take portions of an image and apply them to a mesh.
Attributes:
id: ID for the sampler
name: Name of the sampler
mag_filter: Magnification filter
min_filter: Minification filter
wrap_s: Wrap mode for S
wrap_t: Wrap mode for T
| class Sampler(Delegate):
"""A sampler to use for a texture
A sampler specifies how to take portions of an image and apply them to a mesh.
Attributes:
id: ID for the sampler
name: Name of the sampler
mag_filter: Magnification filter
min_filter: Minification filter
wrap_s: Wrap mode for S
wrap_t: Wrap mode for T
"""
id: SamplerID
name: Optional[str] = "Unnamed Sampler Delegate"
mag_filter: Optional[MagFilterTypes] = MagFilterTypes.linear
min_filter: Optional[MinFilterTypes] = MinFilterTypes.linear_mipmap_linear
wrap_s: Optional[SamplerMode] = "REPEAT"
wrap_t: Optional[SamplerMode] = "REPEAT"
| (*, client: object = None, id: penne.delegates.SamplerID, name: Optional[str] = 'Unnamed Sampler Delegate', signals: Optional[dict] = {}, mag_filter: Optional[penne.delegates.MagFilterTypes] = <MagFilterTypes.linear: 'LINEAR'>, min_filter: Optional[penne.delegates.MinFilterTypes] = <MinFilterTypes.linear_mipmap_linear: 'LINEAR_MIPMAP_LINEAR'>, wrap_s: Optional[penne.delegates.SamplerMode] = 'REPEAT', wrap_t: Optional[penne.delegates.SamplerMode] = 'REPEAT', **extra_data: Any) -> None |
726,984 | penne.delegates | SamplerID | ID specific to samplers | class SamplerID(ID):
"""ID specific to samplers"""
pass
| (slot: int, gen: int) |
726,996 | penne.delegates | SamplerMode | String options for sampler mode
Used in Sampler. Takes value of either CLAMP_TO_EDGE, MIRRORED_REPEAT, or REPEAT
| class SamplerMode(Enum):
"""String options for sampler mode
Used in Sampler. Takes value of either CLAMP_TO_EDGE, MIRRORED_REPEAT, or REPEAT
"""
clamp_to_edge = "CLAMP_TO_EDGE"
mirrored_repeat = "MIRRORED_REPEAT"
repeat = "REPEAT"
| (value, names=None, *, module=None, qualname=None, type=None, start=1) |
726,997 | penne.delegates | Selection | Selection of rows in a table
Attributes:
name (str): Name of selection
rows (List[int]): List of rows to select
row_ranges (List[SelectionRange]): List of ranges of rows to select
| class Selection(NoodleObject):
"""Selection of rows in a table
Attributes:
name (str): Name of selection
rows (List[int]): List of rows to select
row_ranges (List[SelectionRange]): List of ranges of rows to select
"""
name: str
rows: Optional[List[int]] = None
row_ranges: Optional[List[SelectionRange]] = None
| (*, name: str, rows: Optional[List[int]] = None, row_ranges: Optional[List[penne.delegates.SelectionRange]] = None, **extra_data: Any) -> None |
727,025 | penne.delegates | SelectionRange | Range of rows to select in a table
Attributes:
key_from_inclusive (int): First row to select
key_to_exclusive (int): Where to end selection, exclusive
| class SelectionRange(NoodleObject):
"""Range of rows to select in a table
Attributes:
key_from_inclusive (int): First row to select
key_to_exclusive (int): Where to end selection, exclusive
"""
key_from_inclusive: int
key_to_exclusive: int
| (*, key_from_inclusive: int, key_to_exclusive: int, **extra_data: Any) -> None |
727,053 | penne.delegates | Signal | A signal that the server can send to update clients.
Attributes:
id: ID for the signal
name: Name of the signal
doc: Documentation for the signal
arg_doc: Documentation for the arguments
| class Signal(Delegate):
"""A signal that the server can send to update clients.
Attributes:
id: ID for the signal
name: Name of the signal
doc: Documentation for the signal
arg_doc: Documentation for the arguments
"""
id: SignalID
name: str
doc: Optional[str] = None
arg_doc: List[MethodArg] = []
| (*, client: object = None, id: penne.delegates.SignalID, name: str, signals: Optional[dict] = {}, doc: Optional[str] = None, arg_doc: List[penne.delegates.MethodArg] = [], **extra_data: Any) -> None |
727,084 | penne.delegates | SignalID | ID specific to signals | class SignalID(ID):
"""ID specific to signals"""
pass
| (slot: int, gen: int) |
727,096 | penne.delegates | SpotLight | Spotlight information for a light delegate
Attributes:
range (float): Range of light, -1 defaults to infinite
inner_cone_angle_rad (float): Inner cone angle of light
outer_cone_angle_rad (float): Outer cone angle of light
| class SpotLight(NoodleObject):
"""Spotlight information for a light delegate
Attributes:
range (float): Range of light, -1 defaults to infinite
inner_cone_angle_rad (float): Inner cone angle of light
outer_cone_angle_rad (float): Outer cone angle of light
"""
range: float = -1.0
inner_cone_angle_rad: float = 0.0
outer_cone_angle_rad: float = pi/4
| (*, range: float = -1.0, inner_cone_angle_rad: float = 0.0, outer_cone_angle_rad: float = 0.7853981633974483, **extra_data: Any) -> None |
727,124 | penne.delegates | Table | Object to store tabular data.
Note that this delegate doesn't store any actual data. Delegates are meant to subclass and add functionality to
this class. For the client to receive the actual data, they must subscribe to the table. The client will have
access to certain injected methods that allow them to insert, update, delete, and clear the table. This class
provides some abstract methods that can be overridden to handle these events.
Attributes:
id: ID for the table
name: Name of the table
meta: Metadata for the table
methods_list: List of methods for the table
signals_list: List of signals for the table
tbl_subscribe: Injected method to subscribe to the table
tbl_insert: Injected method to insert rows into the table
tbl_update: Injected method to update rows in the table
tbl_remove: Injected method to remove rows from the table
tbl_clear: Injected method to clear the table
tbl_update_selection: Injected method to update the selection
| class Table(Delegate):
"""Object to store tabular data.
Note that this delegate doesn't store any actual data. Delegates are meant to subclass and add functionality to
this class. For the client to receive the actual data, they must subscribe to the table. The client will have
access to certain injected methods that allow them to insert, update, delete, and clear the table. This class
provides some abstract methods that can be overridden to handle these events.
Attributes:
id: ID for the table
name: Name of the table
meta: Metadata for the table
methods_list: List of methods for the table
signals_list: List of signals for the table
tbl_subscribe: Injected method to subscribe to the table
tbl_insert: Injected method to insert rows into the table
tbl_update: Injected method to update rows in the table
tbl_remove: Injected method to remove rows from the table
tbl_clear: Injected method to clear the table
tbl_update_selection: Injected method to update the selection
"""
id: TableID
name: Optional[str] = f"Unnamed Table Delegate"
meta: Optional[str] = None
methods_list: Optional[List[MethodID]] = None
signals_list: Optional[List[SignalID]] = None
tbl_subscribe: Optional[InjectedMethod] = None
tbl_insert: Optional[InjectedMethod] = None
tbl_update: Optional[InjectedMethod] = None
tbl_remove: Optional[InjectedMethod] = None
tbl_clear: Optional[InjectedMethod] = None
tbl_update_selection: Optional[InjectedMethod] = None
def __init__(self, **kwargs):
"""Override init to link default values with methods"""
super().__init__(**kwargs)
self.signals = {
"noo::tbl_reset": self._reset_table,
"noo::tbl_rows_removed": self._remove_rows,
"noo::tbl_updated": self._update_rows,
"noo::tbl_selection_updated": self._update_selection
}
def _on_table_init(self, init_info: dict, callback=None):
"""Creates table from server response info
Args:
init_info (Message Obj):
Server response to subscribe which has columns, keys, data,
and possibly selections
"""
init = TableInitData(**init_info)
logging.info(f"Table Initialized with cols: {init.columns} and row data: {init.data}")
if callback:
callback()
def _reset_table(self, init_info: dict = None):
"""Reset dataframe and selections to blank objects
Method is linked to 'tbl_reset' signal
"""
self.selections = {}
if init_info:
init = TableInitData(**init_info)
logging.info(f"Table Reset and Initialized with cols: {init.columns} and row data: {init.data}")
def _remove_rows(self, keys: List[int]):
"""Removes rows from table
Method is linked to 'tbl_rows_removed' signal
Args:
keys (list): list of keys corresponding to rows to be removed
"""
logging.info(f"Removed Rows: {keys}...\n")
def _update_rows(self, keys: List[int], rows: list):
"""Update rows in table
Method is linked to 'tbl_updated' signal
Args:
keys (list):
list of keys to update
rows (list):
list of rows containing the values for each new row
"""
logging.info(f"Updated Rows...{keys}\n")
def _update_selection(self, selection: dict):
"""Change selection in delegate's state to new selection object
Method is linked to 'tbl_selection_updated' signal
Args:
selection (Selection):
obj with new selections to replace obj with same name
"""
self.selections.setdefault(selection["name"], selection)
logging.info(f"Made selection {selection['name']} = {selection}")
def relink_signals(self):
"""Relink the signals for built-in methods
Injecting signals adds them as keys which map to None. The signals must be relinked after injecting.
These should always be linked, along with whatever is injected.
"""
self.signals["noo::tbl_reset"] = self._reset_table
self.signals["noo::tbl_rows_removed"] = self._remove_rows
self.signals["noo::tbl_updated"] = self._update_rows
self.signals["noo::tbl_selection_updated"] = self._update_selection
def on_new(self, message: dict):
"""Handler when create message is received
Args:
message (Message): create message with the table's info
"""
# Check contents
methods = self.methods_list
signals = self.signals_list
# Inject methods and signals if applicable
if methods:
inject_methods(self, methods)
if signals:
inject_signals(self, signals)
# Reset
self._reset_table()
self.relink_signals()
def on_update(self, message: dict):
"""Handler when update message is received
Args:
message (Message): update message with the new table's info
"""
# Inject methods and signals if applicable
if self.methods_list:
inject_methods(self, self.methods_list)
if self.signals_list:
inject_signals(self, self.signals_list)
self.relink_signals()
def subscribe(self, callback: Callable = None):
"""Subscribe to this delegate's table
Calls on_table_init as callback
Args:
callback (Callable): function to be called after table is subscribed to and initialized
Raises:
Exception: Could not subscribe to table
"""
try:
# Allow for callback after table init
self.tbl_subscribe(callback=lambda data: self._on_table_init(data, callback))
except Exception as e:
raise Exception(f"Could not subscribe to table {self.id}...{e}")
def request_insert(self, row_list: List[List[int]], callback=None):
"""Add rows to end of table
User endpoint for interacting with table and invoking method
For input, row list is list of rows. Also note that tables have
nine columns by default (x, y, z, r, g, b, sx, sy, sz).
x, y, z -> coordinates
r, g, b -> color values [0, 1]
sx, sy, sz -> scaling factors, default size is 1 meter
Row_list: [[1, 2, 3, 4, 5, 6, 7, 8, 9]]
Args:
row_list (list, optional): add rows using list of rows
callback (function, optional): callback function
"""
self.tbl_insert(row_list, callback=callback)
def request_update(self, keys: List[int], rows: List[List[int]], callback=None):
"""Update the table using a DataFrame
User endpoint for interacting with table and invoking method
Args:
keys (list[int]):
list of keys to update
rows (list[list[int]]):
list of new rows to update with
callback (function, optional):
callback function called when complete
"""
self.tbl_update(keys, rows, callback=callback)
def request_remove(self, keys: List[int], callback=None):
"""Remove rows from table by their keys
User endpoint for interacting with table and invoking method
Args:
keys (list):
list of keys for rows to be removed
callback (function, optional):
callback function called when complete
"""
self.tbl_remove(keys, callback=callback)
def request_clear(self, callback=None):
"""Clear the table
User endpoint for interacting with table and invoking method
Args:
callback (function, optional): callback function called when complete
"""
self.tbl_clear(callback=callback)
def request_update_selection(self, name: str, keys: List[int], callback=None):
"""Update a selection object in the table
User endpoint for interacting with table and invoking method
Args:
name (str):
name of the selection object to be updated
keys (list):
list of keys to be in new selection
callback (function, optional):
callback function called when complete
"""
selection = Selection(name=name, rows=keys)
self.tbl_update_selection(selection.model_dump(), callback=callback)
def show_methods(self):
"""Show methods available on the table"""
if self.methods_list is None:
message = "No methods available"
else:
message = f"-- Methods on {self.name} --\n--------------------------------------\n"
for method_id in self.methods_list:
method = self.client.get_delegate(method_id)
message += f">> {method}"
print(message)
return message
| (*, client: object = None, id: penne.delegates.TableID, name: Optional[str] = 'Unnamed Table Delegate', signals: Optional[dict] = {}, meta: Optional[str] = None, methods_list: Optional[List[penne.delegates.MethodID]] = None, signals_list: Optional[List[penne.delegates.SignalID]] = None, tbl_subscribe: Optional[penne.delegates.InjectedMethod] = None, tbl_insert: Optional[penne.delegates.InjectedMethod] = None, tbl_update: Optional[penne.delegates.InjectedMethod] = None, tbl_remove: Optional[penne.delegates.InjectedMethod] = None, tbl_clear: Optional[penne.delegates.InjectedMethod] = None, tbl_update_selection: Optional[penne.delegates.InjectedMethod] = None, **kwargs) -> None |
727,131 | penne.delegates | __init__ | Override init to link default values with methods | def __init__(self, **kwargs):
"""Override init to link default values with methods"""
super().__init__(**kwargs)
self.signals = {
"noo::tbl_reset": self._reset_table,
"noo::tbl_rows_removed": self._remove_rows,
"noo::tbl_updated": self._update_rows,
"noo::tbl_selection_updated": self._update_selection
}
| (self, **kwargs) |
727,145 | penne.delegates | _on_table_init | Creates table from server response info
Args:
init_info (Message Obj):
Server response to subscribe which has columns, keys, data,
and possibly selections
| def _on_table_init(self, init_info: dict, callback=None):
"""Creates table from server response info
Args:
init_info (Message Obj):
Server response to subscribe which has columns, keys, data,
and possibly selections
"""
init = TableInitData(**init_info)
logging.info(f"Table Initialized with cols: {init.columns} and row data: {init.data}")
if callback:
callback()
| (self, init_info: dict, callback=None) |
727,146 | penne.delegates | _remove_rows | Removes rows from table
Method is linked to 'tbl_rows_removed' signal
Args:
keys (list): list of keys corresponding to rows to be removed
| def _remove_rows(self, keys: List[int]):
"""Removes rows from table
Method is linked to 'tbl_rows_removed' signal
Args:
keys (list): list of keys corresponding to rows to be removed
"""
logging.info(f"Removed Rows: {keys}...\n")
| (self, keys: List[int]) |
727,147 | penne.delegates | _reset_table | Reset dataframe and selections to blank objects
Method is linked to 'tbl_reset' signal
| def _reset_table(self, init_info: dict = None):
"""Reset dataframe and selections to blank objects
Method is linked to 'tbl_reset' signal
"""
self.selections = {}
if init_info:
init = TableInitData(**init_info)
logging.info(f"Table Reset and Initialized with cols: {init.columns} and row data: {init.data}")
| (self, init_info: Optional[dict] = None) |
727,148 | penne.delegates | _update_rows | Update rows in table
Method is linked to 'tbl_updated' signal
Args:
keys (list):
list of keys to update
rows (list):
list of rows containing the values for each new row
| def _update_rows(self, keys: List[int], rows: list):
"""Update rows in table
Method is linked to 'tbl_updated' signal
Args:
keys (list):
list of keys to update
rows (list):
list of rows containing the values for each new row
"""
logging.info(f"Updated Rows...{keys}\n")
| (self, keys: List[int], rows: list) |
727,149 | penne.delegates | _update_selection | Change selection in delegate's state to new selection object
Method is linked to 'tbl_selection_updated' signal
Args:
selection (Selection):
obj with new selections to replace obj with same name
| def _update_selection(self, selection: dict):
"""Change selection in delegate's state to new selection object
Method is linked to 'tbl_selection_updated' signal
Args:
selection (Selection):
obj with new selections to replace obj with same name
"""
self.selections.setdefault(selection["name"], selection)
logging.info(f"Made selection {selection['name']} = {selection}")
| (self, selection: dict) |
727,157 | penne.delegates | on_new | Handler when create message is received
Args:
message (Message): create message with the table's info
| def on_new(self, message: dict):
"""Handler when create message is received
Args:
message (Message): create message with the table's info
"""
# Check contents
methods = self.methods_list
signals = self.signals_list
# Inject methods and signals if applicable
if methods:
inject_methods(self, methods)
if signals:
inject_signals(self, signals)
# Reset
self._reset_table()
self.relink_signals()
| (self, message: dict) |
727,159 | penne.delegates | on_update | Handler when update message is received
Args:
message (Message): update message with the new table's info
| def on_update(self, message: dict):
"""Handler when update message is received
Args:
message (Message): update message with the new table's info
"""
# Inject methods and signals if applicable
if self.methods_list:
inject_methods(self, self.methods_list)
if self.signals_list:
inject_signals(self, self.signals_list)
self.relink_signals()
| (self, message: dict) |
727,160 | penne.delegates | relink_signals | Relink the signals for built-in methods
Injecting signals adds them as keys which map to None. The signals must be relinked after injecting.
These should always be linked, along with whatever is injected.
| def relink_signals(self):
"""Relink the signals for built-in methods
Injecting signals adds them as keys which map to None. The signals must be relinked after injecting.
These should always be linked, along with whatever is injected.
"""
self.signals["noo::tbl_reset"] = self._reset_table
self.signals["noo::tbl_rows_removed"] = self._remove_rows
self.signals["noo::tbl_updated"] = self._update_rows
self.signals["noo::tbl_selection_updated"] = self._update_selection
| (self) |
727,161 | penne.delegates | request_clear | Clear the table
User endpoint for interacting with table and invoking method
Args:
callback (function, optional): callback function called when complete
| def request_clear(self, callback=None):
"""Clear the table
User endpoint for interacting with table and invoking method
Args:
callback (function, optional): callback function called when complete
"""
self.tbl_clear(callback=callback)
| (self, callback=None) |
727,162 | penne.delegates | request_insert | Add rows to end of table
User endpoint for interacting with table and invoking method
For input, row list is list of rows. Also note that tables have
nine columns by default (x, y, z, r, g, b, sx, sy, sz).
x, y, z -> coordinates
r, g, b -> color values [0, 1]
sx, sy, sz -> scaling factors, default size is 1 meter
Row_list: [[1, 2, 3, 4, 5, 6, 7, 8, 9]]
Args:
row_list (list, optional): add rows using list of rows
callback (function, optional): callback function
| def request_insert(self, row_list: List[List[int]], callback=None):
"""Add rows to end of table
User endpoint for interacting with table and invoking method
For input, row list is list of rows. Also note that tables have
nine columns by default (x, y, z, r, g, b, sx, sy, sz).
x, y, z -> coordinates
r, g, b -> color values [0, 1]
sx, sy, sz -> scaling factors, default size is 1 meter
Row_list: [[1, 2, 3, 4, 5, 6, 7, 8, 9]]
Args:
row_list (list, optional): add rows using list of rows
callback (function, optional): callback function
"""
self.tbl_insert(row_list, callback=callback)
| (self, row_list: List[List[int]], callback=None) |
727,163 | penne.delegates | request_remove | Remove rows from table by their keys
User endpoint for interacting with table and invoking method
Args:
keys (list):
list of keys for rows to be removed
callback (function, optional):
callback function called when complete
| def request_remove(self, keys: List[int], callback=None):
"""Remove rows from table by their keys
User endpoint for interacting with table and invoking method
Args:
keys (list):
list of keys for rows to be removed
callback (function, optional):
callback function called when complete
"""
self.tbl_remove(keys, callback=callback)
| (self, keys: List[int], callback=None) |
727,164 | penne.delegates | request_update | Update the table using a DataFrame
User endpoint for interacting with table and invoking method
Args:
keys (list[int]):
list of keys to update
rows (list[list[int]]):
list of new rows to update with
callback (function, optional):
callback function called when complete
| def request_update(self, keys: List[int], rows: List[List[int]], callback=None):
"""Update the table using a DataFrame
User endpoint for interacting with table and invoking method
Args:
keys (list[int]):
list of keys to update
rows (list[list[int]]):
list of new rows to update with
callback (function, optional):
callback function called when complete
"""
self.tbl_update(keys, rows, callback=callback)
| (self, keys: List[int], rows: List[List[int]], callback=None) |
727,165 | penne.delegates | request_update_selection | Update a selection object in the table
User endpoint for interacting with table and invoking method
Args:
name (str):
name of the selection object to be updated
keys (list):
list of keys to be in new selection
callback (function, optional):
callback function called when complete
| def request_update_selection(self, name: str, keys: List[int], callback=None):
"""Update a selection object in the table
User endpoint for interacting with table and invoking method
Args:
name (str):
name of the selection object to be updated
keys (list):
list of keys to be in new selection
callback (function, optional):
callback function called when complete
"""
selection = Selection(name=name, rows=keys)
self.tbl_update_selection(selection.model_dump(), callback=callback)
| (self, name: str, keys: List[int], callback=None) |
727,166 | penne.delegates | show_methods | Show methods available on the table | def show_methods(self):
"""Show methods available on the table"""
if self.methods_list is None:
message = "No methods available"
else:
message = f"-- Methods on {self.name} --\n--------------------------------------\n"
for method_id in self.methods_list:
method = self.client.get_delegate(method_id)
message += f">> {method}"
print(message)
return message
| (self) |
727,167 | penne.delegates | subscribe | Subscribe to this delegate's table
Calls on_table_init as callback
Args:
callback (Callable): function to be called after table is subscribed to and initialized
Raises:
Exception: Could not subscribe to table
| def subscribe(self, callback: Callable = None):
"""Subscribe to this delegate's table
Calls on_table_init as callback
Args:
callback (Callable): function to be called after table is subscribed to and initialized
Raises:
Exception: Could not subscribe to table
"""
try:
# Allow for callback after table init
self.tbl_subscribe(callback=lambda data: self._on_table_init(data, callback))
except Exception as e:
raise Exception(f"Could not subscribe to table {self.id}...{e}")
| (self, callback: Optional[Callable] = None) |
727,168 | penne.delegates | TableColumnInfo | Information about a column in a table
Attributes:
name (str): Name of column
type (ColumnType): Type data in the column
| class TableColumnInfo(NoodleObject):
"""Information about a column in a table
Attributes:
name (str): Name of column
type (ColumnType): Type data in the column
"""
name: str
type: ColumnType
| (*, name: str, type: penne.delegates.ColumnType, **extra_data: Any) -> None |
727,196 | penne.delegates | TableID | ID specific to tables | class TableID(ID):
"""ID specific to tables"""
pass
| (slot: int, gen: int) |
727,208 | penne.delegates | TableInitData | Init data to create a table
Attributes:
columns (List[TableColumnInfo]): List of column information
keys (List[int]): List of column indices that are keys
data (List[List[Any]]): List of rows of data
selections (Optional[List[Selection]]): List of selections to apply to table
| class TableInitData(NoodleObject):
"""Init data to create a table
Attributes:
columns (List[TableColumnInfo]): List of column information
keys (List[int]): List of column indices that are keys
data (List[List[Any]]): List of rows of data
selections (Optional[List[Selection]]): List of selections to apply to table
"""
columns: List[TableColumnInfo]
keys: List[int]
data: List[List[Any]] # Originally tried union, but currently order is used to coerce by pydantic
selections: Optional[List[Selection]] = None
# too much overhead? - strict mode
@model_validator(mode="after")
def types_match(cls, model):
for row in model.data:
for col, i in zip(model.columns, range(len(row))):
text_mismatch = isinstance(row[i], str) and col.type != "TEXT"
real_mismatch = isinstance(row[i], float) and col.type != "REAL"
int_mismatch = isinstance(row[i], int) and col.type != "INTEGER"
if text_mismatch or real_mismatch or int_mismatch:
raise ValueError(f"Column Info doesn't match type in data: {col, row[i]}")
return model
| (*, columns: List[penne.delegates.TableColumnInfo], keys: List[int], data: List[List[Any]], selections: Optional[List[penne.delegates.Selection]] = None, **extra_data: Any) -> None |
727,236 | penne.delegates | TextRepresentation | Text representation for an entity
Attributes:
txt (str): Text to display
font (str): Font to use
height (Optional[float]): Height of text
width (Optional[float]): Width of text
| class TextRepresentation(NoodleObject):
"""Text representation for an entity
Attributes:
txt (str): Text to display
font (str): Font to use
height (Optional[float]): Height of text
width (Optional[float]): Width of text
"""
txt: str
font: Optional[str] = "Arial"
height: Optional[float] = .25
width: Optional[float] = -1.0
| (*, txt: str, font: Optional[str] = 'Arial', height: Optional[float] = 0.25, width: Optional[float] = -1.0, **extra_data: Any) -> None |
727,264 | penne.delegates | Texture | A texture, can be used for a material
This is like a wrapping paper that is applied to a mesh. The image specifies the pattern, and
the sampler specifies which part of the image should be applied to each part of the mesh.
Attributes:
id: ID for the texture
name: Name of the texture
image: Image to use for the texture
sampler: Sampler to use for the texture
| class Texture(Delegate):
"""A texture, can be used for a material
This is like a wrapping paper that is applied to a mesh. The image specifies the pattern, and
the sampler specifies which part of the image should be applied to each part of the mesh.
Attributes:
id: ID for the texture
name: Name of the texture
image: Image to use for the texture
sampler: Sampler to use for the texture
"""
id: TextureID
name: Optional[str] = "Unnamed Texture Delegate"
image: ImageID
sampler: Optional[SamplerID] = None
| (*, client: object = None, id: penne.delegates.TextureID, name: Optional[str] = 'Unnamed Texture Delegate', signals: Optional[dict] = {}, image: penne.delegates.ImageID, sampler: Optional[penne.delegates.SamplerID] = None, **extra_data: Any) -> None |
727,295 | penne.delegates | TextureID | ID specific to textures | class TextureID(ID):
"""ID specific to textures"""
pass
| (slot: int, gen: int) |
727,307 | penne.delegates | TextureRef | Reference to a texture
Attributes:
texture (TextureID): Texture to reference
transform (Optional[Mat3]): Transform to apply to texture
texture_coord_slot (Optional[int]): Texture coordinate slot to use
| class TextureRef(NoodleObject):
"""Reference to a texture
Attributes:
texture (TextureID): Texture to reference
transform (Optional[Mat3]): Transform to apply to texture
texture_coord_slot (Optional[int]): Texture coordinate slot to use
"""
texture: TextureID
transform: Optional[Mat3] = [1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0]
texture_coord_slot: Optional[int] = 0.0
| (*, texture: penne.delegates.TextureID, transform: Optional[List[float]] = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], texture_coord_slot: Optional[int] = 0.0, **extra_data: Any) -> None |
727,335 | penne.delegates | WebRepresentation | Web page with a given URL rendered as a plane
Attributes:
source (str): URL for entity
height (Optional[float]): Height of plane
width (Optional[float]): Width of plane
| class WebRepresentation(NoodleObject):
"""Web page with a given URL rendered as a plane
Attributes:
source (str): URL for entity
height (Optional[float]): Height of plane
width (Optional[float]): Width of plane
"""
source: str
height: Optional[float] = .5
width: Optional[float] = .5
| (*, source: str, height: Optional[float] = 0.5, width: Optional[float] = 0.5, **extra_data: Any) -> None |
727,365 | pydantic.functional_validators | field_validator | Usage docs: https://docs.pydantic.dev/dev-v2/usage/validators/#field-validators
Decorate methods on the class indicating that they should be used to validate fields.
Args:
__field: The first field the `field_validator` should be called on; this is separate
from `fields` to ensure an error is raised if you don't pass at least one.
*fields: Additional field(s) the `field_validator` should be called on.
mode: Specifies whether to validate the fields before or after validation.
check_fields: Whether to check that the fields actually exist on the model.
Returns:
A decorator that can be used to decorate a function to be used as a field_validator.
Raises:
PydanticUserError:
- If `@field_validator` is used bare (with no fields).
- If the args passed to `@field_validator` as fields are not strings.
- If `@field_validator` applied to instance methods.
| def field_validator(
__field: str,
*fields: str,
mode: FieldValidatorModes = 'after',
check_fields: bool | None = None,
) -> Callable[[Any], Any]:
"""Usage docs: https://docs.pydantic.dev/dev-v2/usage/validators/#field-validators
Decorate methods on the class indicating that they should be used to validate fields.
Args:
__field: The first field the `field_validator` should be called on; this is separate
from `fields` to ensure an error is raised if you don't pass at least one.
*fields: Additional field(s) the `field_validator` should be called on.
mode: Specifies whether to validate the fields before or after validation.
check_fields: Whether to check that the fields actually exist on the model.
Returns:
A decorator that can be used to decorate a function to be used as a field_validator.
Raises:
PydanticUserError:
- If `@field_validator` is used bare (with no fields).
- If the args passed to `@field_validator` as fields are not strings.
- If `@field_validator` applied to instance methods.
"""
if isinstance(__field, FunctionType):
raise PydanticUserError(
'`@field_validator` should be used with fields and keyword arguments, not bare. '
"E.g. usage should be `@validator('<field_name>', ...)`",
code='validator-no-fields',
)
fields = __field, *fields
if not all(isinstance(field, str) for field in fields): # type: ignore
raise PydanticUserError(
'`@field_validator` fields should be passed as separate string args. '
"E.g. usage should be `@validator('<field_name_1>', '<field_name_2>', ...)`",
code='validator-invalid-fields',
)
def dec(
f: Callable[..., Any] | staticmethod[Any, Any] | classmethod[Any, Any, Any]
) -> _decorators.PydanticDescriptorProxy[Any]:
if _decorators.is_instance_method_from_sig(f):
raise PydanticUserError(
'`@field_validator` cannot be applied to instance methods', code='validator-instance-method'
)
# auto apply the @classmethod decorator
f = _decorators.ensure_classmethod_based_on_signature(f)
dec_info = _decorators.FieldValidatorDecoratorInfo(fields=fields, mode=mode, check_fields=check_fields)
return _decorators.PydanticDescriptorProxy(f, dec_info)
return dec
| (__field: str, *fields: str, mode: Literal['before', 'after', 'wrap', 'plain'] = 'after', check_fields: Optional[bool] = None) -> Callable[[Any], Any] |
727,366 | penne.delegates | get_context | Helper to get context from delegate
Args:
delegate (Delegate): delegate to get context for, can be Entity, Table, or Plot
Returns:
context (dict): context for delegate, None if not found indicating document
| def get_context(delegate: Delegate):
"""Helper to get context from delegate
Args:
delegate (Delegate): delegate to get context for, can be Entity, Table, or Plot
Returns:
context (dict): context for delegate, None if not found indicating document
"""
if isinstance(delegate, Entity):
return {"entity": delegate.id}
elif isinstance(delegate, Table):
return {"table": delegate.id}
elif isinstance(delegate, Plot):
return {"plot": delegate.id}
else:
return None
| (delegate: penne.delegates.Delegate) |
727,368 | penne.delegates | inject_methods | Inject methods into a delegate class
Idea is to inject a method that is from the server to put into a delegate.
Now it looks like the delegate has an instance method that actually calls what
is on the server. Context, is automatically taken care of. This should mostly be
called on_new or on_update for delegates that have methods. This method clears out any
old injected methods if present.
Args:
delegate (Delegate):
identifier for delegate to be modified
methods (list):
list of method id's to inject
| def inject_methods(delegate: Delegate, methods: List[MethodID]):
"""Inject methods into a delegate class
Idea is to inject a method that is from the server to put into a delegate.
Now it looks like the delegate has an instance method that actually calls what
is on the server. Context, is automatically taken care of. This should mostly be
called on_new or on_update for delegates that have methods. This method clears out any
old injected methods if present.
Args:
delegate (Delegate):
identifier for delegate to be modified
methods (list):
list of method id's to inject
"""
# Clear out old injected methods
to_remove = []
for field, value in delegate:
if hasattr(value, "injected"):
logging.debug(f"Deleting: {field} in inject methods")
to_remove.append(field)
for field in to_remove:
delattr(delegate, field)
for method_id in methods:
# Get method delegate and manipulate name to exclude noo::
method = delegate.client.get_delegate(method_id)
if "noo::" in method.name:
name = method.name[5:]
else:
name = method.name
# Create injected by linking delegates, and creating call method
linked = LinkedMethod(delegate, method)
injected = InjectedMethod(linked.__call__)
setattr(delegate, name, injected)
| (delegate: penne.delegates.Delegate, methods: List[penne.delegates.MethodID]) |
727,369 | penne.delegates | inject_signals | Method to inject signals into delegate
Idea is to inject a signal that is from the server to put into a delegate. These signals are stored in a dict
that can be used to map the signal name to a callable response that handles the signal and its args.
Args:
delegate (Delegate):
delegate object to be injected
signals (list):
list of signal id's to be injected
| def inject_signals(delegate: Delegate, signals: List[SignalID]):
"""Method to inject signals into delegate
Idea is to inject a signal that is from the server to put into a delegate. These signals are stored in a dict
that can be used to map the signal name to a callable response that handles the signal and its args.
Args:
delegate (Delegate):
delegate object to be injected
signals (list):
list of signal id's to be injected
"""
for signal_id in signals:
signal = delegate.client.state[signal_id] # refactored state
delegate.signals[signal.name] = None
| (delegate: penne.delegates.Delegate, signals: List[penne.delegates.SignalID]) |
727,371 | pydantic.functional_validators | model_validator | Decorate model methods for validation purposes.
Args:
mode: A required string literal that specifies the validation mode.
It can be one of the following: 'wrap', 'before', or 'after'.
Returns:
A decorator that can be used to decorate a function to be used as a model validator.
| def model_validator(
*,
mode: Literal['wrap', 'before', 'after'],
) -> Any:
"""Decorate model methods for validation purposes.
Args:
mode: A required string literal that specifies the validation mode.
It can be one of the following: 'wrap', 'before', or 'after'.
Returns:
A decorator that can be used to decorate a function to be used as a model validator.
"""
def dec(f: Any) -> _decorators.PydanticDescriptorProxy[Any]:
# auto apply the @classmethod decorator
f = _decorators.ensure_classmethod_based_on_signature(f)
dec_info = _decorators.ModelValidatorDecoratorInfo(mode=mode)
return _decorators.PydanticDescriptorProxy(f, dec_info)
return dec
| (*, mode: Literal['wrap', 'before', 'after']) -> Any |
727,376 | openunmix | umx |
Open Unmix 2-channel/stereo BiLSTM Model trained on MUSDB18
Args:
targets (str): select the targets for the source to be separated.
a list including: ['vocals', 'drums', 'bass', 'other'].
If you don't pick them all, you probably want to
activate the `residual=True` option.
Defaults to all available targets per model.
pretrained (bool): If True, returns a model pre-trained on MUSDB18-HQ
residual (bool): if True, a "garbage" target is created
niter (int): the number of post-processingiterations, defaults to 0
device (str): selects device to be used for inference
wiener_win_len (int or None): The size of the excerpts
(number of frames) on which to apply filtering
independently. This means assuming time varying stereo models and
localization of sources.
None means not batching but using the whole signal. It comes at the
price of a much larger memory usage.
filterbank (str): filterbank implementation method.
Supported are `['torch', 'asteroid']`. `torch` is about 30% faster
compared to `asteroid` on large FFT sizes such as 4096. However,
asteroids stft can be exported to onnx, which makes is practical
for deployment.
| def umx(
targets=None,
residual=False,
niter=1,
device="cpu",
pretrained=True,
wiener_win_len=300,
filterbank="torch",
):
"""
Open Unmix 2-channel/stereo BiLSTM Model trained on MUSDB18
Args:
targets (str): select the targets for the source to be separated.
a list including: ['vocals', 'drums', 'bass', 'other'].
If you don't pick them all, you probably want to
activate the `residual=True` option.
Defaults to all available targets per model.
pretrained (bool): If True, returns a model pre-trained on MUSDB18-HQ
residual (bool): if True, a "garbage" target is created
niter (int): the number of post-processingiterations, defaults to 0
device (str): selects device to be used for inference
wiener_win_len (int or None): The size of the excerpts
(number of frames) on which to apply filtering
independently. This means assuming time varying stereo models and
localization of sources.
None means not batching but using the whole signal. It comes at the
price of a much larger memory usage.
filterbank (str): filterbank implementation method.
Supported are `['torch', 'asteroid']`. `torch` is about 30% faster
compared to `asteroid` on large FFT sizes such as 4096. However,
asteroids stft can be exported to onnx, which makes is practical
for deployment.
"""
from .model import Separator
target_models = umx_spec(targets=targets, device=device, pretrained=pretrained)
separator = Separator(
target_models=target_models,
niter=niter,
residual=residual,
n_fft=4096,
n_hop=1024,
nb_channels=2,
sample_rate=44100.0,
wiener_win_len=wiener_win_len,
filterbank=filterbank,
).to(device)
return separator
| (targets=None, residual=False, niter=1, device='cpu', pretrained=True, wiener_win_len=300, filterbank='torch') |
727,377 | openunmix | umx_spec | null | def umx_spec(targets=None, device="cpu", pretrained=True):
from .model import OpenUnmix
# set urls for weights
target_urls = {
"bass": "https://zenodo.org/records/3370486/files/bass-646024d3.pth",
"drums": "https://zenodo.org/records/3370486/files/drums-5a48008b.pth",
"other": "https://zenodo.org/records/3370486/files/other-f8e132cc.pth",
"vocals": "https://zenodo.org/records/3370486/files/vocals-c8df74a5.pth",
}
if targets is None:
targets = ["vocals", "drums", "bass", "other"]
# determine the maximum bin count for a 16khz bandwidth model
max_bin = utils.bandwidth_to_max_bin(rate=44100.0, n_fft=4096, bandwidth=16000)
target_models = {}
for target in targets:
# load open unmix model
target_unmix = OpenUnmix(nb_bins=4096 // 2 + 1, nb_channels=2, hidden_size=512, max_bin=max_bin)
# enable centering of stft to minimize reconstruction error
if pretrained:
state_dict = torch.hub.load_state_dict_from_url(target_urls[target], map_location=device)
target_unmix.load_state_dict(state_dict, strict=False)
target_unmix.eval()
target_unmix.to(device)
target_models[target] = target_unmix
return target_models
| (targets=None, device='cpu', pretrained=True) |
727,378 | openunmix | umxhq |
Open Unmix 2-channel/stereo BiLSTM Model trained on MUSDB18-HQ
Args:
targets (str): select the targets for the source to be separated.
a list including: ['vocals', 'drums', 'bass', 'other'].
If you don't pick them all, you probably want to
activate the `residual=True` option.
Defaults to all available targets per model.
pretrained (bool): If True, returns a model pre-trained on MUSDB18-HQ
residual (bool): if True, a "garbage" target is created
niter (int): the number of post-processingiterations, defaults to 0
device (str): selects device to be used for inference
wiener_win_len (int or None): The size of the excerpts
(number of frames) on which to apply filtering
independently. This means assuming time varying stereo models and
localization of sources.
None means not batching but using the whole signal. It comes at the
price of a much larger memory usage.
filterbank (str): filterbank implementation method.
Supported are `['torch', 'asteroid']`. `torch` is about 30% faster
compared to `asteroid` on large FFT sizes such as 4096. However,
asteroids stft can be exported to onnx, which makes is practical
for deployment.
| def umxhq(
targets=None,
residual=False,
niter=1,
device="cpu",
pretrained=True,
wiener_win_len=300,
filterbank="torch",
):
"""
Open Unmix 2-channel/stereo BiLSTM Model trained on MUSDB18-HQ
Args:
targets (str): select the targets for the source to be separated.
a list including: ['vocals', 'drums', 'bass', 'other'].
If you don't pick them all, you probably want to
activate the `residual=True` option.
Defaults to all available targets per model.
pretrained (bool): If True, returns a model pre-trained on MUSDB18-HQ
residual (bool): if True, a "garbage" target is created
niter (int): the number of post-processingiterations, defaults to 0
device (str): selects device to be used for inference
wiener_win_len (int or None): The size of the excerpts
(number of frames) on which to apply filtering
independently. This means assuming time varying stereo models and
localization of sources.
None means not batching but using the whole signal. It comes at the
price of a much larger memory usage.
filterbank (str): filterbank implementation method.
Supported are `['torch', 'asteroid']`. `torch` is about 30% faster
compared to `asteroid` on large FFT sizes such as 4096. However,
asteroids stft can be exported to onnx, which makes is practical
for deployment.
"""
from .model import Separator
target_models = umxhq_spec(targets=targets, device=device, pretrained=pretrained)
separator = Separator(
target_models=target_models,
niter=niter,
residual=residual,
n_fft=4096,
n_hop=1024,
nb_channels=2,
sample_rate=44100.0,
wiener_win_len=wiener_win_len,
filterbank=filterbank,
).to(device)
return separator
| (targets=None, residual=False, niter=1, device='cpu', pretrained=True, wiener_win_len=300, filterbank='torch') |
727,379 | openunmix | umxhq_spec | null | def umxhq_spec(targets=None, device="cpu", pretrained=True):
from .model import OpenUnmix
# set urls for weights
target_urls = {
"bass": "https://zenodo.org/records/3370489/files/bass-8d85a5bd.pth",
"drums": "https://zenodo.org/records/3370489/files/drums-9619578f.pth",
"other": "https://zenodo.org/records/3370489/files/other-b52fbbf7.pth",
"vocals": "https://zenodo.org/records/3370489/files/vocals-b62c91ce.pth",
}
if targets is None:
targets = ["vocals", "drums", "bass", "other"]
# determine the maximum bin count for a 16khz bandwidth model
max_bin = utils.bandwidth_to_max_bin(rate=44100.0, n_fft=4096, bandwidth=16000)
target_models = {}
for target in targets:
# load open unmix model
target_unmix = OpenUnmix(nb_bins=4096 // 2 + 1, nb_channels=2, hidden_size=512, max_bin=max_bin)
# enable centering of stft to minimize reconstruction error
if pretrained:
state_dict = torch.hub.load_state_dict_from_url(target_urls[target], map_location=device)
target_unmix.load_state_dict(state_dict, strict=False)
target_unmix.eval()
target_unmix.to(device)
target_models[target] = target_unmix
return target_models
| (targets=None, device='cpu', pretrained=True) |
727,380 | openunmix | umxl |
Open Unmix Extra (UMX-L), 2-channel/stereo BLSTM Model trained on a private dataset
of ~400h of multi-track audio.
Args:
targets (str): select the targets for the source to be separated.
a list including: ['vocals', 'drums', 'bass', 'other'].
If you don't pick them all, you probably want to
activate the `residual=True` option.
Defaults to all available targets per model.
pretrained (bool): If True, returns a model pre-trained on MUSDB18-HQ
residual (bool): if True, a "garbage" target is created
niter (int): the number of post-processingiterations, defaults to 0
device (str): selects device to be used for inference
wiener_win_len (int or None): The size of the excerpts
(number of frames) on which to apply filtering
independently. This means assuming time varying stereo models and
localization of sources.
None means not batching but using the whole signal. It comes at the
price of a much larger memory usage.
filterbank (str): filterbank implementation method.
Supported are `['torch', 'asteroid']`. `torch` is about 30% faster
compared to `asteroid` on large FFT sizes such as 4096. However,
asteroids stft can be exported to onnx, which makes is practical
for deployment.
| def umxl(
targets=None,
residual=False,
niter=1,
device="cpu",
pretrained=True,
wiener_win_len=300,
filterbank="torch",
):
"""
Open Unmix Extra (UMX-L), 2-channel/stereo BLSTM Model trained on a private dataset
of ~400h of multi-track audio.
Args:
targets (str): select the targets for the source to be separated.
a list including: ['vocals', 'drums', 'bass', 'other'].
If you don't pick them all, you probably want to
activate the `residual=True` option.
Defaults to all available targets per model.
pretrained (bool): If True, returns a model pre-trained on MUSDB18-HQ
residual (bool): if True, a "garbage" target is created
niter (int): the number of post-processingiterations, defaults to 0
device (str): selects device to be used for inference
wiener_win_len (int or None): The size of the excerpts
(number of frames) on which to apply filtering
independently. This means assuming time varying stereo models and
localization of sources.
None means not batching but using the whole signal. It comes at the
price of a much larger memory usage.
filterbank (str): filterbank implementation method.
Supported are `['torch', 'asteroid']`. `torch` is about 30% faster
compared to `asteroid` on large FFT sizes such as 4096. However,
asteroids stft can be exported to onnx, which makes is practical
for deployment.
"""
from .model import Separator
target_models = umxl_spec(targets=targets, device=device, pretrained=pretrained)
separator = Separator(
target_models=target_models,
niter=niter,
residual=residual,
n_fft=4096,
n_hop=1024,
nb_channels=2,
sample_rate=44100.0,
wiener_win_len=wiener_win_len,
filterbank=filterbank,
).to(device)
return separator
| (targets=None, residual=False, niter=1, device='cpu', pretrained=True, wiener_win_len=300, filterbank='torch') |
727,381 | openunmix | umxl_spec | null | def umxl_spec(targets=None, device="cpu", pretrained=True):
from .model import OpenUnmix
# set urls for weights
target_urls = {
"bass": "https://zenodo.org/records/5069601/files/bass-2ca1ce51.pth",
"drums": "https://zenodo.org/records/5069601/files/drums-69e0ebd4.pth",
"other": "https://zenodo.org/records/5069601/files/other-c8c5b3e6.pth",
"vocals": "https://zenodo.org/records/5069601/files/vocals-bccbd9aa.pth",
}
if targets is None:
targets = ["vocals", "drums", "bass", "other"]
# determine the maximum bin count for a 16khz bandwidth model
max_bin = utils.bandwidth_to_max_bin(rate=44100.0, n_fft=4096, bandwidth=16000)
target_models = {}
for target in targets:
# load open unmix model
target_unmix = OpenUnmix(nb_bins=4096 // 2 + 1, nb_channels=2, hidden_size=1024, max_bin=max_bin)
# enable centering of stft to minimize reconstruction error
if pretrained:
state_dict = torch.hub.load_state_dict_from_url(target_urls[target], map_location=device)
target_unmix.load_state_dict(state_dict, strict=False)
target_unmix.eval()
target_unmix.to(device)
target_models[target] = target_unmix
return target_models
| (targets=None, device='cpu', pretrained=True) |
727,382 | openunmix | umxse |
Open Unmix Speech Enhancemennt 1-channel BiLSTM Model
trained on the 28-speaker version of Voicebank+Demand
(Sampling rate: 16kHz)
Args:
targets (str): select the targets for the source to be separated.
a list including: ['speech', 'noise'].
If you don't pick them all, you probably want to
activate the `residual=True` option.
Defaults to all available targets per model.
pretrained (bool): If True, returns a model pre-trained on MUSDB18-HQ
residual (bool): if True, a "garbage" target is created
niter (int): the number of post-processingiterations, defaults to 0
device (str): selects device to be used for inference
wiener_win_len (int or None): The size of the excerpts
(number of frames) on which to apply filtering
independently. This means assuming time varying stereo models and
localization of sources.
None means not batching but using the whole signal. It comes at the
price of a much larger memory usage.
filterbank (str): filterbank implementation method.
Supported are `['torch', 'asteroid']`. `torch` is about 30% faster
compared to `asteroid` on large FFT sizes such as 4096. However,
asteroids stft can be exported to onnx, which makes is practical
for deployment.
Reference:
Uhlich, Stefan, & Mitsufuji, Yuki. (2020).
Open-Unmix for Speech Enhancement (UMX SE).
Zenodo. http://doi.org/10.5281/zenodo.3786908
| def umxse(targets=None, residual=False, niter=1, device="cpu", pretrained=True, filterbank="torch", wiener_win_len=300):
"""
Open Unmix Speech Enhancemennt 1-channel BiLSTM Model
trained on the 28-speaker version of Voicebank+Demand
(Sampling rate: 16kHz)
Args:
targets (str): select the targets for the source to be separated.
a list including: ['speech', 'noise'].
If you don't pick them all, you probably want to
activate the `residual=True` option.
Defaults to all available targets per model.
pretrained (bool): If True, returns a model pre-trained on MUSDB18-HQ
residual (bool): if True, a "garbage" target is created
niter (int): the number of post-processingiterations, defaults to 0
device (str): selects device to be used for inference
wiener_win_len (int or None): The size of the excerpts
(number of frames) on which to apply filtering
independently. This means assuming time varying stereo models and
localization of sources.
None means not batching but using the whole signal. It comes at the
price of a much larger memory usage.
filterbank (str): filterbank implementation method.
Supported are `['torch', 'asteroid']`. `torch` is about 30% faster
compared to `asteroid` on large FFT sizes such as 4096. However,
asteroids stft can be exported to onnx, which makes is practical
for deployment.
Reference:
Uhlich, Stefan, & Mitsufuji, Yuki. (2020).
Open-Unmix for Speech Enhancement (UMX SE).
Zenodo. http://doi.org/10.5281/zenodo.3786908
"""
from .model import Separator
target_models = umxse_spec(targets=targets, device=device, pretrained=pretrained)
separator = Separator(
target_models=target_models,
niter=niter,
residual=residual,
n_fft=1024,
n_hop=512,
nb_channels=1,
sample_rate=16000.0,
wiener_win_len=wiener_win_len,
filterbank=filterbank,
).to(device)
return separator
| (targets=None, residual=False, niter=1, device='cpu', pretrained=True, filterbank='torch', wiener_win_len=300) |
727,383 | openunmix | umxse_spec | null | def umxse_spec(targets=None, device="cpu", pretrained=True):
target_urls = {
"speech": "https://zenodo.org/records/3786908/files/speech_f5e0d9f9.pth",
"noise": "https://zenodo.org/records/3786908/files/noise_04a6fc2d.pth",
}
from .model import OpenUnmix
if targets is None:
targets = ["speech", "noise"]
# determine the maximum bin count for a 16khz bandwidth model
max_bin = utils.bandwidth_to_max_bin(rate=16000.0, n_fft=1024, bandwidth=16000)
# load open unmix models speech enhancement models
target_models = {}
for target in targets:
target_unmix = OpenUnmix(nb_bins=1024 // 2 + 1, nb_channels=1, hidden_size=256, max_bin=max_bin)
# enable centering of stft to minimize reconstruction error
if pretrained:
state_dict = torch.hub.load_state_dict_from_url(target_urls[target], map_location=device)
target_unmix.load_state_dict(state_dict, strict=False)
target_unmix.eval()
target_unmix.to(device)
target_models[target] = target_unmix
return target_models
| (targets=None, device='cpu', pretrained=True) |
727,414 | d8s_lists.iterables | cycle | Cycle through the iterable as much as needed. | def cycle(iterable: Iterable[Any], length: Optional[int] = None) -> Iterator[Any]:
"""Cycle through the iterable as much as needed."""
full_cycle = itertools.cycle(iterable)
if length:
for index, item in enumerate(full_cycle):
yield item
if index == length - 1:
break
else:
return full_cycle
| (iterable: Iterable[Any], length: Optional[int] = None) -> Iterator[Any] |
727,418 | d8s_lists.iterables | duplicates | Find duplicates in the given iterable. | def duplicates(iterable: Sequence) -> Iterator[Sequence]:
"""Find duplicates in the given iterable."""
for item in iterable:
if iterable.count(item) > 1:
yield item
| (iterable: Sequence) -> Iterator[Sequence] |
727,419 | d8s_lists.iterables | flatten | Flatten all items in the iterable so that they are all items in the same list. | def flatten(iterable: Iterable[Any], level: int = None, **kwargs) -> Iterator[Any]:
"""Flatten all items in the iterable so that they are all items in the same list."""
import more_itertools
return more_itertools.collapse(iterable, levels=level, **kwargs)
| (iterable: Iterable[Any], level: Optional[int] = None, **kwargs) -> Iterator[Any] |
727,421 | d8s_lists.iterables | iterable_all_items_of_types | Return True if all items in the iterable are of a type given in item_types. Otherwise, return False. | def iterable_all_items_of_types(iterable: Iterable[Any], item_types: Iterable[type]) -> bool:
"""Return True if all items in the iterable are of a type given in item_types. Otherwise, return False."""
for i in iterable:
if type(i) not in item_types:
return False
return True
| (iterable: Iterable[Any], item_types: Iterable[type]) -> bool |
727,422 | d8s_lists.iterables | iterable_count | Count each item in the iterable. | def iterable_count(iterable: Iterable[Any]) -> Dict[Any, int]:
"""Count each item in the iterable."""
counter: Counter = Counter()
counter.update(iterable)
count = dict_sort_by_values(counter)
return count
| (iterable: Iterable[Any]) -> Dict[Any, int] |
727,423 | d8s_lists.iterables | iterable_has_all_items_of_type | Return whether or not all iterable in iterable are of the type specified by the type_arg. | def iterable_has_all_items_of_type(iterable: Iterable[Any], type_arg: type) -> bool:
"""Return whether or not all iterable in iterable are of the type specified by the type_arg."""
for i in iterable:
if type(i) != type_arg:
return False
return True
| (iterable: Iterable[Any], type_arg: type) -> bool |
727,424 | d8s_lists.iterables | iterable_has_mixed_types | Return whether or not the iterable has items with two or more types. | def iterable_has_mixed_types(iterable: Iterable[Any]) -> bool:
"""Return whether or not the iterable has items with two or more types."""
return len(tuple(deduplicate(types(iterable)))) >= 2
| (iterable: Iterable[Any]) -> bool |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.