code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def legend_is_glyph(self, legend: str) -> str | None: """Return glyph name if a given legend refers to a glyph and None otherwise.""" if (name := self._legend_to_name(legend)) and name in self.name_to_svg: return name return None
Return glyph name if a given legend refers to a glyph and None otherwise.
legend_is_glyph
python
caksoylar/keymap-drawer
keymap_drawer/draw/glyph.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/draw/glyph.py
MIT
def get_glyph_defs(self) -> str: """Return an SVG defs block with all glyph SVG definitions to be referred to later on.""" if not self.name_to_svg: return "" defs = "<defs>/* start glyphs */\n" for name, svg in sorted(self.name_to_svg.items()): defs += f'<svg id=...
Return an SVG defs block with all glyph SVG definitions to be referred to later on.
get_glyph_defs
python
caksoylar/keymap-drawer
keymap_drawer/draw/glyph.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/draw/glyph.py
MIT
def get_glyph_dimensions(self, name: str, legend_type: str) -> tuple[float, float, float, float]: """Given a glyph name, calculate and return its width, height and y-offset for drawing.""" view_box = self._view_box_dimensions_re.match(self.name_to_svg[name]) assert view_box is not None _...
Given a glyph name, calculate and return its width, height and y-offset for drawing.
get_glyph_dimensions
python
caksoylar/keymap-drawer
keymap_drawer/draw/glyph.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/draw/glyph.py
MIT
def _fetch_svg_url(name: str, url: str, use_local_cache: bool = False) -> str: """Get an SVG glyph definition from url, using the local cache for reading and writing if enabled.""" cache_path = CACHE_GLYPHS_PATH / f"{name.replace('/', '@')}.svg" if use_local_cache and cache_path.is_file(): logger.de...
Get an SVG glyph definition from url, using the local cache for reading and writing if enabled.
_fetch_svg_url
python
caksoylar/keymap-drawer
keymap_drawer/draw/glyph.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/draw/glyph.py
MIT
def _parse(self, in_str: str, file_name: str | None = None) -> tuple[dict, KeymapData]: """ Parse a Kanata keymap with its content and path and return the layout spec and KeymapData to be dumped to YAML. """ nodes = self._parse_cfg(in_str, Path(file_name) if file_name else None) ...
Parse a Kanata keymap with its content and path and return the layout spec and KeymapData to be dumped to YAML.
_parse
python
caksoylar/keymap-drawer
keymap_drawer/parse/kanata.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/parse/kanata.py
MIT
def parse_modifier_fns(self, keycode: str) -> tuple[str, list[str]]: """ Strip potential modifier functions from the keycode then return a tuple of the keycode and the modifiers. """ if self.cfg.modifier_fn_map is None: return keycode, [] def strip_modifiers(keycode:...
Strip potential modifier functions from the keycode then return a tuple of the keycode and the modifiers.
parse_modifier_fns
python
caksoylar/keymap-drawer
keymap_drawer/parse/parse.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/parse/parse.py
MIT
def format_modified_keys(self, key_str: str, modifiers: list[str]) -> str: """ Format the combination of modifier functions and modified keycode into their display form, as configured by parse_config.modifier_fn_map. """ if self.cfg.modifier_fn_map is None or not modifiers: ...
Format the combination of modifier functions and modified keycode into their display form, as configured by parse_config.modifier_fn_map.
format_modified_keys
python
caksoylar/keymap-drawer
keymap_drawer/parse/parse.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/parse/parse.py
MIT
def update_layer_names(self, names: list[str]) -> None: """Update layer names to given list, then update legends.""" assert self.layer_names is None # make sure they weren't preset self.layer_names = names logger.debug("updated layer names: %s", self.layer_names) self._update_l...
Update layer names to given list, then update legends.
update_layer_names
python
caksoylar/keymap-drawer
keymap_drawer/parse/parse.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/parse/parse.py
MIT
def _update_layer_legends(self) -> None: """Create layer legends from layer_legend_map in parse_config and inferred/provided layer names.""" assert self.layer_names is not None for name in self.cfg.layer_legend_map: if name not in self.layer_names + self.virtual_layers: ...
Create layer legends from layer_legend_map in parse_config and inferred/provided layer names.
_update_layer_legends
python
caksoylar/keymap-drawer
keymap_drawer/parse/parse.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/parse/parse.py
MIT
def update_layer_activated_from( self, from_layers: Sequence[int], to_layer: int, key_positions: Sequence[int] ) -> None: """ Update the data structure that keeps track of what keys were held (i.e. momentary layer keys) in order to activate a given layer. Also considers what keys wer...
Update the data structure that keeps track of what keys were held (i.e. momentary layer keys) in order to activate a given layer. Also considers what keys were already being held in order to activate the `from_layers` that the `to_layer` is being activated from. `from_layers` can be em...
update_layer_activated_from
python
caksoylar/keymap-drawer
keymap_drawer/parse/parse.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/parse/parse.py
MIT
def add_held_keys(self, layers: dict[str, list[LayoutKey]]) -> dict[str, list[LayoutKey]]: """Add "held" specifiers to keys that we previously determined were held to activate a given layer.""" assert self.layer_names is not None # handle conditional layers for then_layer, if_layers in ...
Add "held" specifiers to keys that we previously determined were held to activate a given layer.
add_held_keys
python
caksoylar/keymap-drawer
keymap_drawer/parse/parse.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/parse/parse.py
MIT
def append_virtual_layers(self, layers: dict[str, list[LayoutKey]]) -> dict[str, list[LayoutKey]]: """Add blank "virtual" layers at the end of the keymap, for use in later visualization.""" layer_length = max( (len(layer) for layer in layers.values()), default=0 ) # should all be eq...
Add blank "virtual" layers at the end of the keymap, for use in later visualization.
append_virtual_layers
python
caksoylar/keymap-drawer
keymap_drawer/parse/parse.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/parse/parse.py
MIT
def parse(self, in_buf: TextIOWrapper) -> dict: """Wrapper to call parser on a file handle and do post-processing after firmware-specific parsing.""" layout, keymap_data = self._parse(in_buf.read(), in_buf.name) logger.debug("inferred physical layout: %s", layout) if self.base_keymap is...
Wrapper to call parser on a file handle and do post-processing after firmware-specific parsing.
parse
python
caksoylar/keymap-drawer
keymap_drawer/parse/parse.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/parse/parse.py
MIT
def _parse(self, in_str: str, file_name: str | None = None) -> tuple[dict, KeymapData]: """ Parse a JSON keymap with its file content and path (unused), then return the layout spec and KeymapData to be dumped to YAML. """ raw = json.loads(in_str) layout = {} if ...
Parse a JSON keymap with its file content and path (unused), then return the layout spec and KeymapData to be dumped to YAML.
_parse
python
caksoylar/keymap-drawer
keymap_drawer/parse/qmk.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/parse/qmk.py
MIT
def _parse(self, in_str: str, file_name: str | None = None) -> tuple[dict, KeymapData]: """ Parse a ZMK keymap with its content and path and return the layout spec and KeymapData to be dumped to YAML. """ dts = DeviceTree( in_str, file_name, self.cfg.p...
Parse a ZMK keymap with its content and path and return the layout spec and KeymapData to be dumped to YAML.
_parse
python
caksoylar/keymap-drawer
keymap_drawer/parse/zmk.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/parse/zmk.py
MIT
def parse_prompt_attention(self, text): """ Parses a string with attention tokens and returns a list of pairs: text and its associated weight. Accepted tokens are: (abc) - increases attention to abc by a multiplier of 1.1 (abc:3.12) - increases attention to abc by a multiplier of...
Parses a string with attention tokens and returns a list of pairs: text and its associated weight. Accepted tokens are: (abc) - increases attention to abc by a multiplier of 1.1 (abc:3.12) - increases attention to abc by a multiplier of 3.12 [abc] - decreases attention to abc by...
parse_prompt_attention
python
instantX-research/InstantID
pipeline_stable_diffusion_xl_instantid_full.py
https://github.com/instantX-research/InstantID/blob/master/pipeline_stable_diffusion_xl_instantid_full.py
Apache-2.0
def get_prompts_tokens_with_weights(self, clip_tokenizer: CLIPTokenizer, prompt: str): """ Get prompt token ids and weights, this function works for both prompt and negative prompt Args: pipe (CLIPTokenizer) A CLIPTokenizer prompt (str) A ...
Get prompt token ids and weights, this function works for both prompt and negative prompt Args: pipe (CLIPTokenizer) A CLIPTokenizer prompt (str) A prompt string with weights Returns: text_tokens (list) A list...
get_prompts_tokens_with_weights
python
instantX-research/InstantID
pipeline_stable_diffusion_xl_instantid_full.py
https://github.com/instantX-research/InstantID/blob/master/pipeline_stable_diffusion_xl_instantid_full.py
Apache-2.0
def group_tokens_and_weights(self, token_ids: list, weights: list, pad_last_block=False): """ Produce tokens and weights in groups and pad the missing tokens Args: token_ids (list) The token ids from tokenizer weights (list) The weights li...
Produce tokens and weights in groups and pad the missing tokens Args: token_ids (list) The token ids from tokenizer weights (list) The weights list from function get_prompts_tokens_with_weights pad_last_block (bool) Co...
group_tokens_and_weights
python
instantX-research/InstantID
pipeline_stable_diffusion_xl_instantid_full.py
https://github.com/instantX-research/InstantID/blob/master/pipeline_stable_diffusion_xl_instantid_full.py
Apache-2.0
def STEmbedding(SE, TE, T, D, bn, bn_decay, is_training): ''' spatio-temporal embedding SE: [N, D] TE: [batch_size, P + Q, 2] (dayofweek, timeofday) T: num of time steps in one day D: output dims retrun: [batch_size, P + Q, N, D] ''' # spatial embedding SE = tf....
spatio-temporal embedding SE: [N, D] TE: [batch_size, P + Q, 2] (dayofweek, timeofday) T: num of time steps in one day D: output dims retrun: [batch_size, P + Q, N, D]
STEmbedding
python
zhengchuanpan/GMAN
METR/model.py
https://github.com/zhengchuanpan/GMAN/blob/master/METR/model.py
Apache-2.0
def spatialAttention(X, STE, K, d, bn, bn_decay, is_training): ''' spatial attention mechanism X: [batch_size, num_step, N, D] STE: [batch_size, num_step, N, D] K: number of attention heads d: dimension of each attention outputs return: [batch_size, num_step, N, D] ''' ...
spatial attention mechanism X: [batch_size, num_step, N, D] STE: [batch_size, num_step, N, D] K: number of attention heads d: dimension of each attention outputs return: [batch_size, num_step, N, D]
spatialAttention
python
zhengchuanpan/GMAN
METR/model.py
https://github.com/zhengchuanpan/GMAN/blob/master/METR/model.py
Apache-2.0
def temporalAttention(X, STE, K, d, bn, bn_decay, is_training, mask = True): ''' temporal attention mechanism X: [batch_size, num_step, N, D] STE: [batch_size, num_step, N, D] K: number of attention heads d: dimension of each attention outputs return: [batch_size, num_step,...
temporal attention mechanism X: [batch_size, num_step, N, D] STE: [batch_size, num_step, N, D] K: number of attention heads d: dimension of each attention outputs return: [batch_size, num_step, N, D]
temporalAttention
python
zhengchuanpan/GMAN
METR/model.py
https://github.com/zhengchuanpan/GMAN/blob/master/METR/model.py
Apache-2.0
def gatedFusion(HS, HT, D, bn, bn_decay, is_training): ''' gated fusion HS: [batch_size, num_step, N, D] HT: [batch_size, num_step, N, D] D: output dims return: [batch_size, num_step, N, D] ''' XS = FC( HS, units = D, activations = None, bn = bn, bn_decay = b...
gated fusion HS: [batch_size, num_step, N, D] HT: [batch_size, num_step, N, D] D: output dims return: [batch_size, num_step, N, D]
gatedFusion
python
zhengchuanpan/GMAN
METR/model.py
https://github.com/zhengchuanpan/GMAN/blob/master/METR/model.py
Apache-2.0
def transformAttention(X, STE_P, STE_Q, K, d, bn, bn_decay, is_training): ''' transform attention mechanism X: [batch_size, P, N, D] STE_P: [batch_size, P, N, D] STE_Q: [batch_size, Q, N, D] K: number of attention heads d: dimension of each attention outputs return: [bat...
transform attention mechanism X: [batch_size, P, N, D] STE_P: [batch_size, P, N, D] STE_Q: [batch_size, Q, N, D] K: number of attention heads d: dimension of each attention outputs return: [batch_size, Q, N, D]
transformAttention
python
zhengchuanpan/GMAN
METR/model.py
https://github.com/zhengchuanpan/GMAN/blob/master/METR/model.py
Apache-2.0
def node2vec_walk(self, walk_length, start_node): ''' Simulate a random walk starting from start node. ''' G = self.G alias_nodes = self.alias_nodes alias_edges = self.alias_edges walk = [start_node] while len(walk) < walk_length: cur = walk[-1] cur_nbrs = sorted(G.neighbors(cur)) if len(cur_...
Simulate a random walk starting from start node.
node2vec_walk
python
zhengchuanpan/GMAN
METR/node2vec/node2vec.py
https://github.com/zhengchuanpan/GMAN/blob/master/METR/node2vec/node2vec.py
Apache-2.0
def simulate_walks(self, num_walks, walk_length): ''' Repeatedly simulate random walks from each node. ''' G = self.G walks = [] nodes = list(G.nodes()) print ('Walk iteration:') for walk_iter in range(num_walks): print (str(walk_iter+1), '/', str(num_walks)) random.shuffle(nodes) for node in n...
Repeatedly simulate random walks from each node.
simulate_walks
python
zhengchuanpan/GMAN
METR/node2vec/node2vec.py
https://github.com/zhengchuanpan/GMAN/blob/master/METR/node2vec/node2vec.py
Apache-2.0
def get_alias_edge(self, src, dst): ''' Get the alias edge setup lists for a given edge. ''' G = self.G p = self.p q = self.q unnormalized_probs = [] for dst_nbr in sorted(G.neighbors(dst)): if dst_nbr == src: unnormalized_probs.append(G[dst][dst_nbr]['weight']/p) elif G.has_edge(dst_nbr, src...
Get the alias edge setup lists for a given edge.
get_alias_edge
python
zhengchuanpan/GMAN
METR/node2vec/node2vec.py
https://github.com/zhengchuanpan/GMAN/blob/master/METR/node2vec/node2vec.py
Apache-2.0
def preprocess_transition_probs(self): ''' Preprocessing of transition probabilities for guiding the random walks. ''' G = self.G is_directed = self.is_directed alias_nodes = {} for node in G.nodes(): unnormalized_probs = [G[node][nbr]['weight'] for nbr in sorted(G.neighbors(node))] norm_const = su...
Preprocessing of transition probabilities for guiding the random walks.
preprocess_transition_probs
python
zhengchuanpan/GMAN
METR/node2vec/node2vec.py
https://github.com/zhengchuanpan/GMAN/blob/master/METR/node2vec/node2vec.py
Apache-2.0
def alias_setup(probs): ''' Compute utility lists for non-uniform sampling from discrete distributions. Refer to https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/ for details ''' K = len(probs) q = np.zeros(K) J = np.zeros(K, dtype=np.int) smaller =...
Compute utility lists for non-uniform sampling from discrete distributions. Refer to https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/ for details
alias_setup
python
zhengchuanpan/GMAN
METR/node2vec/node2vec.py
https://github.com/zhengchuanpan/GMAN/blob/master/METR/node2vec/node2vec.py
Apache-2.0
def alias_draw(J, q): ''' Draw sample from a non-uniform discrete distribution using alias sampling. ''' K = len(J) kk = int(np.floor(np.random.rand()*K)) if np.random.rand() < q[kk]: return kk else: return J[kk]
Draw sample from a non-uniform discrete distribution using alias sampling.
alias_draw
python
zhengchuanpan/GMAN
METR/node2vec/node2vec.py
https://github.com/zhengchuanpan/GMAN/blob/master/METR/node2vec/node2vec.py
Apache-2.0
async def async_get_access_token(self) -> str: """Get access token using master token.""" def _get_access_token() -> str | None: return self._client.get_access_token() access_token = await self.hass.async_add_executor_job(_get_access_token) if access_token is None: ...
Get access token using master token.
async_get_access_token
python
leikoilja/ha-google-home
custom_components/google_home/api.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/api.py
MIT
async def get_google_devices(self) -> list[GoogleHomeDevice]: """Get google device authentication tokens. Note this method will fetch necessary access tokens if missing. """ if not self.google_devices: def _get_google_devices() -> list[Device]: return self....
Get google device authentication tokens. Note this method will fetch necessary access tokens if missing.
get_google_devices
python
leikoilja/ha-google-home
custom_components/google_home/api.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/api.py
MIT
def create_url(ip_address: str, port: int, api_endpoint: str) -> str: """Create url to endpoint. Note: port argument is unused because all request must be done to 8443. """ if isinstance(ipaddress.ip_address(ip_address), ipaddress.IPv6Address): ip_address = f"[{ip_address}]"...
Create url to endpoint. Note: port argument is unused because all request must be done to 8443.
create_url
python
leikoilja/ha-google-home
custom_components/google_home/api.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/api.py
MIT
async def update_google_devices_information(self) -> list[GoogleHomeDevice]: """Retrieve devices from glocaltokens and fetches alarm/timer data from each of the device.""" devices = await self.get_google_devices() # Gives the user a warning if the device is offline for device in device...
Retrieve devices from glocaltokens and fetches alarm/timer data from each of the device.
update_google_devices_information
python
leikoilja/ha-google-home
custom_components/google_home/api.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/api.py
MIT
async def update_alarms_and_timers( self, device: GoogleHomeDevice ) -> GoogleHomeDevice: """Fetch timers and alarms from google device.""" response = await self.request( method="GET", endpoint=API_ENDPOINT_ALARMS, device=device, polling=True ) if response is not...
Fetch timers and alarms from google device.
update_alarms_and_timers
python
leikoilja/ha-google-home
custom_components/google_home/api.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/api.py
MIT
async def delete_alarm_or_timer( self, device: GoogleHomeDevice, item_to_delete: str ) -> None: """Delete a timer or alarm. Can also delete multiple if a list is provided (Not implemented yet). """ data = {"ids": [item_to_delete]} item_type = item_to_delete.split("...
Delete a timer or alarm. Can also delete multiple if a list is provided (Not implemented yet).
delete_alarm_or_timer
python
leikoilja/ha-google-home
custom_components/google_home/api.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/api.py
MIT
async def reboot_google_device(self, device: GoogleHomeDevice) -> None: """Reboot a Google Home device if it supports this.""" # "now" means reboot and "fdr" means factory reset (Not implemented). data = {"params": "now"} _LOGGER.debug( "Trying to reboot Google Home device ...
Reboot a Google Home device if it supports this.
reboot_google_device
python
leikoilja/ha-google-home
custom_components/google_home/api.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/api.py
MIT
async def update_do_not_disturb( self, device: GoogleHomeDevice, enable: bool | None = None ) -> GoogleHomeDevice: """Get or set the do not disturb setting on a Google Home device.""" data = None polling = False if enable is not None: # Setting is inverted on de...
Get or set the do not disturb setting on a Google Home device.
update_do_not_disturb
python
leikoilja/ha-google-home
custom_components/google_home/api.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/api.py
MIT
async def update_alarm_volume( self, device: GoogleHomeDevice, volume: int | None = None ) -> GoogleHomeDevice: """Get or set the alarm volume setting on a Google Home device.""" data: JsonDict | None = None polling = False if volume is not None: # Setting is in...
Get or set the alarm volume setting on a Google Home device.
update_alarm_volume
python
leikoilja/ha-google-home
custom_components/google_home/api.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/api.py
MIT
async def _show_config_form(self) -> ConfigFlowResult: """Show the configuration form to edit login information.""" return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Optional(CONF_USERNAME): str, vol...
Show the configuration form to edit login information.
_show_config_form
python
leikoilja/ha-google-home
custom_components/google_home/config_flow.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/config_flow.py
MIT
async def _get_master_token(client: GlocaltokensApiClient) -> str: """Return master token if credentials are valid.""" master_token = "" try: master_token = await client.async_get_master_token() except (InvalidMasterToken, RequestException): _LOGGER.exception("Fai...
Return master token if credentials are valid.
_get_master_token
python
leikoilja/ha-google-home
custom_components/google_home/config_flow.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/config_flow.py
MIT
async def _get_access_token(client: GlocaltokensApiClient) -> str: """Return access token if master token is valid.""" access_token = "" try: access_token = await client.async_get_access_token() except (InvalidMasterToken, RequestException): _LOGGER.exception("Fai...
Return access token if master token is valid.
_get_access_token
python
leikoilja/ha-google-home
custom_components/google_home/config_flow.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/config_flow.py
MIT
def get_device(self) -> GoogleHomeDevice | None: """Return the device matched by device name from the list of google devices in coordinator_data.""" matched_devices: list[GoogleHomeDevice] = [ device for device in self.coordinator.data if device.device_id == self.devi...
Return the device matched by device name from the list of google devices in coordinator_data.
get_device
python
leikoilja/ha-google-home
custom_components/google_home/entity.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/entity.py
MIT
def get_sorted_alarms(self) -> list[GoogleHomeAlarm]: """Return alarms in a sorted order. Inactive & missed alarms are at the end.""" return sorted( self._alarms, key=lambda k: ( k.fire_time if k.status not in (GoogleHomeAlarmStatus...
Return alarms in a sorted order. Inactive & missed alarms are at the end.
get_sorted_alarms
python
leikoilja/ha-google-home
custom_components/google_home/models.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/models.py
MIT
def get_sorted_timers(self) -> list[GoogleHomeTimer]: """Return timers in a sorted order. If timer is paused, put it in the end.""" return sorted( self._timers, key=lambda k: k.fire_time if k.fire_time is not None else sys.maxsize, )
Return timers in a sorted order. If timer is paused, put it in the end.
get_sorted_timers
python
leikoilja/ha-google-home
custom_components/google_home/models.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/models.py
MIT
def state(self) -> str | None: """Return device IP address if any.""" device = self.get_device() return device.ip_address if device else None
Return device IP address if any.
state
python
leikoilja/ha-google-home
custom_components/google_home/sensor.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/sensor.py
MIT
def _get_next_alarm_status(self) -> str: """Update next alarm status from coordinator.""" device = self.get_device() next_alarm = device.get_next_alarm() if device else None return ( next_alarm.status.name.lower() if next_alarm else GoogleHomeAlarmStat...
Update next alarm status from coordinator.
_get_next_alarm_status
python
leikoilja/ha-google-home
custom_components/google_home/sensor.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/sensor.py
MIT
def _get_alarm_volume(self) -> float: """Update alarm volume status from coordinator.""" device = self.get_device() alarm_volume = device.get_alarm_volume() if device else None return alarm_volume if alarm_volume else GOOGLE_HOME_ALARM_DEFAULT_VALUE
Update alarm volume status from coordinator.
_get_alarm_volume
python
leikoilja/ha-google-home
custom_components/google_home/sensor.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/sensor.py
MIT
def _get_alarms_data(self) -> list[GoogleHomeAlarmDict]: """Update alarms data extracting it from coordinator.""" device = self.get_device() return ( [alarm.as_dict() for alarm in device.get_sorted_alarms()] if device else [] )
Update alarms data extracting it from coordinator.
_get_alarms_data
python
leikoilja/ha-google-home
custom_components/google_home/sensor.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/sensor.py
MIT
def is_valid_alarm_id(alarm_id: str) -> bool: """Check if the alarm id provided is valid.""" return ( alarm_id.startswith("alarm/") and len(alarm_id) == ALARM_AND_TIMER_ID_LENGTH )
Check if the alarm id provided is valid.
is_valid_alarm_id
python
leikoilja/ha-google-home
custom_components/google_home/sensor.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/sensor.py
MIT
async def async_delete_alarm(self, call: ServiceCall) -> None: """Service call to delete alarm on device.""" device = self.get_device() if device is None: _LOGGER.error("Device %s is not found.", self.device_name) return alarm_id: str = call.data[SERVICE_ATTR_AL...
Service call to delete alarm on device.
async_delete_alarm
python
leikoilja/ha-google-home
custom_components/google_home/sensor.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/sensor.py
MIT
def _get_next_timer_status(self) -> str: """Update next timer status from coordinator.""" device = self.get_device() next_timer = device.get_next_timer() if device else None return ( next_timer.status.name.lower() if next_timer else GoogleHomeTimerStat...
Update next timer status from coordinator.
_get_next_timer_status
python
leikoilja/ha-google-home
custom_components/google_home/sensor.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/sensor.py
MIT
def _get_timers_data(self) -> list[GoogleHomeTimerDict]: """Update timers data extracting it from coordinator.""" device = self.get_device() return ( [timer.as_dict() for timer in device.get_sorted_timers()] if device else [] )
Update timers data extracting it from coordinator.
_get_timers_data
python
leikoilja/ha-google-home
custom_components/google_home/sensor.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/sensor.py
MIT
def is_valid_timer_id(timer_id: str) -> bool: """Check if the timer id provided is valid.""" return ( timer_id.startswith("timer/") and len(timer_id) == ALARM_AND_TIMER_ID_LENGTH )
Check if the timer id provided is valid.
is_valid_timer_id
python
leikoilja/ha-google-home
custom_components/google_home/sensor.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/sensor.py
MIT
def is_on(self) -> bool: """Return true if Do Not Disturb Mode is on.""" device = self.get_device() if device is None: return False return device.get_do_not_disturb()
Return true if Do Not Disturb Mode is on.
is_on
python
leikoilja/ha-google-home
custom_components/google_home/switch.py
https://github.com/leikoilja/ha-google-home/blob/master/custom_components/google_home/switch.py
MIT
def update_manifests(repo: Repository, version: str) -> None: """Update manifest.json and hacs.json.""" print("Updating manifest.json...") manifest = repo.get_contents("custom_components/google_home/manifest.json") assert isinstance(manifest, ContentFile) manifest_json = json.loads(manifest.decoded_...
Update manifest.json and hacs.json.
update_manifests
python
leikoilja/ha-google-home
script/publish_release.py
https://github.com/leikoilja/ha-google-home/blob/master/script/publish_release.py
MIT
def extract_pyproject_info(pyproject_path: Path) -> Dict[str, str]: """ Extract necessary information from pyproject.toml. Args: ---- pyproject_path (Path): Path to the pyproject.toml file. Returns: ------- Dict[str, str]: A dictionary containing the extracted information. ...
Extract necessary information from pyproject.toml. Args: ---- pyproject_path (Path): Path to the pyproject.toml file. Returns: ------- Dict[str, str]: A dictionary containing the extracted information.
extract_pyproject_info
python
superduper-io/superduper
plugins/generate_readme.py
https://github.com/superduper-io/superduper/blob/master/plugins/generate_readme.py
Apache-2.0
def parse_example(docstring: str) -> Optional[List[Dict[str, str]]]: """ Parse the docstring to extract an example with text descriptions and code blocks. Args: ---- docstring (str): The docstring of a class or method. Returns: ------- Optional[List[Dict[str, str]]]: A list of ...
Parse the docstring to extract an example with text descriptions and code blocks. Args: ---- docstring (str): The docstring of a class or method. Returns: ------- Optional[List[Dict[str, str]]]: A list of example parts, each part is a dict w...
parse_example
python
superduper-io/superduper
plugins/generate_readme.py
https://github.com/superduper-io/superduper/blob/master/plugins/generate_readme.py
Apache-2.0
def get_classes_with_docstrings( package_dir: Path, package_name: str ) -> List[Dict[str, Union[str, List[Dict[str, str]]]]]: """ Parse Python files to extract classes and their docstrings. Args: ---- package_dir (Path): Path to the package directory containing Python modules. packa...
Parse Python files to extract classes and their docstrings. Args: ---- package_dir (Path): Path to the package directory containing Python modules. package_name (str): The package's importable name. Returns: ------- List[Dict[str, Union[str, List[Dict[str, str]]]]]: A list...
get_classes_with_docstrings
python
superduper-io/superduper
plugins/generate_readme.py
https://github.com/superduper-io/superduper/blob/master/plugins/generate_readme.py
Apache-2.0
def generate_readme_content( info: Dict[str, str], classes_info: List[Dict[str, Union[str, List[Dict[str, str]]]]], ) -> str: """ Generate the README.md content based on extracted information. :param info: Extracted information from pyproject.toml. :param classes_info: Extracted classes and the...
Generate the README.md content based on extracted information. :param info: Extracted information from pyproject.toml. :param classes_info: Extracted classes and their docstrings.
generate_readme_content
python
superduper-io/superduper
plugins/generate_readme.py
https://github.com/superduper-io/superduper/blob/master/plugins/generate_readme.py
Apache-2.0
def update_readme(readme_path: Path, new_content: str) -> None: """ Update the README.md file with new content, preserving existing sections. Args: ---- readme_path (Path): Path to the README.md file. new_content (str): The new content to insert into the README.md. """ auto_gen...
Update the README.md file with new content, preserving existing sections. Args: ---- readme_path (Path): Path to the README.md file. new_content (str): The new content to insert into the README.md.
update_readme
python
superduper-io/superduper
plugins/generate_readme.py
https://github.com/superduper-io/superduper/blob/master/plugins/generate_readme.py
Apache-2.0
def process_plugin(plugin_dir: Path) -> None: """ Process a single plugin directory to generate or update its README.md. Args: ---- plugin_dir (Path): Path to the plugin directory. """ print(f"Processing plugin at {plugin_dir}") pyproject_path = plugin_dir / "pyproject.toml" if...
Process a single plugin directory to generate or update its README.md. Args: ---- plugin_dir (Path): Path to the plugin directory.
process_plugin
python
superduper-io/superduper
plugins/generate_readme.py
https://github.com/superduper-io/superduper/blob/master/plugins/generate_readme.py
Apache-2.0
def main(): """Main function to process all plugins in the plugins directory.""" parser = argparse.ArgumentParser( description="Generate or update README.md files for plugins." ) parser.add_argument( "plugin_path", nargs="?", default=None, help="Path to the plugin...
Main function to process all plugins in the plugins directory.
main
python
superduper-io/superduper
plugins/generate_readme.py
https://github.com/superduper-io/superduper/blob/master/plugins/generate_readme.py
Apache-2.0
def setup(self, db=None): """Initialize the model. :param db: The database to use. """ self.client = anthropic.Anthropic( api_key=os.environ[KEY_NAME], **self.client_kwargs ) super().setup(db=db)
Initialize the model. :param db: The database to use.
setup
python
superduper-io/superduper
plugins/anthropic/superduper_anthropic/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/anthropic/superduper_anthropic/model.py
Apache-2.0
def predict( self, X: t.Union[str, list[dict]], context: t.Optional[t.List[str]] = None, **kwargs, ): """Generate text from a single input. :param X: The input to generate text from. :param context: The context to use for the prompt. :param kwargs: Th...
Generate text from a single input. :param X: The input to generate text from. :param context: The context to use for the prompt. :param kwargs: The keyword arguments to pass to the prompt function and the llm model.
predict
python
superduper-io/superduper
plugins/anthropic/superduper_anthropic/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/anthropic/superduper_anthropic/model.py
Apache-2.0
def predict(self, X: str): """Predict the embedding of a single text. :param X: The text to predict the embedding of. """ client = cohere.Client(os.environ[KEY_NAME], **self.client_kwargs) e = client.embed(texts=[X], model=self.identifier, **self.predict_kwargs) return e...
Predict the embedding of a single text. :param X: The text to predict the embedding of.
predict
python
superduper-io/superduper
plugins/cohere/superduper_cohere/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/cohere/superduper_cohere/model.py
Apache-2.0
def predict_batches(self, dataset: t.Union[t.List, QueryDataset]) -> t.List: """Predict the embeddings of a dataset. :param dataset: The dataset to predict the embeddings of. """ out = [] for i in tqdm.tqdm(range(0, len(dataset), self.batch_size)): out.extend( ...
Predict the embeddings of a dataset. :param dataset: The dataset to predict the embeddings of.
predict_batches
python
superduper-io/superduper
plugins/cohere/superduper_cohere/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/cohere/superduper_cohere/model.py
Apache-2.0
def predict(self, prompt: str, context: t.Optional[t.List[str]] = None): """Predict the generation of a single prompt. :param prompt: The prompt to generate text from. :param context: The context to use for the prompt. """ if context is not None: prompt = format_prom...
Predict the generation of a single prompt. :param prompt: The prompt to generate text from. :param context: The context to use for the prompt.
predict
python
superduper-io/superduper
plugins/cohere/superduper_cohere/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/cohere/superduper_cohere/model.py
Apache-2.0
def encode_batch(self, texts: List[str]) -> List[List[float]]: """Encode a batch of texts synchronously. :param texts: The list of texts to encode. """ response = self._session.post( JINA_API_URL, json={"input": texts, "model": self.model_name} ).json() if "d...
Encode a batch of texts synchronously. :param texts: The list of texts to encode.
encode_batch
python
superduper-io/superduper
plugins/jina/superduper_jina/client.py
https://github.com/superduper-io/superduper/blob/master/plugins/jina/superduper_jina/client.py
Apache-2.0
async def aencode_batch(self, texts: List[str]) -> List[List[float]]: """Encode a batch of texts asynchronously. :param texts: The list of texts to encode. """ async with aiohttp.ClientSession() as session: payload = { 'model': self.model_name, ...
Encode a batch of texts asynchronously. :param texts: The list of texts to encode.
aencode_batch
python
superduper-io/superduper
plugins/jina/superduper_jina/client.py
https://github.com/superduper-io/superduper/blob/master/plugins/jina/superduper_jina/client.py
Apache-2.0
def add(self, items: t.Sequence[VectorItem], cache: bool = False) -> None: """Add vectors to the index. :param items: List of vectors to add :param cache: Cache vectors. """ ids = [item.id for item in items] vectors = [item.vector for item in items] self._create_...
Add vectors to the index. :param items: List of vectors to add :param cache: Cache vectors.
add
python
superduper-io/superduper
plugins/lance/superduper_lance/lance.py
https://github.com/superduper-io/superduper/blob/master/plugins/lance/superduper_lance/lance.py
Apache-2.0
def delete(self, ids: t.Sequence[str]) -> None: """Delete vectors from the index. :param ids: List of IDs to delete """ to_remove = ", ".join(f"'{str(id)}'" for id in ids) self.dataset.delete(f"id IN ({to_remove})")
Delete vectors from the index. :param ids: List of IDs to delete
delete
python
superduper-io/superduper
plugins/lance/superduper_lance/lance.py
https://github.com/superduper-io/superduper/blob/master/plugins/lance/superduper_lance/lance.py
Apache-2.0
def find_nearest_from_id( self, _id, n: int = 100, within_ids: t.Sequence[str] = (), ) -> t.Tuple[t.List[str], t.List[float]]: """Find the nearest vectors to a given ID. :param _id: ID to search :param n: Number of results to return :param within_ids:...
Find the nearest vectors to a given ID. :param _id: ID to search :param n: Number of results to return :param within_ids: List of IDs to search within
find_nearest_from_id
python
superduper-io/superduper
plugins/lance/superduper_lance/lance.py
https://github.com/superduper-io/superduper/blob/master/plugins/lance/superduper_lance/lance.py
Apache-2.0
def find_nearest_from_array( self, h: np.typing.ArrayLike, n: int = 100, within_ids: t.Sequence[str] = (), ) -> t.Tuple[t.List[str], t.List[float]]: """Find the nearest vectors to a given vector. :param h: Vector to search :param n: Number of results to retur...
Find the nearest vectors to a given vector. :param h: Vector to search :param n: Number of results to return :param within_ids: List of IDs to search within
find_nearest_from_array
python
superduper-io/superduper
plugins/lance/superduper_lance/lance.py
https://github.com/superduper-io/superduper/blob/master/plugins/lance/superduper_lance/lance.py
Apache-2.0
def download_uri(uri, save_path): """Download file. :param uri: URI to download :param save_path: place to save """ response = requests.get(uri) if response.status_code == 200: with open(save_path, 'wb') as file: file.write(response.content) else: raise Exception...
Download file. :param uri: URI to download :param save_path: place to save
download_uri
python
superduper-io/superduper
plugins/llamacpp/superduper_llamacpp/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/llamacpp/superduper_llamacpp/model.py
Apache-2.0
def setup(self): """Initialize the model. If the model_name_or_path is a uri, download it to the download_dir. """ if self.model_name_or_path.startswith('http'): # Download the uri os.makedirs(self.download_dir, exist_ok=True) saved_path = os.path.joi...
Initialize the model. If the model_name_or_path is a uri, download it to the download_dir.
setup
python
superduper-io/superduper
plugins/llamacpp/superduper_llamacpp/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/llamacpp/superduper_llamacpp/model.py
Apache-2.0
def _generate(self, prompt: str, **kwargs) -> str: """Generate embedding from a prompt. :param prompt: The prompt to generate the embedding from. :param kwargs: The keyword arguments to pass to the llm model. """ return self._model.create_embedding( prompt, embedding...
Generate embedding from a prompt. :param prompt: The prompt to generate the embedding from. :param kwargs: The keyword arguments to pass to the llm model.
_generate
python
superduper-io/superduper
plugins/llamacpp/superduper_llamacpp/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/llamacpp/superduper_llamacpp/model.py
Apache-2.0
def drop(self, force: bool = False): """Drop the data backend. Please use with caution as you will lose all data. :param force: Force the drop, default is False. If False, a confirmation prompt will be displayed. """ if not force: if not click.c...
Drop the data backend. Please use with caution as you will lose all data. :param force: Force the drop, default is False. If False, a confirmation prompt will be displayed.
drop
python
superduper-io/superduper
plugins/mongodb/superduper_mongodb/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/mongodb/superduper_mongodb/data_backend.py
Apache-2.0
def replace(self, table: str, condition: t.Dict, r: t.Dict) -> t.List[str]: """Replace data. :param table: The table to insert into. :param condition: The condition to replace. :param r: The data to replace. """ if '_id' in r: del r['_id'] self._datab...
Replace data. :param table: The table to insert into. :param condition: The condition to replace. :param r: The data to replace.
replace
python
superduper-io/superduper
plugins/mongodb/superduper_mongodb/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/mongodb/superduper_mongodb/data_backend.py
Apache-2.0
def missing_outputs(self, query, predict_id: str): """Get the missing outputs for the prediction.""" key = f'{CFG.output_prefix}{predict_id}' lookup = [ { '$lookup': { 'from': key, 'localField': '_id', 'forei...
Get the missing outputs for the prediction.
missing_outputs
python
superduper-io/superduper
plugins/mongodb/superduper_mongodb/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/mongodb/superduper_mongodb/data_backend.py
Apache-2.0
def execute_native(self, query: str): """Execute a native MongoDB pipeline with aggregate. :param query: JSON string with the collection and pipeline as a list. >>> query = '{"collection": "c", "pipeline": [{"$match": {"field": "value"}}]}' >>> backend.execute_native(query) """...
Execute a native MongoDB pipeline with aggregate. :param query: JSON string with the collection and pipeline as a list. >>> query = '{"collection": "c", "pipeline": [{"$match": {"field": "value"}}]}' >>> backend.execute_native(query)
execute_native
python
superduper-io/superduper
plugins/mongodb/superduper_mongodb/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/mongodb/superduper_mongodb/data_backend.py
Apache-2.0
def _get_avaliable_conn(uri: str, **kwargs): """Get an available connection to the database. This can avoid some issues with database permission verification. 1. Try to connect to the database with the given URI. 2. Try to connect to the database with the base URI without database name. :param uri...
Get an available connection to the database. This can avoid some issues with database permission verification. 1. Try to connect to the database with the given URI. 2. Try to connect to the database with the base URI without database name. :param uri: The URI of the database. :param kwargs: Additi...
_get_avaliable_conn
python
superduper-io/superduper
plugins/mongodb/superduper_mongodb/utils.py
https://github.com/superduper-io/superduper/blob/master/plugins/mongodb/superduper_mongodb/utils.py
Apache-2.0
def connection_callback(uri, flavour): """Get the connection to the database. :param uri: The URI of the database. :param flavour: The flavour of the database. """ flavour = uri.split(":")[0] if flavour is None else flavour if flavour == "mongodb": name = uri.split("/")[-1] conn...
Get the connection to the database. :param uri: The URI of the database. :param flavour: The flavour of the database.
connection_callback
python
superduper-io/superduper
plugins/mongodb/superduper_mongodb/utils.py
https://github.com/superduper-io/superduper/blob/master/plugins/mongodb/superduper_mongodb/utils.py
Apache-2.0
def from_component(cls, vi: "VectorIndex"): """Create a vector searcher from a vector index. :param vi: VectorIndex instance """ from superduper.components.listener import Listener assert isinstance(vi.indexing_listener, Listener) assert vi.indexing_listener.select is n...
Create a vector searcher from a vector index. :param vi: VectorIndex instance
from_component
python
superduper-io/superduper
plugins/mongodb/superduper_mongodb/vector_search.py
https://github.com/superduper-io/superduper/blob/master/plugins/mongodb/superduper_mongodb/vector_search.py
Apache-2.0
def delete(self, ids: t.Sequence[str]) -> None: """Remove items from the index. :param ids: t.Sequence of ids of vectors. """
Remove items from the index. :param ids: t.Sequence of ids of vectors.
delete
python
superduper-io/superduper
plugins/mongodb/superduper_mongodb/vector_search.py
https://github.com/superduper-io/superduper/blob/master/plugins/mongodb/superduper_mongodb/vector_search.py
Apache-2.0
def find_nearest_from_id(self, id: str, n=100, within_ids=None): """Find the nearest vectors to the given ID. :param id: ID of the vector :param n: number of nearest vectors to return :param within_ids: list of IDs to search within """ h = self.index.find_one({"_id": id}...
Find the nearest vectors to the given ID. :param id: ID of the vector :param n: number of nearest vectors to return :param within_ids: list of IDs to search within
find_nearest_from_id
python
superduper-io/superduper
plugins/mongodb/superduper_mongodb/vector_search.py
https://github.com/superduper-io/superduper/blob/master/plugins/mongodb/superduper_mongodb/vector_search.py
Apache-2.0
def find_nearest_from_array(self, h, n=100, within_ids=None): """Find the nearest vectors to the given vector. :param h: vector :param n: number of nearest vectors to return :param within_ids: list of IDs to search within """ self._check_if_exists(create=True) se...
Find the nearest vectors to the given vector. :param h: vector :param n: number of nearest vectors to return :param within_ids: list of IDs to search within
find_nearest_from_array
python
superduper-io/superduper
plugins/mongodb/superduper_mongodb/vector_search.py
https://github.com/superduper-io/superduper/blob/master/plugins/mongodb/superduper_mongodb/vector_search.py
Apache-2.0
def _create_index(self): """Create a vector index in the data backend if an Atlas deployment.""" if self.collection not in self.database.list_collection_names(): logging.warn( f"Collection {self.collection} does not exist. " "Cannot create index." ) re...
Create a vector index in the data backend if an Atlas deployment.
_create_index
python
superduper-io/superduper
plugins/mongodb/superduper_mongodb/vector_search.py
https://github.com/superduper-io/superduper/blob/master/plugins/mongodb/superduper_mongodb/vector_search.py
Apache-2.0
def before_record_response(response): """ VCR filter function to only record the PNG signature in the response. This is necessary because the response is a PNG which can be quite large. """ if 'body' not in response: return response if PNG_BYTE_SIGNATURE in response['body']['string']: ...
VCR filter function to only record the PNG signature in the response. This is necessary because the response is a PNG which can be quite large.
before_record_response
python
superduper-io/superduper
plugins/openai/plugin_test/test_model_openai.py
https://github.com/superduper-io/superduper/blob/master/plugins/openai/plugin_test/test_model_openai.py
Apache-2.0
def predict_batches(self, dataset: t.List) -> t.List: """Predict on a dataset. :param dataset: The dataset to predict on. """ out = [] for i in tqdm.tqdm(range(0, len(dataset), self.batch_size)): batch = [ dataset[i] for i in range(i, min(len(dataset)...
Predict on a dataset. :param dataset: The dataset to predict on.
predict_batches
python
superduper-io/superduper
plugins/openai/superduper_openai/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/openai/superduper_openai/model.py
Apache-2.0
def predict(self, X: str): """Generates embeddings from text. :param X: The text to generate embeddings for. """ e = self.sync_client.embeddings.create( input=X, model=self.model, **self.predict_kwargs ) out = numpy.array(e.data[0].embedding).astype('float32...
Generates embeddings from text. :param X: The text to generate embeddings for.
predict
python
superduper-io/superduper
plugins/openai/superduper_openai/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/openai/superduper_openai/model.py
Apache-2.0
def predict(self, X: str, context: t.Optional[str] = None, **kwargs): """Generates text completions from prompts. :param X: The prompt. :param context: The context to use for the prompt. :param kwargs: Additional keyword arguments. """ if context is not None: ...
Generates text completions from prompts. :param X: The prompt. :param context: The context to use for the prompt. :param kwargs: Additional keyword arguments.
predict
python
superduper-io/superduper
plugins/openai/superduper_openai/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/openai/superduper_openai/model.py
Apache-2.0
def predict_batches(self, dataset: t.List) -> t.List: """Generates text completions from prompts. :param dataset: The dataset of prompts. """ out = [] for i in range(len(dataset)): out.append(method_wrapper(self.predict, dataset[i], self.signature)) return ou...
Generates text completions from prompts. :param dataset: The dataset of prompts.
predict_batches
python
superduper-io/superduper
plugins/openai/superduper_openai/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/openai/superduper_openai/model.py
Apache-2.0
def _decode_data(self, item): """Decode the data. :param item: The data to decode. """ try: return PIL.Image.open(io.BytesIO(item)) except Exception as e: if self.handle_exceptions: return BLANK_IMAGE else: rais...
Decode the data. :param item: The data to decode.
_decode_data
python
superduper-io/superduper
plugins/pillow/superduper_pillow/encoder.py
https://github.com/superduper-io/superduper/blob/master/plugins/pillow/superduper_pillow/encoder.py
Apache-2.0
def add(self, items: t.Sequence[VectorItem], cache: bool = False) -> None: """Add vectors to the index. :param items: List of vectors to add :param cache: Cache vectors (not used in Qdrant implementation). """ points = [] for item in items: point = models.Poi...
Add vectors to the index. :param items: List of vectors to add :param cache: Cache vectors (not used in Qdrant implementation).
add
python
superduper-io/superduper
plugins/qdrant/superduper_qdrant/qdrant.py
https://github.com/superduper-io/superduper/blob/master/plugins/qdrant/superduper_qdrant/qdrant.py
Apache-2.0
def drop(self, force: bool = False): """Drop the in-memory store. :param force: Force drop the in-memory store. """ if not force and not click.confirm( 'Are you sure you want to drop the in-memory store?' ): logging.warning('Aborting drop of in-memory sto...
Drop the in-memory store. :param force: Force drop the in-memory store.
drop
python
superduper-io/superduper
plugins/redis/superduper_redis/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/redis/superduper_redis/data_backend.py
Apache-2.0
def keys(self, *pattern: str): """Get the keys in the in-memory store. :param pattern: Pattern to match the keys. """ matches = self.conn.keys(':'.join(pattern)) return [tuple(x.split(':')) for x in matches]
Get the keys in the in-memory store. :param pattern: Pattern to match the keys.
keys
python
superduper-io/superduper
plugins/redis/superduper_redis/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/redis/superduper_redis/data_backend.py
Apache-2.0
def reconnect(self): """Reconnect to the in-memory store.""" self.conn = redis.from_url( self.uri, decode_responses=True, )
Reconnect to the in-memory store.
reconnect
python
superduper-io/superduper
plugins/redis/superduper_redis/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/redis/superduper_redis/data_backend.py
Apache-2.0
def to(self, device): """Move the model to a device. :param device: The device to move to, e.g. 'cpu' or 'cuda'. """ self.object = self.object.to(device) self.object._target_device = device
Move the model to a device. :param device: The device to move to, e.g. 'cpu' or 'cuda'.
to
python
superduper-io/superduper
plugins/sentence_transformers/superduper_sentence_transformers/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/sentence_transformers/superduper_sentence_transformers/model.py
Apache-2.0
def predict(self, text): """Predict on a single input. :param text: The input to predict on. """ if self.preprocess is not None: text = self.preprocess(text) assert self.object is not None result = self.object.encode(text, **self.predict_kwargs) if s...
Predict on a single input. :param text: The input to predict on.
predict
python
superduper-io/superduper
plugins/sentence_transformers/superduper_sentence_transformers/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/sentence_transformers/superduper_sentence_transformers/model.py
Apache-2.0
def fit( self, model: 'Estimator', db: Datalayer, train_dataset: QueryDataset, valid_dataset: QueryDataset, ): """Fit the model. :param model: Model :param db: Datalayer :param train_dataset: Training dataset :param valid_dataset: Vali...
Fit the model. :param model: Model :param db: Datalayer :param train_dataset: Training dataset :param valid_dataset: Validation dataset
fit
python
superduper-io/superduper
plugins/sklearn/superduper_sklearn/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/sklearn/superduper_sklearn/model.py
Apache-2.0