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 handle_references(item, builds):
"""Handle references in a schema.
:param item: Item to handle references in.
:param builds: Build cache for decoding references.
"""
if '?(' not in str(item):
return item
if isinstance(item, str):
instances = ... | Handle references in a schema.
:param item: Item to handle references in.
:param builds: Build cache for decoding references.
| handle_references | python | superduper-io/superduper | superduper/base/schema.py | https://github.com/superduper-io/superduper/blob/master/superduper/base/schema.py | Apache-2.0 |
def decode_data(
self, data: dict[str, t.Any], builds: t.Dict, db
) -> dict[str, t.Any]:
"""Decode data using the schema's encoders.
:param data: Data to decode.
:param builds: build cache for decoding references.
:param db: Datalayer instance
"""
if self.tri... | Decode data using the schema's encoders.
:param data: Data to decode.
:param builds: build cache for decoding references.
:param db: Datalayer instance
| decode_data | python | superduper-io/superduper | superduper/base/schema.py | https://github.com/superduper-io/superduper/blob/master/superduper/base/schema.py | Apache-2.0 |
def encode_data(self, out, context: t.Optional[EncodeContext] = None, **kwargs):
"""Encode data using the schema's encoders.
:param out: Data to encode.
:param context: Encoding context.
:param kwargs: Additional encoding arguments.
"""
result = {k: v for k, v in out.ite... | Encode data using the schema's encoders.
:param out: Data to encode.
:param context: Encoding context.
:param kwargs: Additional encoding arguments.
| encode_data | python | superduper-io/superduper | superduper/base/schema.py | https://github.com/superduper-io/superduper/blob/master/superduper/base/schema.py | Apache-2.0 |
def get_schema(db, schema: t.Union[Schema, str]) -> t.Optional[Schema]:
"""Handle schema caching and loading.
:param db: Datalayer instance.
:param schema: Schema to get. If a string, it will be loaded from the database.
"""
if schema is None:
return None
if isinstance(schema, Schema):
... | Handle schema caching and loading.
:param db: Datalayer instance.
:param schema: Schema to get. If a string, it will be loaded from the database.
| get_schema | python | superduper-io/superduper | superduper/base/schema.py | https://github.com/superduper-io/superduper/blob/master/superduper/base/schema.py | Apache-2.0 |
def create_pydantic(
name: str, schema: Schema, components: t.Dict[str, t.Type] | None = None
):
"""Create pydantic model from schema.
:param name: Name of the model.
:param schema: Schema to create the model from.
:param components: Additional components to add to the model.
"""
lookup = {... | Create pydantic model from schema.
:param name: Name of the model.
:param schema: Schema to create the model from.
:param components: Additional components to add to the model.
| create_pydantic | python | superduper-io/superduper | superduper/base/schema.py | https://github.com/superduper-io/superduper/blob/master/superduper/base/schema.py | Apache-2.0 |
def init_status():
"""Initialize the status of the component."""
return STATUS_UNINITIALIZED, {
'reason': 'waiting for initialization',
'message': None,
'last_change_time': str(datetime.now()),
'failed_children': {},
} | Initialize the status of the component. | init_status | python | superduper-io/superduper | superduper/base/status.py | https://github.com/superduper-io/superduper/blob/master/superduper/base/status.py | Apache-2.0 |
def running_status():
"""The status of the component as ready."""
return STATUS_RUNNING, {
'reason': 'the component is ready to use',
'message': None,
'last_change_time': str(datetime.now()),
'failed_children': {},
} | The status of the component as ready. | running_status | python | superduper-io/superduper | superduper/base/status.py | https://github.com/superduper-io/superduper/blob/master/superduper/base/status.py | Apache-2.0 |
def superduper(item: str | None = None, **kwargs) -> t.Any:
"""Build a superduper connection.
:param item: URI of connection.
:param kwargs: Additional parameters to building `Datalayer`
"""
from superduper.base.build import build_datalayer
if item is None:
return build_datalayer(**kwa... | Build a superduper connection.
:param item: URI of connection.
:param kwargs: Additional parameters to building `Datalayer`
| superduper | python | superduper-io/superduper | superduper/base/superduper.py | https://github.com/superduper-io/superduper/blob/master/superduper/base/superduper.py | Apache-2.0 |
def build_context(vars_dict: dict[str, t.Any] | None):
"""Context manager to set build variables for components.
:param vars_dict: Dictionary of variables to set for the build context.
"""
token = build_vars_var.set(vars_dict or {})
try:
yield
finally:
build_vars_var.reset(token... | Context manager to set build variables for components.
:param vars_dict: Dictionary of variables to set for the build context.
| build_context | python | superduper-io/superduper | superduper/components/application.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/application.py | Apache-2.0 |
def postinit(self):
"""Post-initialization method to set up the application."""
with build_context(self.variables):
for component in self.components:
# Might be just a ComponentRef
if isinstance(component, Component):
component.postinit()
... | Post-initialization method to set up the application. | postinit | python | superduper-io/superduper | superduper/components/application.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/application.py | Apache-2.0 |
def build_from_db(cls, identifier, db: "Datalayer"):
"""Build application from `superduper`.
:param identifier: Identifier of the application.
:param db: Datalayer instance
"""
components = []
for component_info in db.show():
logging.info(f"Component info: {c... | Build application from `superduper`.
:param identifier: Identifier of the application.
:param db: Datalayer instance
| build_from_db | python | superduper-io/superduper | superduper/components/application.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/application.py | Apache-2.0 |
def handle_update_or_same(self, other):
"""Handle the case in which the component is update without breaking changes.
:param other: The other component to handle.
"""
super().handle_update_or_same(other)
other.cdc_table = self.cdc_table | Handle the case in which the component is update without breaking changes.
:param other: The other component to handle.
| handle_update_or_same | python | superduper-io/superduper | superduper/components/cdc.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/cdc.py | Apache-2.0 |
def build_streaming_graph(table, db: "Datalayer") -> nx.DiGraph:
"""Build a streaming graph from a table.
The graph has as each node a component which
ingests from the table, or ingests from
a component which ingests from the table (etc.).
This function constructs a directed graph representing the... | Build a streaming graph from a table.
The graph has as each node a component which
ingests from the table, or ingests from
a component which ingests from the table (etc.).
This function constructs a directed graph representing the data flow
between components connected to the specified table.
... | build_streaming_graph | python | superduper-io/superduper | superduper/components/cdc.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/cdc.py | Apache-2.0 |
def ensure_setup(func):
"""Decorator to ensure that the model is initialized before calling the function.
:param func: Decorator function.
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
if not getattr(self, "_is_setup", False):
model_message = f"{self.__class__.__name__} ... | Decorator to ensure that the model is initialized before calling the function.
:param func: Decorator function.
| ensure_setup | python | superduper-io/superduper | superduper/components/component.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/component.py | Apache-2.0 |
def propagate_failure(f):
"""Propagate failure decorator.
:param f: Function to decorate.
"""
@wraps(f)
def decorated(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except Exception as e:
self.propagate_failure(e)
raise e
retur... | Propagate failure decorator.
:param f: Function to decorate.
| propagate_failure | python | superduper-io/superduper | superduper/components/component.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/component.py | Apache-2.0 |
def current_build_vars(default: t.Any | None = None) -> dict[str, t.Any] | None:
"""Get the current build variables.
:param default: Default value to return if no variables are set.
"""
try:
return build_vars_var.get()
except LookupError:
return default | Get the current build variables.
:param default: Default value to return if no variables are set.
| current_build_vars | python | superduper-io/superduper | superduper/components/component.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/component.py | Apache-2.0 |
def save(self):
"""Save the component to the datalayer."""
assert self.db is not None, "Datalayer is not set"
self.db.apply(self, jobs=False, force=True) | Save the component to the datalayer. | save | python | superduper-io/superduper | superduper/components/component.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/component.py | Apache-2.0 |
def get_merkle_tree(self, breaks: bool):
"""Get the merkle tree of the component.
:param breaks: If set `true` only regard the parameters which break a version.
"""
r = self._dict(metadata=False)
s = self.class_schema
keys = sorted(
[
k
... | Get the merkle tree of the component.
:param breaks: If set `true` only regard the parameters which break a version.
| get_merkle_tree | python | superduper-io/superduper | superduper/components/component.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/component.py | Apache-2.0 |
def diff(self, other: 'Component'):
"""Get the difference between two components.
:param other: The other component to compare.
"""
if not isreallyinstance(other, type(self)):
raise ValueError('Cannot compare different types of components')
if other.hash == self.has... | Get the difference between two components.
:param other: The other component to compare.
| diff | python | superduper-io/superduper | superduper/components/component.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/component.py | Apache-2.0 |
def sort_components(components):
"""Sort components based on topological order.
:param components: List of components.
"""
logging.info('Resorting components based on topological order.')
G = networkx.DiGraph()
lookup = {c.huuid: c for c in components}
for k in l... | Sort components based on topological order.
:param components: List of components.
| sort_components | python | superduper-io/superduper | superduper/components/component.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/component.py | Apache-2.0 |
def handle_update_or_same(self, other: 'Component'):
"""Handle when a component is changed without breaking changes.
:param other: The other component to handle.
"""
other.uuid = self.uuid
other.version = self.version | Handle when a component is changed without breaking changes.
:param other: The other component to handle.
| handle_update_or_same | python | superduper-io/superduper | superduper/components/component.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/component.py | Apache-2.0 |
def get_children_refs(self, deep: bool = False, only_initializing: bool = False):
"""Get all the children of the component.
:param deep: If set `true` get all the children of the component.
:param only_initializing: If set `true` get only the initializing children.
"""
r = self.... | Get all the children of the component.
:param deep: If set `true` get all the children of the component.
:param only_initializing: If set `true` get only the initializing children.
| get_children_refs | python | superduper-io/superduper | superduper/components/component.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/component.py | Apache-2.0 |
def get_children(self, deep: bool = False) -> t.List["Component"]:
"""Get all the children of the component.
:param deep: If set `True` get all recursively.
"""
from superduper.base.datatype import ComponentRef, Saveable
r = self.dict().encode(leaves_to_keep=(Component, Saveabl... | Get all the children of the component.
:param deep: If set `True` get all recursively.
| get_children | python | superduper-io/superduper | superduper/components/component.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/component.py | Apache-2.0 |
def get_triggers(self, event_type, requires: t.Sequence[str] | None = None):
"""
Get all the triggers for the component.
:param event_type: event_type
:param requires: the methods which should run first
"""
# Get all of the methods in the class which have the `@trigger` ... |
Get all the triggers for the component.
:param event_type: event_type
:param requires: the methods which should run first
| get_triggers | python | superduper-io/superduper | superduper/components/component.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/component.py | Apache-2.0 |
def propagate_failure(self, exc: Exception):
"""Propagate the status of the component to its parents.
:param exc: The exception to propagate.
"""
self.db.metadata.set_component_failed(
component=self.component,
uuid=self.uuid,
) | Propagate the status of the component to its parents.
:param exc: The exception to propagate.
| propagate_failure | python | superduper-io/superduper | superduper/components/component.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/component.py | Apache-2.0 |
def set_status(self):
"""Set the status of the component.
:param status: The status to set the component to.
"""
return self.db.metadata.set_component_status(
self.__class__.__name__,
self.uuid,
status=STATUS_RUNNING,
reason='The component... | Set the status of the component.
:param status: The status to set the component to.
| set_status | python | superduper-io/superduper | superduper/components/component.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/component.py | Apache-2.0 |
def create_jobs(
self,
context: str,
event_type: str,
ids: t.Sequence[str] | None = None,
jobs: t.Sequence['Job'] = (),
requires: t.Sequence[str] | None = None,
) -> t.List['Job']:
"""Deploy apply jobs for the component.
:param context: The context of... | Deploy apply jobs for the component.
:param context: The context of the component.
:param event_type: The event type.
:param ids: The ids of the component.
:param jobs: The jobs of the component.
:param requires: The requirements of the component.
| create_jobs | python | superduper-io/superduper | superduper/components/component.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/component.py | Apache-2.0 |
def leaves(self):
"""Get all the leaves in the component."""
r = self.dict()
leaf_keys = [k for k in r.keys(True) if isinstance(r[k], Base)]
return {k: r[k] for k in leaf_keys} | Get all the leaves in the component. | leaves | python | superduper-io/superduper | superduper/components/component.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/component.py | Apache-2.0 |
def setup(self):
"""Method to help initiate component field dependencies."""
def mro(item):
objects = item.__class__.__mro__
return [f'{o.__module__}.{o.__name__}' for o in objects]
def _setup(item):
if 'superduper.components.component.Component' in mro(ite... | Method to help initiate component field dependencies. | setup | python | superduper-io/superduper | superduper/components/component.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/component.py | Apache-2.0 |
def reload(self):
"""Reload the component from the datalayer."""
assert self.db is not None
latest_uuid = self.db.metadata.get_latest_uuid(self.component, self.identifier)
if latest_uuid != self.uuid:
return self.db.load(self.component, self.identifier)
return self | Reload the component from the datalayer. | reload | python | superduper-io/superduper | superduper/components/component.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/component.py | Apache-2.0 |
def export(
self,
path: t.Optional[str] = None,
defaults: bool = True,
metadata: bool = False,
format: str = "json",
):
"""
Save `self` to a directory using super-duper protocol.
:param path: Path to the directory to save the component.
:param... |
Save `self` to a directory using super-duper protocol.
:param path: Path to the directory to save the component.
:param defaults: Whether to save default values.
:param metadata: Whether to save metadata.
:param format: Format to save the component. Accepts `json` and `yaml`.
... | export | python | superduper-io/superduper | superduper/components/component.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/component.py | Apache-2.0 |
def dict(self, metadata: bool = True):
"""Get the dictionary representation of the component.
:param metadata: If set `True` include metadata in the dictionary.
"""
r = self._dict(metadata=metadata)
r['uuid'] = self.uuid
r['_path'] = self.__module__ + '.' + self.__class_... | Get the dictionary representation of the component.
:param metadata: If set `True` include metadata in the dictionary.
| dict | python | superduper-io/superduper | superduper/components/component.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/component.py | Apache-2.0 |
def run_and_propagate_failure(self):
"""Run the job and propagate failure to the crontab service."""
try:
self.run()
except Exception as e:
self.propagate_failure(e)
raise e | Run the job and propagate failure to the crontab service. | run_and_propagate_failure | python | superduper-io/superduper | superduper/components/cron_job.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/cron_job.py | Apache-2.0 |
def method_wrapper(method, item, signature: str):
"""Wrap the item with the model.
:param method: Method to execute.
:param item: Item to wrap.
:param signature: Signature of the method.
"""
if signature == 'singleton':
return method(item)
if signature == '*args':
assert isi... | Wrap the item with the model.
:param method: Method to execute.
:param item: Item to wrap.
:param signature: Signature of the method.
| method_wrapper | python | superduper-io/superduper | superduper/components/model.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/model.py | Apache-2.0 |
def fit(
self,
model: Model,
db: Datalayer,
train_dataset: t.List,
valid_dataset: t.List,
):
"""Fit on the model on training dataset with `valid_dataset` for validation.
:param model: Model to be fit
:param db: The datalayer
:param train_datas... | Fit on the model on training dataset with `valid_dataset` for validation.
:param model: Model to be fit
:param db: The datalayer
:param train_dataset: The training ``Dataset`` instances to use
:param valid_dataset: The validation ``Dataset`` instances to use
| fit | python | superduper-io/superduper | superduper/components/model.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/model.py | Apache-2.0 |
def init_decorator(func):
"""Decorator to set _is_setup to `True` after init method is called.
:param func: init function.
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
result = func(self, *args, **kwargs)
self._is_setup = True
return result
return wrapper | Decorator to set _is_setup to `True` after init method is called.
:param func: init function.
| init_decorator | python | superduper-io/superduper | superduper/components/model.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/model.py | Apache-2.0 |
def serve(f):
"""Decorator to serve the model on the associated cluster.
:param f: Method to serve.
"""
@wraps(f)
def wrapper(self, *args, **kwargs):
if (
self.serve
and self.db is not None
and self.db.cluster is not None
and self.db.cluster.... | Decorator to serve the model on the associated cluster.
:param f: Method to serve.
| serve | python | superduper-io/superduper | superduper/components/model.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/model.py | Apache-2.0 |
def predict_batches(self, dataset: t.List) -> t.List:
"""Execute on a series of data points defined in the dataset.
:param dataset: Series of data points to predict on.
"""
outputs = []
if self.num_workers:
pool = multiprocessing.Pool(processes=self.num_workers)
... | Execute on a series of data points defined in the dataset.
:param dataset: Series of data points to predict on.
| predict_batches | python | superduper-io/superduper | superduper/components/model.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/model.py | Apache-2.0 |
def validate(self, key, dataset: Dataset, metrics: t.Sequence[Metric]):
"""Validate `dataset` on metrics.
:param key: Define input map
:param dataset: Dataset to run validation on.
:param metrics: Metrics for performing validation
"""
if isinstance(key, str):
... | Validate `dataset` on metrics.
:param key: Define input map
:param dataset: Dataset to run validation on.
:param metrics: Metrics for performing validation
| validate | python | superduper-io/superduper | superduper/components/model.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/model.py | Apache-2.0 |
def validate_in_db(self):
"""Validation job in database.
:param db: DataLayer instance.
"""
assert isinstance(self.validation, Validation)
for dataset in self.validation.datasets:
logging.info(f'Validating on {dataset.identifier}...')
results = self.valid... | Validation job in database.
:param db: DataLayer instance.
| validate_in_db | python | superduper-io/superduper | superduper/components/model.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/model.py | Apache-2.0 |
def fit(
self,
train_dataset: t.List[t.Any],
valid_dataset: t.List[t.Any],
db: Datalayer,
):
"""Fit the model on the training dataset with `valid_dataset` for validation.
:param train_dataset: The training ``Dataset`` instances to use.
:param valid_dataset: T... | Fit the model on the training dataset with `valid_dataset` for validation.
:param train_dataset: The training ``Dataset`` instances to use.
:param valid_dataset: The validation ``Dataset`` instances to use.
:param db: The datalayer.
| fit | python | superduper-io/superduper | superduper/components/model.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/model.py | Apache-2.0 |
def fit_in_db(self):
"""Fit the model on the given data.
:param db: The datalayer
"""
assert isinstance(self.trainer, Trainer)
train_dataset, valid_dataset = self._create_datasets(
select=self.trainer.select,
X=self.trainer.key,
db=self.db,
... | Fit the model on the given data.
:param db: The datalayer
| fit_in_db | python | superduper-io/superduper | superduper/components/model.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/model.py | Apache-2.0 |
def append_metrics(self, d: t.Dict[str, float]) -> None:
"""Append metrics to the model.
:param d: Dictionary of metrics to append.
"""
assert self.trainer is not None
if self.trainer.metric_values is not None:
for k, v in d.items():
self.trainer.metr... | Append metrics to the model.
:param d: Dictionary of metrics to append.
| append_metrics | python | superduper-io/superduper | superduper/components/model.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/model.py | Apache-2.0 |
def predict(self, *args, **kwargs):
"""Predict on a single data point.
Method to execute ``Object`` on args and kwargs.
This method is also used for debugging the Model.
:param args: Positional arguments of model
:param kwargs: Keyword arguments of model
"""
obj... | Predict on a single data point.
Method to execute ``Object`` on args and kwargs.
This method is also used for debugging the Model.
:param args: Positional arguments of model
:param kwargs: Keyword arguments of model
| predict | python | superduper-io/superduper | superduper/components/model.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/model.py | Apache-2.0 |
def predict_batches(self, dataset: t.List, *args, **kwargs) -> t.List:
"""Use multi-threading to predict on a series of data points.
:param dataset: Series of data points.
:param args: Positional arguments to predict on.
:param kwargs: Keyword arguments to predict on.
"""
... | Use multi-threading to predict on a series of data points.
:param dataset: Series of data points.
:param args: Positional arguments to predict on.
:param kwargs: Keyword arguments to predict on.
| predict_batches | python | superduper-io/superduper | superduper/components/model.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/model.py | Apache-2.0 |
def postinit(self):
"""Initialize the model data (e.g. weights etc.)."""
self.params['model'] = self.model
env_variables = re.findall(r'{([A-Z0-9\_]+)}', self.url)
runtime_variables = re.findall(r'{([a-z0-9\_]+)}', self.url)
runtime_variables = [x for x in runtime_variables if x ... | Initialize the model data (e.g. weights etc.). | postinit | python | superduper-io/superduper | superduper/components/model.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/model.py | Apache-2.0 |
def predict(self, *args, **kwargs):
"""Predict on a single data point.
Method to requests to `url` on args and kwargs.
This method is also used for debugging the model.
:param args: Positional arguments to predict on.
:param kwargs: Keyword arguments to predict on.
"""
... | Predict on a single data point.
Method to requests to `url` on args and kwargs.
This method is also used for debugging the model.
:param args: Positional arguments to predict on.
:param kwargs: Keyword arguments to predict on.
| predict | python | superduper-io/superduper | superduper/components/model.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/model.py | Apache-2.0 |
def predict(self, *args, **kwargs):
"""Predict on a single data point.
Method to perform a single prediction on args and kwargs.
This method is also used for debugging the model.
:param args: Positional arguments to predict on.
:param kwargs: Keyword arguments to predict on.
... | Predict on a single data point.
Method to perform a single prediction on args and kwargs.
This method is also used for debugging the model.
:param args: Positional arguments to predict on.
:param kwargs: Keyword arguments to predict on.
| predict | python | superduper-io/superduper | superduper/components/model.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/model.py | Apache-2.0 |
def predict(self, *args, **kwargs):
"""Predict on a single data point.
Method to do single prediction on args and kwargs.
This method is also used for debugging the model.
:param args: Positional arguments to predict on.
:param kwargs: Keyword arguments to predict on.
"... | Predict on a single data point.
Method to do single prediction on args and kwargs.
This method is also used for debugging the model.
:param args: Positional arguments to predict on.
:param kwargs: Keyword arguments to predict on.
| predict | python | superduper-io/superduper | superduper/components/model.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/model.py | Apache-2.0 |
def predict_batches(self, dataset: t.List) -> t.List:
"""Execute on series of data point defined in dataset.
:param dataset: Series of data point to predict on.
"""
for i, p in enumerate(self.models):
assert isreallyinstance(p, Model), f'Expected `Model`, got {type(p)}'
... | Execute on series of data point defined in dataset.
:param dataset: Series of data point to predict on.
| predict_batches | python | superduper-io/superduper | superduper/components/model.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/model.py | Apache-2.0 |
def page(self):
"""Get the streamlit page for the multi-page app."""
import streamlit as st
def demo_func():
return self.demo_func(db=self.db, **self.demo_kwargs)
demo_func.__name__ = self.identifier
return st.Page(demo_func, title=self.identifier, default=self.def... | Get the streamlit page for the multi-page app. | page | python | superduper-io/superduper | superduper/components/streamlit.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/streamlit.py | Apache-2.0 |
def read(path):
"""Read the template from the given path.
:param path: Path to the template.
If the template has yet to be built, it will be built using
the `build.ipynb` notebook.
"""
path = pathlib.Path(path)
if 'SUPERDUPER_CONFIG' in os.environ:
... | Read the template from the given path.
:param path: Path to the template.
If the template has yet to be built, it will be built using
the `build.ipynb` notebook.
| read | python | superduper-io/superduper | superduper/components/template.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/template.py | Apache-2.0 |
def download(name: str = '*', path='./templates'):
"""Download the templates to the given path.
:param name: Name of the template to download.
:param path: Path to download the templates.
Here are the supported templates:
- llm_finetuning
- multimodal_image_search
... | Download the templates to the given path.
:param name: Name of the template to download.
:param path: Path to download the templates.
Here are the supported templates:
- llm_finetuning
- multimodal_image_search
- multimodal_video_search
- pdf_rag
- rag
... | download | python | superduper-io/superduper | superduper/components/template.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/template.py | Apache-2.0 |
def form_template(self):
"""Form to be diplayed to user."""
info = self.info.copy() if self.info else {}
if self.types:
info['types'] = self.types
if self.schema:
info['schema'] = self.schema
return {
'template': self.template,
'bui... | Form to be diplayed to user. | form_template | python | superduper-io/superduper | superduper/components/template.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/template.py | Apache-2.0 |
def __call__(self, identifier=None, **kwargs):
"""Method to create component from the given template and `kwargs`.
:param kwargs: Variables to be set in the template.
"""
kwargs.update({k: v for k, v in self.default_values.items() if k not in kwargs})
wants = set(self.template_... | Method to create component from the given template and `kwargs`.
:param kwargs: Variables to be set in the template.
| __call__ | python | superduper-io/superduper | superduper/components/template.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/template.py | Apache-2.0 |
def ibatch(iterable: t.Iterable[T], batch_size: int) -> t.Iterator[t.List[T]]:
"""Batch an iterable into chunks of size `batch_size`.
:param iterable: the iterable to batch
:param batch_size: the number of groups to write
"""
iterator = iter(iterable)
while True:
batch = list(itertools.... | Batch an iterable into chunks of size `batch_size`.
:param iterable: the iterable to batch
:param batch_size: the number of groups to write
| ibatch | python | superduper-io/superduper | superduper/components/vector_index.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/vector_index.py | Apache-2.0 |
def get_vectors(self, ids: t.Sequence[str] | None = None):
"""Get vectors from the vector index.
:param ids: A list of ids to match
"""
self.indexing_listener.setup()
if not hasattr(self.indexing_listener.model, 'datatype'):
self.indexing_listener.model = self.db.loa... | Get vectors from the vector index.
:param ids: A list of ids to match
| get_vectors | python | superduper-io/superduper | superduper/components/vector_index.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/vector_index.py | Apache-2.0 |
def copy_vectors(self, ids: t.Sequence[str] | None = None):
"""Copy vectors to the vector index."""
vectors = self.get_vectors(ids=ids)
# TODO combine logic from backfill
if vectors:
self.db.cluster.vector_search.add(
uuid=self.uuid, vectors=[VectorItem(**vect... | Copy vectors to the vector index. | copy_vectors | python | superduper-io/superduper | superduper/components/vector_index.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/vector_index.py | Apache-2.0 |
def get_vector(
self,
like: Document,
models: t.Dict,
keys: KeyType,
outputs: t.Optional[t.Dict] = None,
):
"""Peform vector search.
Perform vector search with query `like` from outputs in db
on `self.identifier` vector index.
:param like: Th... | Peform vector search.
Perform vector search with query `like` from outputs in db
on `self.identifier` vector index.
:param like: The document to compare against
:param models: List of models to retrieve outputs
:param keys: Keys available to retrieve outputs of model
:p... | get_vector | python | superduper-io/superduper | superduper/components/vector_index.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/vector_index.py | Apache-2.0 |
def get_nearest(
self,
like: Document,
outputs: t.Optional[t.Dict] = None,
ids: t.Optional[t.Sequence[str]] = None,
n: int = 100,
) -> t.Tuple[t.List[str], t.List[float]]:
"""Get nearest results in this vector index.
Given a document, find the nearest results... | Get nearest results in this vector index.
Given a document, find the nearest results in this vector index, returned as
two parallel lists of result IDs and scores.
:param like: The document to compare against
:param outputs: An optional dictionary
:param ids: A list of ids to m... | get_nearest | python | superduper-io/superduper | superduper/components/vector_index.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/vector_index.py | Apache-2.0 |
def models_keys(self):
"""Return a list of model and keys for each listener."""
assert not isinstance(self.indexing_listener, str)
assert not isinstance(self.compatible_listener, str)
if self.compatible_listener:
listeners = [self.indexing_listener, self.compatible_listener]... | Return a list of model and keys for each listener. | models_keys | python | superduper-io/superduper | superduper/components/vector_index.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/vector_index.py | Apache-2.0 |
def dimensions(self) -> int:
"""Get dimension for vector database.
This dimension will be used to prepare vectors in the vector database.
"""
msg = f'Couldn\'t find an output table for {self.indexing_listener.huuid}'
assert isinstance(self.indexing_listener.output_table, Table),... | Get dimension for vector database.
This dimension will be used to prepare vectors in the vector database.
| dimensions | python | superduper-io/superduper | superduper/components/vector_index.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/vector_index.py | Apache-2.0 |
def predict_batches(self, dataset: t.List, **kwargs) -> t.Sequence:
"""Generate text from a dataset.
:param dataset: The dataset to generate text from.
:param kwargs: The keyword arguments to pass to the prompt function and
the llm model.
"""
xs = [self.... | Generate text from a dataset.
:param dataset: The dataset to generate text from.
:param kwargs: The keyword arguments to pass to the prompt function and
the llm model.
| predict_batches | python | superduper-io/superduper | superduper/components/llm/model.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/llm/model.py | Apache-2.0 |
def get_kwargs(self, func: t.Callable, *kwargs_list):
"""Get kwargs and object attributes that are in the function signature.
:param func: function to get kwargs for
:param *kwargs_list: kwargs to filter
"""
total_kwargs = reduce(lambda x, y: {**y, **x}, [self.dict(), *kwargs_li... | Get kwargs and object attributes that are in the function signature.
:param func: function to get kwargs for
:param *kwargs_list: kwargs to filter
| get_kwargs | python | superduper-io/superduper | superduper/components/llm/model.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/llm/model.py | Apache-2.0 |
def _generate_wrapper(self, prompt: str, **kwargs: t.Any) -> str:
"""Wrapper for the _generate method to handle exceptions."""
try:
return self._generate(prompt, **kwargs)
except Exception as e:
logging.error(f"Error generating response for prompt '{prompt}': {e}")
... | Wrapper for the _generate method to handle exceptions. | _generate_wrapper | python | superduper-io/superduper | superduper/components/llm/model.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/llm/model.py | Apache-2.0 |
def _batch_generate(self, prompts: t.List[str], **kwargs: t.Any) -> t.List[str]:
"""
Base method to batch generate text from a list of prompts using multi-threading.
Handles exceptions in _generate method.
:param prompts: The list of prompts to generate text from.
"""
w... |
Base method to batch generate text from a list of prompts using multi-threading.
Handles exceptions in _generate method.
:param prompts: The list of prompts to generate text from.
| _batch_generate | python | superduper-io/superduper | superduper/components/llm/model.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/llm/model.py | Apache-2.0 |
def __call__(self, x: t.Any, **kwargs):
"""Format the prompt.
:param x: The input to format the prompt.
:param kwargs: The keyword arguments to pass to the prompt function.
"""
if self.prompt_func is not None:
sig = inspect.signature(self.prompt_func)
new... | Format the prompt.
:param x: The input to format the prompt.
:param kwargs: The keyword arguments to pass to the prompt function.
| __call__ | python | superduper-io/superduper | superduper/components/llm/prompter.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/llm/prompter.py | Apache-2.0 |
def predict(self, prompt):
"""Create a prompt based on the facts and the question.
:param prompt: The prompt to answer the question.
"""
out = super().predict(prompt=prompt)
prompt = (
self.prompt_explanation
+ self.join
+ self.join.join(out)
... | Create a prompt based on the facts and the question.
:param prompt: The prompt to answer the question.
| predict | python | superduper-io/superduper | superduper/components/llm/prompter.py | https://github.com/superduper-io/superduper/blob/master/superduper/components/llm/prompter.py | Apache-2.0 |
def extract_parameters(doc):
"""
Extracts and organizes parameter descriptions from a Sphinx-styled docstring.
:param doc: Sphinx-styled docstring.
Docstring may have multiple lines
"""
lines = [x.strip() for x in doc.split('\n')]
was_doc = False
import re
params = defa... |
Extracts and organizes parameter descriptions from a Sphinx-styled docstring.
:param doc: Sphinx-styled docstring.
Docstring may have multiple lines
| extract_parameters | python | superduper-io/superduper | superduper/misc/annotations.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/annotations.py | Apache-2.0 |
def replace_parameters(doc, placeholder: str = '!!!'):
"""
Replace parameters in a doc-string with a placeholder.
:param doc: Sphinx-styled docstring.
:param placeholder: Placeholder to replace parameters with.
"""
doc = [x.strip() for x in doc.split('\n')]
lines = []
had_parameters = F... |
Replace parameters in a doc-string with a placeholder.
:param doc: Sphinx-styled docstring.
:param placeholder: Placeholder to replace parameters with.
| replace_parameters | python | superduper-io/superduper | superduper/misc/annotations.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/annotations.py | Apache-2.0 |
def anonymize_url(url):
"""Anonymize a URL by replacing the username and password with a mask token.
Change the username and password to *** keeping one character before and after each.
:param url: Database URL
"""
if not url:
return url
pattern = re.compile(r'(?<=://)(.*?)(?=@)')
... | Anonymize a URL by replacing the username and password with a mask token.
Change the username and password to *** keeping one character before and after each.
:param url: Database URL
| anonymize_url | python | superduper-io/superduper | superduper/misc/anonymize.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/anonymize.py | Apache-2.0 |
def load_plugin(name: str):
"""Load a plugin by name.
:param name: The name of the plugin to load.
"""
if name in {'local', 'inmemory', 'simple'}:
return importlib.import_module('superduper.backends.{}'.format(name))
logging.info(f"Loading plugin: {name}")
plugin = importlib.import_modu... | Load a plugin by name.
:param name: The name of the plugin to load.
| load_plugin | python | superduper-io/superduper | superduper/misc/importing.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/importing.py | Apache-2.0 |
def import_object(path):
"""Import item from path.
:param path: Path to import from.
"""
module = '.'.join(path.split('.')[:-1])
cls = path.split('.')[-1]
return getattr(importlib.import_module(module), cls) | Import item from path.
:param path: Path to import from.
| import_object | python | superduper-io/superduper | superduper/misc/importing.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/importing.py | Apache-2.0 |
def isreallyinstance(this, cls):
"""Check if the component is an instance of a class.
:param this: The component to check.
:param cls: The class to check.
"""
# no idea why this is sometimes necessary - may be IPython autoreload related
mro = [f'{o.__module__}.{o.__name__}' for o in this.__clas... | Check if the component is an instance of a class.
:param this: The component to check.
:param cls: The class to check.
| isreallyinstance | python | superduper-io/superduper | superduper/misc/importing.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/importing.py | Apache-2.0 |
def __call__(self, f: t.Callable) -> t.Any:
"""Decorate a function to retry on exceptions.
Uses the exception types and config provided to the constructor.
:param f: The function to decorate.
"""
cfg = self.cfg or s.CFG.retries
retry = tenacity.retry_if_exception_type(se... | Decorate a function to retry on exceptions.
Uses the exception types and config provided to the constructor.
:param f: The function to decorate.
| __call__ | python | superduper-io/superduper | superduper/misc/retry.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/retry.py | Apache-2.0 |
def safe_retry(exception_to_check, retries=1, delay=0.3, verbose=1):
"""
A decorator that retries a function if a specified exception is raised.
:param exception_to_check: The exception or tuple of exceptions to check.
:param retries: The maximum number of retries.
:param delay: Delay between retri... |
A decorator that retries a function if a specified exception is raised.
:param exception_to_check: The exception or tuple of exceptions to check.
:param retries: The maximum number of retries.
:param delay: Delay between retries in seconds.
:param verbose: Verbose for logs.
:return: The result... | safe_retry | python | superduper-io/superduper | superduper/misc/retry.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/retry.py | Apache-2.0 |
def gather_mro_globals(cls):
"""Return a merged dictionary of the module global from the MRO of `cls`.
:param cls: The class to gather the MRO globals from.
"""
merged = {}
for base in cls.__mro__:
# We skip anything that doesn't have a __module__ (e.g., a built-in type)
if hasattr(... | Return a merged dictionary of the module global from the MRO of `cls`.
:param cls: The class to gather the MRO globals from.
| gather_mro_globals | python | superduper-io/superduper | superduper/misc/schema.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/schema.py | Apache-2.0 |
def process(annotation):
"""Process an annotation with a crude mapping to workable superduper types.
Output is expected as a tuple of base type and iterable over that type.
:param annotation: The annotation to process.
>>> import typing as t
>>> from superduper import Model, Component
>>> pro... | Process an annotation with a crude mapping to workable superduper types.
Output is expected as a tuple of base type and iterable over that type.
:param annotation: The annotation to process.
>>> import typing as t
>>> from superduper import Model, Component
>>> process(Model)
(superduper.comp... | process | python | superduper-io/superduper | superduper/misc/schema.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/schema.py | Apache-2.0 |
def get_schema(cls):
"""Get a schema for a superduper class.
:param cls: The class to get a schema for.
"""
annotations = _safe_get_type_hints(cls)
schema = {}
for parameter in annotations:
annotation = annotations[parameter]
if annotation is None:
schema[parameter]... | Get a schema for a superduper class.
:param cls: The class to get a schema for.
| get_schema | python | superduper-io/superduper | superduper/misc/schema.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/schema.py | Apache-2.0 |
def asdict(obj, *, copy_method=copy.copy) -> t.Dict[str, t.Any]:
"""Convert the dataclass instance to a dict.
Custom ``asdict`` function which exports a dataclass object into a dict,
with a option to choose for nested non atomic objects copy strategy.
:param obj: The dataclass instance to
:param c... | Convert the dataclass instance to a dict.
Custom ``asdict`` function which exports a dataclass object into a dict,
with a option to choose for nested non atomic objects copy strategy.
:param obj: The dataclass instance to
:param copy_method: The copy method to use for non atomic objects
| asdict | python | superduper-io/superduper | superduper/misc/serialization.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/serialization.py | Apache-2.0 |
def items(self, deep: bool = False):
"""Returns an iterator of key-value pairs.
:param deep: `bool` whether to iterate over all nested key-value pairs.
"""
for key, value in super().items():
if deep and isinstance(value, DeepKeyedDict):
for sub_key, sub_value... | Returns an iterator of key-value pairs.
:param deep: `bool` whether to iterate over all nested key-value pairs.
| items | python | superduper-io/superduper | superduper/misc/special_dicts.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/special_dicts.py | Apache-2.0 |
def keys(self, deep: bool = False):
"""Returns an iterator of keys.
:param deep: `bool` whether to iterate over all nested keys.
"""
for key in super().keys():
if deep and isinstance(self[key], DeepKeyedDict):
for sub_key in self[key].keys(deep=True):
... | Returns an iterator of keys.
:param deep: `bool` whether to iterate over all nested keys.
| keys | python | superduper-io/superduper | superduper/misc/special_dicts.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/special_dicts.py | Apache-2.0 |
def diff(r1, r2):
"""Get the difference between two dictionaries.
>>> _diff({'a': 1, 'b': 2}, {'a': 2, 'b': 2})
{'a': (1, 2)}
>>> _diff({'a': {'c': 3}, 'b': 2}, {'a': 2, 'b': 2})
{'a': ({'c': 3}, 2)}
:param r1: Dict
:param r2: Dict
"""
d = _diff_impl(r1, r2)
out = {}
for pa... | Get the difference between two dictionaries.
>>> _diff({'a': 1, 'b': 2}, {'a': 2, 'b': 2})
{'a': (1, 2)}
>>> _diff({'a': {'c': 3}, 'b': 2}, {'a': 2, 'b': 2})
{'a': ({'c': 3}, 2)}
:param r1: Dict
:param r2: Dict
| diff | python | superduper-io/superduper | superduper/misc/special_dicts.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/special_dicts.py | Apache-2.0 |
def recursive_update(data, replace_function: t.Callable):
"""Recursively update data with a replace function.
:param data: Dict, List, Tuple, Set
:param replace_function: Callable
"""
if isinstance(data, dict):
for key, value in data.items():
data[key] = recursive_update(value, ... | Recursively update data with a replace function.
:param data: Dict, List, Tuple, Set
:param replace_function: Callable
| recursive_update | python | superduper-io/superduper | superduper/misc/special_dicts.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/special_dicts.py | Apache-2.0 |
def recursive_find(data, check_function: t.Callable):
"""Recursively find items in data that satisfy a check function.
:param data: Dict, List, Tuple, Set
:param check_function: Callable
"""
found_items = []
def recurse(data):
if isinstance(data, dict):
for value in data.va... | Recursively find items in data that satisfy a check function.
:param data: Dict, List, Tuple, Set
:param check_function: Callable
| recursive_find | python | superduper-io/superduper | superduper/misc/special_dicts.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/special_dicts.py | Apache-2.0 |
def dict_to_ascii_table(d):
"""
Return a single string that represents an ASCII table.
Each key/value in the dict is a column.
Columns are centered and padded based on the widest
string needed (key or value).
:param d: Convert a dictionary to a table.
"""
if not d:
return "<emp... |
Return a single string that represents an ASCII table.
Each key/value in the dict is a column.
Columns are centered and padded based on the widest
string needed (key or value).
:param d: Convert a dictionary to a table.
| dict_to_ascii_table | python | superduper-io/superduper | superduper/misc/special_dicts.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/special_dicts.py | Apache-2.0 |
def center_text(text, width):
"""Center text within a given width using spaces."""
text = str(text)
if len(text) >= width:
return text # already as wide or wider, won't cut off
# Calculate left/right spaces for centering
left_spaces = (width - len(text)) // 2
... | Center text within a given width using spaces. | center_text | python | superduper-io/superduper | superduper/misc/special_dicts.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/special_dicts.py | Apache-2.0 |
def dict_to_tree(dictionary, root: str = 'root', tree=None):
"""
Convert a dictionary to a `rich.Tree`.
:param dictionary: Input dict
:param root: Name of root
:param tree: Ignore
"""
if tree is None:
tree = Tree(root)
for key, value in dictionary.items():
if isinstance... |
Convert a dictionary to a `rich.Tree`.
:param dictionary: Input dict
:param root: Name of root
:param tree: Ignore
| dict_to_tree | python | superduper-io/superduper | superduper/misc/tree.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/tree.py | Apache-2.0 |
def str_shape(shape: t.Sequence[int] | int) -> str:
"""Convert a shape to a string.
:param shape: The shape to convert.
"""
if isinstance(shape, int):
return str(shape)
if not shape:
raise ValueError('Shape was empty')
return 'x'.join(str(x) for x in shape) | Convert a shape to a string.
:param shape: The shape to convert.
| str_shape | python | superduper-io/superduper | superduper/misc/utils.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/utils.py | Apache-2.0 |
def merge_dicts(r: t.Dict, s: t.Dict) -> dict:
"""Merge two dictionaries recursively.
:param r: The first dictionary.
:param s: The second dictionary.
>>> r = {'foo': {'bar': 1, 'baz': 2}, 'qux': 3}
>>> s = {'foo': {'bar': 4, 'quux': 5}, 'quux': 6}
>>> merge_dicts(r, s)
{'foo': {'bar': 4, ... | Merge two dictionaries recursively.
:param r: The first dictionary.
:param s: The second dictionary.
>>> r = {'foo': {'bar': 1, 'baz': 2}, 'qux': 3}
>>> s = {'foo': {'bar': 4, 'quux': 5}, 'quux': 6}
>>> merge_dicts(r, s)
{'foo': {'bar': 4, 'baz': 2, 'quux': 5}, 'qux': 3, 'quux': 6}
| merge_dicts | python | superduper-io/superduper | superduper/misc/utils.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/utils.py | Apache-2.0 |
def format_prompt(X: str, prompt: str, context: t.Optional[t.List[str]] = None) -> str:
"""Format a prompt with the given input and context.
:param X: The input to format the prompt with.
:param prompt: The prompt to format.
:param context: The context to format the prompt with.
"""
format_para... | Format a prompt with the given input and context.
:param X: The input to format the prompt with.
:param prompt: The prompt to format.
:param context: The context to format the prompt with.
| format_prompt | python | superduper-io/superduper | superduper/misc/utils.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/utils.py | Apache-2.0 |
def hash_item(item: t.Any) -> str:
"""Hash an item.
:param item: The item to hash.
"""
if item is None:
return hashlib.sha256(('<NoneType>' + str(item)).encode()).hexdigest()
if isinstance(item, bytearray):
return hashlib.sha256(item).hexdigest()
if isinstance(item, str):
... | Hash an item.
:param item: The item to hash.
| hash_item | python | superduper-io/superduper | superduper/misc/utils.py | https://github.com/superduper-io/superduper/blob/master/superduper/misc/utils.py | Apache-2.0 |
def predict(self, question: str, filename: str):
"""Predict the answer to a question based on the content of a file.
:param question: The question to ask.
:param filename: The name of the file to analyse.
:param project_name: The name of the project.
"""
files =... | Predict the answer to a question based on the content of a file.
:param question: The question to ask.
:param filename: The name of the file to analyse.
:param project_name: The name of the project.
| predict | python | superduper-io/superduper | templates/copilot/components.py | https://github.com/superduper-io/superduper/blob/master/templates/copilot/components.py | Apache-2.0 |
def analyse(self, content: str):
"""Analyse the content of a file and return a comment.
:param content: The content of the file to analyse.
"""
messages = [
{
"role": "user",
"content": self.prompt +
'\nHERE IS TH... | Analyse the content of a file and return a comment.
:param content: The content of the file to analyse.
| analyse | python | superduper-io/superduper | templates/copilot/components.py | https://github.com/superduper-io/superduper/blob/master/templates/copilot/components.py | Apache-2.0 |
async def distribute_message(message: str):
"""Send messages to all connected WebSocket clients."""
disconnected_clients = []
for client in clients:
try:
await client.send_text(message)
except Exception:
# If we fail to send, it means the client is disconnected or inv... | Send messages to all connected WebSocket clients. | distribute_message | python | superduper-io/superduper | templates/copilot/server.py | https://github.com/superduper-io/superduper/blob/master/templates/copilot/server.py | Apache-2.0 |
def background_init(db, path="."):
"""
1. Insert existing .py files into DB (if not already present).
2. Start the Watcher (blocking).
"""
now = datetime.datetime.now()
if not path.endswith('/'):
path += '/'
files = [
os.path.join(dp, f)
for dp, _, fn in os.walk(pat... |
1. Insert existing .py files into DB (if not already present).
2. Start the Watcher (blocking).
| background_init | python | superduper-io/superduper | templates/copilot/server.py | https://github.com/superduper-io/superduper/blob/master/templates/copilot/server.py | Apache-2.0 |
def get_user_input(input_mode, input_key, questions):
"""
A function to get user input based on the input mode
"""
if input_mode == "Free text":
return st.text_input(
"Enter your text", placeholder="Type here...", key=input_key
)
else: # Question Selection
return... |
A function to get user input based on the input mode
| get_user_input | python | superduper-io/superduper | templates/pdf_rag/streamlit.py | https://github.com/superduper-io/superduper/blob/master/templates/pdf_rag/streamlit.py | Apache-2.0 |
def get_related_merged_documents(
db,
contexts,
chunk_key,
split_image_key,
match_text=None,
):
"""
Convert contexts to a dataframe
Will merge the same page
"""
image_folder = os.environ.get("IMAGES_FOLDER", ".cache/images")
source_ids = [source["_source"] for source in conte... |
Convert contexts to a dataframe
Will merge the same page
| get_related_merged_documents | python | superduper-io/superduper | templates/pdf_rag/utils.py | https://github.com/superduper-io/superduper/blob/master/templates/pdf_rag/utils.py | Apache-2.0 |
def draw_rectangle_and_display(image_path, relative_coordinates, expand=0.005):
"""
Draw a rectangle on an image based on relative coordinates with the origin at the bottom-left
and display it in Jupyter Notebook.
:param image_path: Path to the original image.
:param relative_coordinates: A list of... |
Draw a rectangle on an image based on relative coordinates with the origin at the bottom-left
and display it in Jupyter Notebook.
:param image_path: Path to the original image.
:param relative_coordinates: A list of (left, bottom, right, top) coordinates as a ratio of the image size.
| draw_rectangle_and_display | python | superduper-io/superduper | templates/pdf_rag/utils.py | https://github.com/superduper-io/superduper/blob/master/templates/pdf_rag/utils.py | Apache-2.0 |
def predict(self, query: str):
"""Predict on a single query string.
:param query: Query string.
"""
from superduper.base.datalayer import Datalayer
assert isinstance(self.db, Datalayer)
select = self.select.set_variables(db=self.db, query=query)
results = [r.unp... | Predict on a single query string.
:param query: Query string.
| predict | python | superduper-io/superduper | templates/simple_rag/rag_plugin.py | https://github.com/superduper-io/superduper/blob/master/templates/simple_rag/rag_plugin.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.