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 get_arguments():
"""Parse all the arguments provided from the CLI.
Returns:
A list of parsed arguments.
"""
parser = argparse.ArgumentParser(description="DeepLab-ResNet Network")
parser.add_argument("--batch-size", type=int, default=BATCH_SIZE,
help="Number of ... | Parse all the arguments provided from the CLI.
Returns:
A list of parsed arguments.
| get_arguments | python | iyah4888/SIGGRAPH18SSS | parse_opt.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/parse_opt.py | MIT |
def __init__(self, sess, args):
"""Initialize the parameters.
sess: tensorflow session
"""
self.sess = sess
self.batch_size = args.batch_size
self.args = args
# parameters used to save a checkpoint
self.dataset = "Hypcol"
self.options = []
self._attrs = ['batch_size', 'dataset']
self.build_mo... | Initialize the parameters.
sess: tensorflow session
| __init__ | python | iyah4888/SIGGRAPH18SSS | deeplab_resnet/hc_deeplab.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/deeplab_resnet/hc_deeplab.py | MIT |
def image_scaling(img, label):
"""
Randomly scales the images between 0.5 to 1.5 times the original size.
Args:
img: Training image to scale.
label: Segmentation mask to scale.
"""
scale = tf.random_uniform([1], minval=0.5, maxval=1.5, dtype=tf.float32, seed=None)
h_new = tf.to... |
Randomly scales the images between 0.5 to 1.5 times the original size.
Args:
img: Training image to scale.
label: Segmentation mask to scale.
| image_scaling | python | iyah4888/SIGGRAPH18SSS | deeplab_resnet/image_reader.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/deeplab_resnet/image_reader.py | MIT |
def image_mirroring(img, label):
"""
Randomly mirrors the images.
Args:
img: Training image to mirror.
label: Segmentation mask to mirror.
"""
distort_left_right_random = tf.random_uniform([1], 0, 1.0, dtype=tf.float32)[0]
mirror = tf.less(tf.stack([1.0, distort_left_right_rand... |
Randomly mirrors the images.
Args:
img: Training image to mirror.
label: Segmentation mask to mirror.
| image_mirroring | python | iyah4888/SIGGRAPH18SSS | deeplab_resnet/image_reader.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/deeplab_resnet/image_reader.py | MIT |
def random_crop_and_pad_image_and_labels(image, label, crop_h, crop_w, ignore_label=255):
"""
Randomly crop and pads the input images.
Args:
image: Training image to crop/ pad.
label: Segmentation mask to crop/ pad.
crop_h: Height of cropped segment.
crop_w: Width of cropped segment... |
Randomly crop and pads the input images.
Args:
image: Training image to crop/ pad.
label: Segmentation mask to crop/ pad.
crop_h: Height of cropped segment.
crop_w: Width of cropped segment.
ignore_label: Label to ignore during the training.
| random_crop_and_pad_image_and_labels | python | iyah4888/SIGGRAPH18SSS | deeplab_resnet/image_reader.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/deeplab_resnet/image_reader.py | MIT |
def read_labeled_image_list(data_dir, data_list):
"""Reads txt file containing paths to images and ground truth masks.
Args:
data_dir: path to the directory with images and masks.
data_list: path to the file with lines of the form '/path/to/image /path/to/mask'.
Returns:
Two l... | Reads txt file containing paths to images and ground truth masks.
Args:
data_dir: path to the directory with images and masks.
data_list: path to the file with lines of the form '/path/to/image /path/to/mask'.
Returns:
Two lists with all file names for images and masks, respective... | read_labeled_image_list | python | iyah4888/SIGGRAPH18SSS | deeplab_resnet/image_reader.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/deeplab_resnet/image_reader.py | MIT |
def read_images_from_disk(input_queue, input_size, random_scale, random_mirror, ignore_label, img_mean): # optional pre-processing arguments
"""Read one image and its corresponding mask with optional pre-processing.
Args:
input_queue: tf queue with paths to the image and its mask.
input_size: a... | Read one image and its corresponding mask with optional pre-processing.
Args:
input_queue: tf queue with paths to the image and its mask.
input_size: a tuple with (height, width) values.
If not given, return images of original size.
random_scale: whether to randomly scale th... | read_images_from_disk | python | iyah4888/SIGGRAPH18SSS | deeplab_resnet/image_reader.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/deeplab_resnet/image_reader.py | MIT |
def __init__(self, data_dir, data_list, input_size,
random_scale, random_mirror, ignore_label, img_mean, coord):
'''Initialise an ImageReader.
Args:
data_dir: path to the directory with images and masks.
data_list: path to the file with lines of the form '/... | Initialise an ImageReader.
Args:
data_dir: path to the directory with images and masks.
data_list: path to the file with lines of the form '/path/to/image /path/to/mask'.
input_size: a tuple with (height, width) values, to which all the images will be resized.
ra... | __init__ | python | iyah4888/SIGGRAPH18SSS | deeplab_resnet/image_reader.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/deeplab_resnet/image_reader.py | MIT |
def dequeue(self, num_elements):
'''Pack images and labels into a batch.
Args:
num_elements: the batch size.
Returns:
Two tensors of size (batch_size, h, w, {3, 1}) for images and masks.'''
image_batch, label_batch = tf.train.batch([self.image, sel... | Pack images and labels into a batch.
Args:
num_elements: the batch size.
Returns:
Two tensors of size (batch_size, h, w, {3, 1}) for images and masks. | dequeue | python | iyah4888/SIGGRAPH18SSS | deeplab_resnet/image_reader.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/deeplab_resnet/image_reader.py | MIT |
def setup(self, is_training, num_classes):
'''Network definition.
Args:
is_training: whether to update the running mean and variance of the batch normalisation layer.
If the batch size is small, it is better to keep the running mean and variance of
... | Network definition.
Args:
is_training: whether to update the running mean and variance of the batch normalisation layer.
If the batch size is small, it is better to keep the running mean and variance of
the-pretrained model frozen.
num_... | setup | python | iyah4888/SIGGRAPH18SSS | deeplab_resnet/model.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/deeplab_resnet/model.py | MIT |
def decode_labels(mask, num_images=1, num_classes=21):
"""Decode batch of segmentation masks.
Args:
mask: result of inference after taking argmax.
num_images: number of images to decode from the batch.
num_classes: number of classes to predict (including background).
Returns:
... | Decode batch of segmentation masks.
Args:
mask: result of inference after taking argmax.
num_images: number of images to decode from the batch.
num_classes: number of classes to predict (including background).
Returns:
A batch with num_images RGB images of the same size as the ... | decode_labels | python | iyah4888/SIGGRAPH18SSS | deeplab_resnet/utils.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/deeplab_resnet/utils.py | MIT |
def prepare_label(input_batch, new_size, num_classes, one_hot=True):
"""Resize masks and perform one-hot encoding.
Args:
input_batch: input tensor of shape [batch_size H W 1].
new_size: a tensor with new height and width.
num_classes: number of classes to predict (including background).
... | Resize masks and perform one-hot encoding.
Args:
input_batch: input tensor of shape [batch_size H W 1].
new_size: a tensor with new height and width.
num_classes: number of classes to predict (including background).
one_hot: whether perform one-hot encoding.
Returns:
Outputs a te... | prepare_label | python | iyah4888/SIGGRAPH18SSS | deeplab_resnet/utils.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/deeplab_resnet/utils.py | MIT |
def inv_preprocess(imgs, num_images, img_mean):
"""Inverse preprocessing of the batch of images.
Add the mean vector and convert from BGR to RGB.
Args:
imgs: batch of input images.
num_images: number of images to apply the inverse transformations on.
img_mean: vector of mean col... | Inverse preprocessing of the batch of images.
Add the mean vector and convert from BGR to RGB.
Args:
imgs: batch of input images.
num_images: number of images to apply the inverse transformations on.
img_mean: vector of mean colour values.
Returns:
The batch of the size... | inv_preprocess | python | iyah4888/SIGGRAPH18SSS | deeplab_resnet/utils.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/deeplab_resnet/utils.py | MIT |
def __init__(self, def_path, phase='test'):
'''
def_path: Path to the model definition (.prototxt)
data_path: Path to the model data (.caffemodel)
phase: Either 'test' or 'train'. Used for filtering phase-specific nodes.
'''
self.def_path = def_path
self.phase = p... |
def_path: Path to the model definition (.prototxt)
data_path: Path to the model data (.caffemodel)
phase: Either 'test' or 'train'. Used for filtering phase-specific nodes.
| __init__ | python | iyah4888/SIGGRAPH18SSS | kaffe/graph.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/kaffe/graph.py | MIT |
def load(self):
'''Load the layer definitions from the prototxt.'''
self.params = get_caffe_resolver().NetParameter()
with open(self.def_path, 'rb') as def_file:
text_format.Merge(def_file.read(), self.params) | Load the layer definitions from the prototxt. | load | python | iyah4888/SIGGRAPH18SSS | kaffe/graph.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/kaffe/graph.py | MIT |
def filter_layers(self, layers):
'''Filter out layers based on the current phase.'''
phase_map = {0: 'train', 1: 'test'}
filtered_layer_names = set()
filtered_layers = []
for layer in layers:
phase = self.phase
if len(layer.include):
phase ... | Filter out layers based on the current phase. | filter_layers | python | iyah4888/SIGGRAPH18SSS | kaffe/graph.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/kaffe/graph.py | MIT |
def make_node(self, layer):
'''Create a graph node for the given layer.'''
kind = NodeKind.map_raw_kind(layer.type)
if kind is None:
raise KaffeError('Unknown layer type encountered: %s' % layer.type)
# We want to use the layer's top names (the "output" names), rather than th... | Create a graph node for the given layer. | make_node | python | iyah4888/SIGGRAPH18SSS | kaffe/graph.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/kaffe/graph.py | MIT |
def make_input_nodes(self):
'''
Create data input nodes.
This method is for old-style inputs, where the input specification
was not treated as a first-class layer in the prototext.
Newer models use the "Input layer" type.
'''
nodes = [Node(name, NodeKind.Data) fo... |
Create data input nodes.
This method is for old-style inputs, where the input specification
was not treated as a first-class layer in the prototext.
Newer models use the "Input layer" type.
| make_input_nodes | python | iyah4888/SIGGRAPH18SSS | kaffe/graph.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/kaffe/graph.py | MIT |
def build(self):
'''
Builds the graph from the Caffe layer definitions.
'''
# Get the layers
layers = self.params.layers or self.params.layer
# Filter out phase-excluded layers
layers = self.filter_layers(layers)
# Get any separately-specified input layers... |
Builds the graph from the Caffe layer definitions.
| build | python | iyah4888/SIGGRAPH18SSS | kaffe/graph.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/kaffe/graph.py | MIT |
def load(self, data_path, session, ignore_missing=False):
'''Load network weights.
data_path: The path to the numpy-serialized network weights
session: The current TensorFlow session
ignore_missing: If true, serialized weights for missing layers are ignored.
'''
data_dict... | Load network weights.
data_path: The path to the numpy-serialized network weights
session: The current TensorFlow session
ignore_missing: If true, serialized weights for missing layers are ignored.
| load | python | iyah4888/SIGGRAPH18SSS | kaffe/tensorflow/network.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/kaffe/tensorflow/network.py | MIT |
def feed(self, *args):
'''Set the input(s) for the next operation by replacing the terminal nodes.
The arguments can be either layer names or the actual layers.
'''
assert len(args) != 0
self.terminals = []
for fed_layer in args:
if isinstance(fed_layer, str):... | Set the input(s) for the next operation by replacing the terminal nodes.
The arguments can be either layer names or the actual layers.
| feed | python | iyah4888/SIGGRAPH18SSS | kaffe/tensorflow/network.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/kaffe/tensorflow/network.py | MIT |
def get_unique_name(self, prefix):
'''Returns an index-suffixed unique name for the given prefix.
This is used for auto-generating layer names based on the type-prefix.
'''
ident = sum(t.startswith(prefix) for t, _ in list(self.layers.items())) + 1
return '%s_%d' % (prefix, ident... | Returns an index-suffixed unique name for the given prefix.
This is used for auto-generating layer names based on the type-prefix.
| get_unique_name | python | iyah4888/SIGGRAPH18SSS | kaffe/tensorflow/network.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/kaffe/tensorflow/network.py | MIT |
def get_padding_type(kernel_params, input_shape, output_shape):
'''Translates Caffe's numeric padding to one of ('SAME', 'VALID').
Caffe supports arbitrary padding values, while TensorFlow only
supports 'SAME' and 'VALID' modes. So, not all Caffe paddings
can be translated to TensorFlow. There are some ... | Translates Caffe's numeric padding to one of ('SAME', 'VALID').
Caffe supports arbitrary padding values, while TensorFlow only
supports 'SAME' and 'VALID' modes. So, not all Caffe paddings
can be translated to TensorFlow. There are some subtleties to
how the padding edge-cases are handled. These are des... | get_padding_type | python | iyah4888/SIGGRAPH18SSS | kaffe/tensorflow/transformer.py | https://github.com/iyah4888/SIGGRAPH18SSS/blob/master/kaffe/tensorflow/transformer.py | MIT |
def run(
self,
query="What is a lagrangian?",
limit_broad_results=1_000,
limit_deduped_url_results=50,
limit_hierarchical_url_results=50,
limit_final_pagerank_results=20,
url_contains_filter=None,
):
"""Run a search query using the WebSearchEngine clie... | Run a search query using the WebSearchEngine client | run | python | SciPhi-AI/agent-search | agent_search/app/server.py | https://github.com/SciPhi-AI/agent-search/blob/master/agent_search/app/server.py | Apache-2.0 |
def to_string_dict(self) -> dict:
"""Returns a dictionary representation with all values as strings."""
return {
"score": str(self.score),
"url": self.url,
"title": self.title,
"dataset": self.dataset,
"metadata": self.metadata,
"te... | Returns a dictionary representation with all values as strings. | to_string_dict | python | SciPhi-AI/agent-search | agent_search/core/search_types.py | https://github.com/SciPhi-AI/agent-search/blob/master/agent_search/core/search_types.py | Apache-2.0 |
def select_top_urls(
ordered_points: List[AgentSearchResult],
max_urls: int = 10,
url_contains: Optional[List[str]] = None,
) -> List[str]:
"""A function to return the top unique URLs from the given poitns results."""
if not url_contains:
url_contains = []
top_urls = set([])
for poi... | A function to return the top unique URLs from the given poitns results. | select_top_urls | python | SciPhi-AI/agent-search | agent_search/core/utils.py | https://github.com/SciPhi-AI/agent-search/blob/master/agent_search/core/utils.py | Apache-2.0 |
def cosine_similarity(v1: np.ndarray, v2: np.ndarray) -> float:
"""Compute the cosine similarity between two vectors."""
dot_product = np.dot(v1, v2)
norm_v1 = np.linalg.norm(v1)
norm_v2 = np.linalg.norm(v2)
return dot_product / (norm_v1 * norm_v2) | Compute the cosine similarity between two vectors. | cosine_similarity | python | SciPhi-AI/agent-search | agent_search/core/utils.py | https://github.com/SciPhi-AI/agent-search/blob/master/agent_search/core/utils.py | Apache-2.0 |
def __init__(
self,
api_base: Optional[str] = None,
api_key: Optional[str] = None,
timeout: int = 30,
) -> None:
"""
Initializes the SciPhi client.
Args:
api_base (Optional[str]): Base URL for the SciPhi API.
api_key (Optional[str]): A... |
Initializes the SciPhi client.
Args:
api_base (Optional[str]): Base URL for the SciPhi API.
api_key (Optional[str]): API key for authenticating requests.
timeout (int): Timeout for API requests in seconds.
Raises:
ValueError: If `api_key` is not... | __init__ | python | SciPhi-AI/agent-search | agent_search/providers/sciphi.py | https://github.com/SciPhi-AI/agent-search/blob/master/agent_search/providers/sciphi.py | Apache-2.0 |
def _handle_api_response(self, response: httpx.Response) -> Dict:
"""
Handles the HTTP response from the API.
Args:
response (httpx.Response): The response from the API request.
Returns:
Dict: JSON response content.
Raises:
Exception: If the... |
Handles the HTTP response from the API.
Args:
response (httpx.Response): The response from the API request.
Returns:
Dict: JSON response content.
Raises:
Exception: If the response indicates an error.
| _handle_api_response | python | SciPhi-AI/agent-search | agent_search/providers/sciphi.py | https://github.com/SciPhi-AI/agent-search/blob/master/agent_search/providers/sciphi.py | Apache-2.0 |
def _handle_search_response(self, search_results: Dict[str, str]) -> None:
"""
Handles dictionary search resopnses from the API.
Args:
search_results (Dict[str, str]): The response from the API request.
Returns:
Dict: JSON response content.
Raises:
... |
Handles dictionary search resopnses from the API.
Args:
search_results (Dict[str, str]): The response from the API request.
Returns:
Dict: JSON response content.
Raises:
Exception: If the response indicates an error.
| _handle_search_response | python | SciPhi-AI/agent-search | agent_search/providers/sciphi.py | https://github.com/SciPhi-AI/agent-search/blob/master/agent_search/providers/sciphi.py | Apache-2.0 |
def _retry_api_request(
self, method: str, url: str, payload: Dict, max_retries: int = 3
):
"""
Common method for retrying API requests with exponential backoff.
Args:
method (str): The HTTP method to use ('get' or 'post').
url (str): The API endpoint.
... |
Common method for retrying API requests with exponential backoff.
Args:
method (str): The HTTP method to use ('get' or 'post').
url (str): The API endpoint.
payload (Dict): The payload for the request.
max_retries (int): Maximum number of retry attempts.... | _retry_api_request | python | SciPhi-AI/agent-search | agent_search/providers/sciphi.py | https://github.com/SciPhi-AI/agent-search/blob/master/agent_search/providers/sciphi.py | Apache-2.0 |
def search(
self, query: str, search_provider: str, max_retries: int = 3
) -> List[Dict]:
"""
Performs a search query using the SciPhi API with retry and backoff logic.
Args:
query (str): The search query string.
search_provider (str): The search provider to ... |
Performs a search query using the SciPhi API with retry and backoff logic.
Args:
query (str): The search query string.
search_provider (str): The search provider to use.
max_retries (int): Maximum number of retry attempts.
Returns:
List[Dict]: A lis... | search | python | SciPhi-AI/agent-search | agent_search/providers/sciphi.py | https://github.com/SciPhi-AI/agent-search/blob/master/agent_search/providers/sciphi.py | Apache-2.0 |
def get_search_rag_response(
self,
query: str,
search_provider: str,
llm_model: str = "SciPhi/Sensei-7B-V1",
temperature: int = 0.2,
top_p: int = 0.95,
):
"""
Retrieves a search RAG (Retrieval-Augmented Generation) response from the API.
Args:... |
Retrieves a search RAG (Retrieval-Augmented Generation) response from the API.
Args:
query (str): The search query string.
search_provider (str): The search provider to use.
llm_model (str): The language model to use.
temperature (int): The temperature s... | get_search_rag_response | python | SciPhi-AI/agent-search | agent_search/providers/sciphi.py | https://github.com/SciPhi-AI/agent-search/blob/master/agent_search/providers/sciphi.py | Apache-2.0 |
def completion(
self,
prompt: str,
llm_model_name: str = "SciPhi/Sensei-7B-V1",
llm_max_tokens_to_sample: int = 1_024,
llm_temperature: float = 0.2,
llm_top_p: float = 0.90,
) -> SearchRAGResponse:
"""
Generates a completion for a given prompt using th... |
Generates a completion for a given prompt using the SciPhi API.
Args:
prompt (str): The prompt for generating completion.
llm_model_name (str): The language model to use.
llm_max_tokens_to_sample (int): Maximum number of tokens for the sample.
llm_temper... | completion | python | SciPhi-AI/agent-search | agent_search/providers/sciphi.py | https://github.com/SciPhi-AI/agent-search/blob/master/agent_search/providers/sciphi.py | Apache-2.0 |
def process_rows(rows, output_queue):
"""Process the rows into qdrant point objects."""
qdrant_points = []
for row in rows:
_, url, __, text_chunks, embeddings_binary, ___, ____ = row
embeddings = np.frombuffer(
embeddings_binary, dtype=np.float32
).reshape(-1, EMBEDDING_... | Process the rows into qdrant point objects. | process_rows | python | SciPhi-AI/agent-search | agent_search/scripts/populate_qdrant_from_postgres.py | https://github.com/SciPhi-AI/agent-search/blob/master/agent_search/scripts/populate_qdrant_from_postgres.py | Apache-2.0 |
def qdrant_writer(config, qdrant_queue, delete_existing):
"""A writer that listens for output events in a separate thread."""
qclient = QdrantClient(
config["qdrant_host"],
port=config["qdrant_grpc_port"],
prefer_grpc=config["qdrant_prefer_grpc"],
)
if delete_existing:
qc... | A writer that listens for output events in a separate thread. | qdrant_writer | python | SciPhi-AI/agent-search | agent_search/scripts/populate_qdrant_from_postgres.py | https://github.com/SciPhi-AI/agent-search/blob/master/agent_search/scripts/populate_qdrant_from_postgres.py | Apache-2.0 |
def process_batches(config, start, end, batch_size, output_queue):
"""Processes the batches in steps of the given batch_size"""
# Connect to the database
conn = psycopg2.connect(
dbname=config["postgres_db"],
user=config["postgres_user"],
password=config["postgres_password"],
... | Processes the batches in steps of the given batch_size | process_batches | python | SciPhi-AI/agent-search | agent_search/scripts/populate_qdrant_from_postgres.py | https://github.com/SciPhi-AI/agent-search/blob/master/agent_search/scripts/populate_qdrant_from_postgres.py | Apache-2.0 |
def run(self, num_processes=16, batch_size=1_024, delete_existing=False):
"""Runs the population process for the qdrant database"""
qdrant_queue = multiprocessing.Queue()
qdrant_writer_thread = multiprocessing.Process(
target=qdrant_writer,
args=(
self.con... | Runs the population process for the qdrant database | run | python | SciPhi-AI/agent-search | agent_search/scripts/populate_qdrant_from_postgres.py | https://github.com/SciPhi-AI/agent-search/blob/master/agent_search/scripts/populate_qdrant_from_postgres.py | Apache-2.0 |
def hierarchical_similarity_reranking(
self,
query_vector: np.ndarray,
urls: List[str],
limit: int = 100,
) -> List[AgentSearchResult]:
"""Hierarchical URL search to find the most similar text chunk for the given query and URLs"""
results = self.execute_batch_query(ur... | Hierarchical URL search to find the most similar text chunk for the given query and URLs | hierarchical_similarity_reranking | python | SciPhi-AI/agent-search | agent_search/search/base.py | https://github.com/SciPhi-AI/agent-search/blob/master/agent_search/search/base.py | Apache-2.0 |
def pagerank_reranking(
self,
similarity_results: List[AgentSearchResult],
limit: int = 100,
) -> List[AgentSearchResult]:
"""Reranks the results based on the PageRank score of the domain"""
if not self.pagerank_rerank_module:
raise Exception(
"Pag... | Reranks the results based on the PageRank score of the domain | pagerank_reranking | python | SciPhi-AI/agent-search | agent_search/search/base.py | https://github.com/SciPhi-AI/agent-search/blob/master/agent_search/search/base.py | Apache-2.0 |
def scrub_str(string):
"""
The purpose of this function is to scrub the weird template mark-up out of strings
that Veekun is using for their pokedex.
Example:
[]{move:dragon-tail} will effect the opponents [HP]{mechanic:hp}.
Becomes:
dragon tail will effect the opponents HP.
If ... |
The purpose of this function is to scrub the weird template mark-up out of strings
that Veekun is using for their pokedex.
Example:
[]{move:dragon-tail} will effect the opponents [HP]{mechanic:hp}.
Becomes:
dragon tail will effect the opponents HP.
If you find this results in weird... | scrub_str | python | PokeAPI/pokeapi | data/v2/build.py | https://github.com/PokeAPI/pokeapi/blob/master/data/v2/build.py | BSD-3-Clause |
def __SectionLength(this):
"""(4 bytes) Gets the length of characters the given section is"""
offset = this.__SectionDataOffset
return struct.unpack_from("<I", this.__data, offset)[0] | (4 bytes) Gets the length of characters the given section is | __SectionLength | python | PokeAPI/pokeapi | Resources/scripts/data/gen8/read_swsh.py | https://github.com/PokeAPI/pokeapi/blob/master/Resources/scripts/data/gen8/read_swsh.py | BSD-3-Clause |
def __LineOffsets(this):
"""Figures out the offset for each entry based on the data section offset"""
result = [None] * this.__LineCount
sdo = int(this.__SectionDataOffset)
for i in range(0, len(result)):
result[i] = TextLine()
result[i].offset = struct.unpack_from("<i", this.__data, (i * 8) + sdo + 4)[0]... | Figures out the offset for each entry based on the data section offset | __LineOffsets | python | PokeAPI/pokeapi | Resources/scripts/data/gen8/read_swsh.py | https://github.com/PokeAPI/pokeapi/blob/master/Resources/scripts/data/gen8/read_swsh.py | BSD-3-Clause |
def HashFNV1_64(this, word):
"""Fowler-Noll-Vo hash function; 64-bit"""
fnvPrime_64 = 0x100000001b3
offsetBasis_64 = 0xCBF29CE484222645
hash = offsetBasis_64
for c in word:
hash = hash ^ ord(c)
# Cast hash to at 64-bit value
hash = (hash * fnvPrime_64) % 2**64
return hash | Fowler-Noll-Vo hash function; 64-bit | HashFNV1_64 | python | PokeAPI/pokeapi | Resources/scripts/data/gen8/read_swsh.py | https://github.com/PokeAPI/pokeapi/blob/master/Resources/scripts/data/gen8/read_swsh.py | BSD-3-Clause |
def __LineData(this, data):
"""Loads the file into a list to later decrypt"""
key = copy.copy(this.__KEY_BASE)
result = [None] * this.__LineCount
lines = this.__LineOffsets
for i in range(0, len(lines)):
# Make a list twice the size of the current text line size
encrypted = lines[i].length * 2
# The... | Loads the file into a list to later decrypt | __LineData | python | PokeAPI/pokeapi | Resources/scripts/data/gen8/read_swsh.py | https://github.com/PokeAPI/pokeapi/blob/master/Resources/scripts/data/gen8/read_swsh.py | BSD-3-Clause |
def __CryptLineData(this, data, key):
"""Decrypts the given line into a list of bytes"""
copied = copy.copy(data)
result = [None] * len(copied)
for i in range(0, len(copied), 2):
result[i] = copied[i] ^ (key % 256)
result[i + 1] = copied[i + 1] ^ ((key >> 8) % 256)
# Bit-shift and OR key, then cast to... | Decrypts the given line into a list of bytes | __CryptLineData | python | PokeAPI/pokeapi | Resources/scripts/data/gen8/read_swsh.py | https://github.com/PokeAPI/pokeapi/blob/master/Resources/scripts/data/gen8/read_swsh.py | BSD-3-Clause |
def __GetLineString(this, data):
"""Turns the given list of bytes into a finished string"""
if (data is None):
return None
string = ""
i = 0
while (i < len(data)):
# Cast 2 bytes to figure out what to do next
value = struct.unpack_from("<H", data, i)[0]
if (value == this.__KEY_TERMINATOR):
br... | Turns the given list of bytes into a finished string | __GetLineString | python | PokeAPI/pokeapi | Resources/scripts/data/gen8/read_swsh.py | https://github.com/PokeAPI/pokeapi/blob/master/Resources/scripts/data/gen8/read_swsh.py | BSD-3-Clause |
def __MakeLabelHash(this, f):
"""Returns the label name and a FNV1_64 hash"""
# Next 8 bytes is the hash of the label name
hash = struct.unpack("<Q", f.read(8))[0]
# Next 2 bytes is the label"s name length
nameLength = struct.unpack("<H", f.read(2))[0]
# Read the bytes until 0x0 is found
name = this.__Rea... | Returns the label name and a FNV1_64 hash | __MakeLabelHash | python | PokeAPI/pokeapi | Resources/scripts/data/gen8/read_swsh.py | https://github.com/PokeAPI/pokeapi/blob/master/Resources/scripts/data/gen8/read_swsh.py | BSD-3-Clause |
def __ReadUntil(this, f, value):
"""Reads the given file until it reaches the given value"""
string = ""
c = f.read(1)
end = bytes([value])
while (c != end):
# Read one byte at a time to get each character
string += c.decode("utf-8")
c = f.read(1)
return string | Reads the given file until it reaches the given value | __ReadUntil | python | PokeAPI/pokeapi | Resources/scripts/data/gen8/read_swsh.py | https://github.com/PokeAPI/pokeapi/blob/master/Resources/scripts/data/gen8/read_swsh.py | BSD-3-Clause |
def call_phone_number(input: str) -> str:
"""calls a phone number as a bot and returns a transcript of the conversation.
the input to this tool is a pipe separated list of a phone number, a prompt, and the first thing the bot should say.
The prompt should instruct the bot with what to do on the call and be ... | calls a phone number as a bot and returns a transcript of the conversation.
the input to this tool is a pipe separated list of a phone number, a prompt, and the first thing the bot should say.
The prompt should instruct the bot with what to do on the call and be in the 3rd person,
like 'the assistant is per... | call_phone_number | python | vocodedev/vocode-core | apps/langchain_agent/tools/vocode.py | https://github.com/vocodedev/vocode-core/blob/master/apps/langchain_agent/tools/vocode.py | MIT |
async def respond(
self,
human_input: str,
conversation_id: str,
is_interrupt: bool = False,
) -> Tuple[Optional[str], bool]:
"""Generates a response from the SpellerAgent.
The response is generated by joining each character in the human input with a space.
T... | Generates a response from the SpellerAgent.
The response is generated by joining each character in the human input with a space.
The second element of the tuple indicates whether the agent should stop (False means it should not stop).
Args:
human_input (str): The input from the hum... | respond | python | vocodedev/vocode-core | apps/telephony_app/speller_agent.py | https://github.com/vocodedev/vocode-core/blob/master/apps/telephony_app/speller_agent.py | MIT |
def create_agent(self, agent_config: AgentConfig) -> BaseAgent:
"""Creates an agent based on the provided agent configuration.
Args:
agent_config (AgentConfig): The configuration for the agent to be created.
Returns:
BaseAgent: The created agent.
Raises:
... | Creates an agent based on the provided agent configuration.
Args:
agent_config (AgentConfig): The configuration for the agent to be created.
Returns:
BaseAgent: The created agent.
Raises:
Exception: If the agent configuration type is not recognized.
... | create_agent | python | vocodedev/vocode-core | apps/telephony_app/speller_agent.py | https://github.com/vocodedev/vocode-core/blob/master/apps/telephony_app/speller_agent.py | MIT |
def get_metrics_data(self):
"""Reads and returns current metrics from the SDK"""
with self._lock:
self.collect()
metrics_data = self._metrics_data
self._metrics_data = None
return metrics_data | Reads and returns current metrics from the SDK | get_metrics_data | python | vocodedev/vocode-core | playground/streaming/tracing_utils.py | https://github.com/vocodedev/vocode-core/blob/master/playground/streaming/tracing_utils.py | MIT |
def default_env_vars() -> dict[str, str]:
"""
Defines default environment variables for the test session.
This fixture provides a dictionary of default environment variables that are
commonly used across tests. It can be overridden in submodule scoped `conftest.py`
files or directly in tests.
... |
Defines default environment variables for the test session.
This fixture provides a dictionary of default environment variables that are
commonly used across tests. It can be overridden in submodule scoped `conftest.py`
files or directly in tests.
:return: A dictionary of default environment vari... | default_env_vars | python | vocodedev/vocode-core | tests/conftest.py | https://github.com/vocodedev/vocode-core/blob/master/tests/conftest.py | MIT |
def mock_env(
monkeypatch: MonkeyPatch, request: pytest.FixtureRequest, default_env_vars: dict[str, str]
) -> Generator[None, None, None]:
"""
Temporarily sets environment variables for testing.
This fixture allows tests to run with a modified set of environment variables,
either using the default ... |
Temporarily sets environment variables for testing.
This fixture allows tests to run with a modified set of environment variables,
either using the default set provided by `default_env_vars` or overridden by
test-specific parameters. It ensures that changes to environment variables do
not leak bet... | mock_env | python | vocodedev/vocode-core | tests/conftest.py | https://github.com/vocodedev/vocode-core/blob/master/tests/conftest.py | MIT |
def default_env_vars(default_env_vars: dict[str, str]) -> dict[str, str]:
"""
Extends the `default_env_vars` fixture specifically for the submodule.
This fixture takes the session-scoped `default_env_vars` fixture from the parent conftest.py
and extends or overrides it with additional or modified envir... |
Extends the `default_env_vars` fixture specifically for the submodule.
This fixture takes the session-scoped `default_env_vars` fixture from the parent conftest.py
and extends or overrides it with additional or modified environment variables specific to
the submodule.
:param default_env_vars: The... | default_env_vars | python | vocodedev/vocode-core | tests/streaming/action/conftest.py | https://github.com/vocodedev/vocode-core/blob/master/tests/streaming/action/conftest.py | MIT |
def action_config() -> dict:
"""Provides a common action configuration for tests."""
return {
"processing_mode": "muted",
"name": "name",
"description": "A description",
"url": "https://example.com",
"input_schema": json.dumps(ACTION_INPUT_SCHEMA),
"speak_on_send"... | Provides a common action configuration for tests. | action_config | python | vocodedev/vocode-core | tests/streaming/action/test_external_actions.py | https://github.com/vocodedev/vocode-core/blob/master/tests/streaming/action/test_external_actions.py | MIT |
def execute_action_setup(mocker, action_config) -> ExecuteExternalAction:
"""Common setup for creating an ExecuteExternalAction instance."""
action = ExecuteExternalAction(
action_config=ExecuteExternalActionVocodeActionConfig(**action_config),
)
mocked_requester = mocker.AsyncMock()
mocked_... | Common setup for creating an ExecuteExternalAction instance. | execute_action_setup | python | vocodedev/vocode-core | tests/streaming/action/test_external_actions.py | https://github.com/vocodedev/vocode-core/blob/master/tests/streaming/action/test_external_actions.py | MIT |
def _patched_serialize_record(text: str, record: dict) -> str:
"""
This function takes a text string and a record dictionary as input and returns a serialized
string representation of the record.
The record dictionary is expected to contain various keys related to logging information such as
'level... |
This function takes a text string and a record dictionary as input and returns a serialized
string representation of the record.
The record dictionary is expected to contain various keys related to logging information such as
'level', 'time', 'elapsed', 'exception', 'extra', 'file', 'function', 'line'... | _patched_serialize_record | python | vocodedev/vocode-core | vocode/logging.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/logging.py | MIT |
def emit(self, record: logging.LogRecord) -> None: # pragma: no cover
"""
Propagates logs to loguru.
:param record: record to log.
"""
try:
level: str | int = logger.level(record.levelname).name
except ValueError:
level = record.levelno
... |
Propagates logs to loguru.
:param record: record to log.
| emit | python | vocodedev/vocode-core | vocode/logging.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/logging.py | MIT |
def configure_intercepter() -> None:
"""
Configures the logging system to intercept log messages.
This function sets up an InterceptHandler instance as the main handler for the root logger.
It sets the logging level to INFO, meaning that all messages with severity INFO and above will be handled.
I... |
Configures the logging system to intercept log messages.
This function sets up an InterceptHandler instance as the main handler for the root logger.
It sets the logging level to INFO, meaning that all messages with severity INFO and above will be handled.
It then iterates over all the loggers in the ... | configure_intercepter | python | vocodedev/vocode-core | vocode/logging.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/logging.py | MIT |
def configure_pretty_logging() -> None:
"""
Configures the logging system to output pretty logs.
This function enables the 'vocode' logger, sets up an intercept handler to
capture logs from the standard logging module, removes all existing handlers
from the 'loguru' logger, and adds a new handler t... |
Configures the logging system to output pretty logs.
This function enables the 'vocode' logger, sets up an intercept handler to
capture logs from the standard logging module, removes all existing handlers
from the 'loguru' logger, and adds a new handler that outputs to stdout with
pretty formattin... | configure_pretty_logging | python | vocodedev/vocode-core | vocode/logging.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/logging.py | MIT |
def configure_json_logging() -> None:
"""
Configures the logging system to output logs in JSON format.
This function enables the 'vocode' logger, sets up an intercept handler to
capture logs from the standard logging module, removes all existing handlers
from the 'loguru' logger, and adds a new han... |
Configures the logging system to output logs in JSON format.
This function enables the 'vocode' logger, sets up an intercept handler to
capture logs from the standard logging module, removes all existing handlers
from the 'loguru' logger, and adds a new handler that outputs to stdout with
JSON for... | configure_json_logging | python | vocodedev/vocode-core | vocode/logging.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/logging.py | MIT |
async def check_for_idle(self):
"""Asks if human is still on the line if no activity is detected, and terminates the conversation if not."""
await self.initial_message_tracker.wait()
check_human_present_count = 0
check_human_present_threshold = self.agent.get_agent_config().num_check_hum... | Asks if human is still on the line if no activity is detected, and terminates the conversation if not. | check_for_idle | python | vocodedev/vocode-core | vocode/streaming/streaming_conversation.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/streaming_conversation.py | MIT |
async def broadcast_interrupt(self):
"""Stops all inflight events and cancels all workers that are sending output
Returns true if any events were interrupted - which is used as a flag for the agent (is_interrupt)
"""
async with self.interrupt_lock:
num_interrupts = 0
... | Stops all inflight events and cancels all workers that are sending output
Returns true if any events were interrupted - which is used as a flag for the agent (is_interrupt)
| broadcast_interrupt | python | vocodedev/vocode-core | vocode/streaming/streaming_conversation.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/streaming_conversation.py | MIT |
async def send_speech_to_output(
self,
message: str,
synthesis_result: SynthesisResult,
stop_event: threading.Event,
seconds_per_chunk: float,
transcript_message: Optional[Message] = None,
started_event: Optional[threading.Event] = None,
):
"""
... |
- Sends the speech chunk by chunk to the output device
- update the transcript message as chunks come in (transcript_message is always provided for non filler audio utterances)
- If the stop_event is set, the output is stopped
- Sets started_event when the first chunk is sent
... | send_speech_to_output | python | vocodedev/vocode-core | vocode/streaming/streaming_conversation.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/streaming_conversation.py | MIT |
async def _end_of_run_hook(self) -> None:
"""This method is called at the end of the run method. It is optional but intended to be
overridden if needed."""
pass | This method is called at the end of the run method. It is optional but intended to be
overridden if needed. | _end_of_run_hook | python | vocodedev/vocode-core | vocode/streaming/action/end_conversation.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/action/end_conversation.py | MIT |
def merge_event_logs(event_logs: List[EventLog]) -> List[EventLog]:
"""Returns a new list of event logs where consecutive bot messages are merged."""
new_event_logs: List[EventLog] = []
idx = 0
while idx < len(event_logs):
bot_messages_buffer: List[Message] = []
current_log = event_logs[... | Returns a new list of event logs where consecutive bot messages are merged. | merge_event_logs | python | vocodedev/vocode-core | vocode/streaming/agent/openai_utils.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/agent/openai_utils.py | MIT |
def split_sentences(text: str) -> List[str]:
"""Splits text into sentences and preserve trailing periods.
Merge sentences that are just numbers, as they are part of lists.
"""
initial_split = text.split(". ")
final_split = []
buffer = ""
for i, sentence in enumerate(initial_split):
... | Splits text into sentences and preserve trailing periods.
Merge sentences that are just numbers, as they are part of lists.
| split_sentences | python | vocodedev/vocode-core | vocode/streaming/agent/streaming_utils.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/agent/streaming_utils.py | MIT |
def num_tokens_from_messages(messages: List[dict], model: str = "gpt-3.5-turbo-0613"):
"""Return the number of tokens used by a list of messages."""
tokenizer_info = get_tokenizer_info(model)
if tokenizer_info is None:
raise NotImplementedError(
f"""num_tokens_from_messages() is not impl... | Return the number of tokens used by a list of messages. | num_tokens_from_messages | python | vocodedev/vocode-core | vocode/streaming/agent/token_utils.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/agent/token_utils.py | MIT |
def tokens_from_dict(encoding: tiktoken.Encoding, d: Dict[str, Any], tokens_per_name: int) -> int:
"""Return the number of OpenAI tokens in a dict."""
num_tokens: int = 0
for key, value in d.items():
if value is None:
continue
if isinstance(value, str):
num_tokens += ... | Return the number of OpenAI tokens in a dict. | tokens_from_dict | python | vocodedev/vocode-core | vocode/streaming/agent/token_utils.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/agent/token_utils.py | MIT |
def num_tokens_from_functions(functions: List[dict] | None, model="gpt-3.5-turbo-0613") -> int:
"""Return the number of tokens used by a list of functions."""
if not functions:
return 0
try:
encoding = tiktoken.encoding_for_model(model)
except KeyError:
logger.warning("Warning: ... | Return the number of tokens used by a list of functions. | num_tokens_from_functions | python | vocodedev/vocode-core | vocode/streaming/agent/token_utils.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/agent/token_utils.py | MIT |
async def initialize_source(self, room: rtc.Room):
"""Creates the AudioSource that will be used to capture audio frames.
Can only be called once the room has set up its track callbcks
"""
self.room = room
source = rtc.AudioSource(self.sampling_rate, NUM_CHANNELS)
track =... | Creates the AudioSource that will be used to capture audio frames.
Can only be called once the room has set up its track callbcks
| initialize_source | python | vocodedev/vocode-core | vocode/streaming/output_device/livekit_output_device.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/output_device/livekit_output_device.py | MIT |
async def play(self, chunk: bytes):
"""Sends an audio chunk to immediate playback"""
pass | Sends an audio chunk to immediate playback | play | python | vocodedev/vocode-core | vocode/streaming/output_device/rate_limit_interruptions_output_device.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/output_device/rate_limit_interruptions_output_device.py | MIT |
async def listen() -> None:
"""Listen to the websocket for audio data and stream it."""
first_message = True
buffer = bytearray()
while True:
message = await ws.recv()
if "audio" not in message:
... | Listen to the websocket for audio data and stream it. | listen | python | vocodedev/vocode-core | vocode/streaming/synthesizer/eleven_labs_websocket_synthesizer.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/synthesizer/eleven_labs_websocket_synthesizer.py | MIT |
async def create_speech_uncached(
self,
message: BaseMessage,
chunk_size: int,
is_first_text_chunk: bool = False,
is_sole_text_chunk: bool = False,
):
"""
Ran when doing utterance parsing.
ie: "Hello, my name is foo."
"""
if not self.we... |
Ran when doing utterance parsing.
ie: "Hello, my name is foo."
| create_speech_uncached | python | vocodedev/vocode-core | vocode/streaming/synthesizer/eleven_labs_websocket_synthesizer.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/synthesizer/eleven_labs_websocket_synthesizer.py | MIT |
async def send_token_to_synthesizer(self, message: LLMToken, chunk_size: int):
"""
Ran when parsing a single chunk of text.
ie: "Hello,"
"""
self.total_chars += len(message.text)
if not self.websocket_listener:
self.websocket_listener = asyncio.create_task(
... |
Ran when parsing a single chunk of text.
ie: "Hello,"
| send_token_to_synthesizer | python | vocodedev/vocode-core | vocode/streaming/synthesizer/eleven_labs_websocket_synthesizer.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/synthesizer/eleven_labs_websocket_synthesizer.py | MIT |
async def generate_chunks(
play_ht_chunk: bytes,
cut_leading_silence=False,
) -> AsyncGenerator[bytes, None]:
"""Yields chunks of size chunk_size from play_ht_chunk and leaves the remainder in buffer.
If cut_leading_silence is True, does not yield chunks until it... | Yields chunks of size chunk_size from play_ht_chunk and leaves the remainder in buffer.
If cut_leading_silence is True, does not yield chunks until it detects voice.
| generate_chunks | python | vocodedev/vocode-core | vocode/streaming/synthesizer/play_ht_synthesizer_v2.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/synthesizer/play_ht_synthesizer_v2.py | MIT |
async def _cut_out_trailing_silence(
trailing_chunk: bytes,
) -> AsyncGenerator[bytes, None]:
"""Yields chunks of size chunk_size from trailing_chunk until it detects silence."""
for buffer_idx, chunk in self._enumerate_by_chunk_size(trailing_chunk, chunk_size):
... | Yields chunks of size chunk_size from trailing_chunk until it detects silence. | _cut_out_trailing_silence | python | vocodedev/vocode-core | vocode/streaming/synthesizer/play_ht_synthesizer_v2.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/synthesizer/play_ht_synthesizer_v2.py | MIT |
def __init__(
self,
prefix: Optional[str] = None,
suffix: Optional[str] = None,
) -> None:
"""
Initialize a RedisGenericMessageQueue instance.
This initializes a Redis client and sets the name of the stream.
"""
self.redis: Redis = initialize_redis()
... |
Initialize a RedisGenericMessageQueue instance.
This initializes a Redis client and sets the name of the stream.
| __init__ | python | vocodedev/vocode-core | vocode/streaming/utils/redis.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/utils/redis.py | MIT |
async def publish(self, message: dict) -> None:
"""
Publishes a message to the Redis stream.
Args:
message (dict): The message to be published.
Returns:
None
"""
logger.info(f"[{self.queue_name}] Publishing message: {message}")
try:
... |
Publishes a message to the Redis stream.
Args:
message (dict): The message to be published.
Returns:
None
| publish | python | vocodedev/vocode-core | vocode/streaming/utils/redis.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/utils/redis.py | MIT |
async def process(self, item):
"""
Publish results onto output queue.
Calls to async function / task should be able to handle asyncio.CancelledError gracefully and not re-raise it
"""
raise NotImplementedError |
Publish results onto output queue.
Calls to async function / task should be able to handle asyncio.CancelledError gracefully and not re-raise it
| process | python | vocodedev/vocode-core | vocode/streaming/utils/worker.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/utils/worker.py | MIT |
def interrupt(self) -> bool:
"""
Returns True if the event was interruptible and is now interrupted.
"""
if not self.is_interruptible:
return False
self.interruption_event.set()
return True |
Returns True if the event was interruptible and is now interrupted.
| interrupt | python | vocodedev/vocode-core | vocode/streaming/utils/worker.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/utils/worker.py | MIT |
async def process(self, item: InterruptibleEventType):
"""
Publish results onto output queue.
Calls to async function / task should be able to handle asyncio.CancelledError gracefully:
"""
raise NotImplementedError |
Publish results onto output queue.
Calls to async function / task should be able to handle asyncio.CancelledError gracefully:
| process | python | vocodedev/vocode-core | vocode/streaming/utils/worker.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/utils/worker.py | MIT |
def cancel_current_task(self):
"""Free up the resources. That's useful so implementors do not have to implement this but:
- threads tasks won't be able to be interrupted. Hopefully not too much of a big deal
Threads will also get a reference to the interruptible event
- asyncio tasks... | Free up the resources. That's useful so implementors do not have to implement this but:
- threads tasks won't be able to be interrupted. Hopefully not too much of a big deal
Threads will also get a reference to the interruptible event
- asyncio tasks will still have to handle CancelledError ... | cancel_current_task | python | vocodedev/vocode-core | vocode/streaming/utils/worker.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/utils/worker.py | MIT |
async def generate_from_async_iter_with_lookahead(
async_iter: AsyncIterator[AsyncIteratorGenericType],
lookahead: int,
) -> AsyncGenerator[List[AsyncIteratorGenericType], None]:
"""Yield sliding window lists of length `lookahead + 1` from an async iterator.
If the length of async iterator < lookahead ... | Yield sliding window lists of length `lookahead + 1` from an async iterator.
If the length of async iterator < lookahead + 1, then it should just yield the whole
async iterator as a list.
| generate_from_async_iter_with_lookahead | python | vocodedev/vocode-core | vocode/streaming/utils/__init__.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/utils/__init__.py | MIT |
async def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
namespace: Optional[str] = None,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Args:
t... | Run more texts through the embeddings and add to the vectorstore.
Args:
texts: Iterable of strings to add to the vectorstore.
metadatas: Optional list of metadatas associated with the texts.
ids: Optional list of ids to associate with the texts.
namespace: Option... | add_texts | python | vocodedev/vocode-core | vocode/streaming/vector_db/pinecone.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/vector_db/pinecone.py | MIT |
async def similarity_search_with_score(
self,
query: str,
filter: Optional[dict] = None,
namespace: Optional[str] = None,
) -> List[Tuple[Document, float]]:
"""Return pinecone documents most similar to query, along with scores.
Args:
query: Text to look u... | Return pinecone documents most similar to query, along with scores.
Args:
query: Text to look up documents similar to.
filter: Dictionary of argument(s) to filter on metadata
namespace: Namespace to search in. Default will search in '' namespace.
Returns:
... | similarity_search_with_score | python | vocodedev/vocode-core | vocode/streaming/vector_db/pinecone.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/streaming/vector_db/pinecone.py | MIT |
def __init__(self, func: Callable, *args: Tuple, **kwargs: Dict) -> None:
"""
Constructs all the necessary attributes for the SentryConfiguredContextManager object.
Args:
func (Callable): The function to be executed.
*args (Tuple): The positional arguments to pass to the... |
Constructs all the necessary attributes for the SentryConfiguredContextManager object.
Args:
func (Callable): The function to be executed.
*args (Tuple): The positional arguments to pass to the function.
**kwargs (Dict): The keyword arguments to pass to the function... | __init__ | python | vocodedev/vocode-core | vocode/utils/sentry_utils.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/utils/sentry_utils.py | MIT |
def is_configured(self) -> bool:
"""
Checks if Sentry is configured.
Returns:
bool: True if Sentry is configured, False otherwise.
"""
client = sentry_sdk.Hub.current.client
if client is not None and client.options is not None and "dsn" in client.options:
... |
Checks if Sentry is configured.
Returns:
bool: True if Sentry is configured, False otherwise.
| is_configured | python | vocodedev/vocode-core | vocode/utils/sentry_utils.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/utils/sentry_utils.py | MIT |
def __enter__(self) -> Optional[Any]:
"""
Executes the function if Sentry is configured.
Returns:
Any: The result of the function execution, or None if Sentry is not configured.
"""
if self.is_configured:
self.result = self.func(*self.args, **self.kwargs)... |
Executes the function if Sentry is configured.
Returns:
Any: The result of the function execution, or None if Sentry is not configured.
| __enter__ | python | vocodedev/vocode-core | vocode/utils/sentry_utils.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/utils/sentry_utils.py | MIT |
def __call__(self) -> Optional[Any]:
"""
Executes the function if Sentry is configured, and prints a message if it's not.
Returns:
Any: The result of the function execution, or None if Sentry is not configured.
"""
if self.is_configured:
return self.func(... |
Executes the function if Sentry is configured, and prints a message if it's not.
Returns:
Any: The result of the function execution, or None if Sentry is not configured.
| __call__ | python | vocodedev/vocode-core | vocode/utils/sentry_utils.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/utils/sentry_utils.py | MIT |
def synthesizer_base_name_if_should_report_to_sentry(
synthesizer: "BaseSynthesizer",
) -> Optional[str]:
"""Returns a synthesizer name if we should report metrics to Sentry for this
kind of synthesizer; else returns None.
"""
return f"synthesizer.{_SYNTHESIZER_NAMES.get(synthesizer.__class__.__qual... | Returns a synthesizer name if we should report metrics to Sentry for this
kind of synthesizer; else returns None.
| synthesizer_base_name_if_should_report_to_sentry | python | vocodedev/vocode-core | vocode/utils/sentry_utils.py | https://github.com/vocodedev/vocode-core/blob/master/vocode/utils/sentry_utils.py | MIT |
def HandleRequest(req, method, post_data=None):
"""Sample dynamic HTTP response handler.
Parameters
----------
req : BaseHTTPServer.BaseHTTPRequestHandler
The BaseHTTPRequestHandler that recevied the request
method: str
The HTTP method, either 'HEAD', 'GET', 'POST' as of this writin... | Sample dynamic HTTP response handler.
Parameters
----------
req : BaseHTTPServer.BaseHTTPRequestHandler
The BaseHTTPRequestHandler that recevied the request
method: str
The HTTP method, either 'HEAD', 'GET', 'POST' as of this writing
post_data: str
The HTTP post data receive... | HandleRequest | python | mandiant/flare-fakenet-ng | fakenet/configs/CustomProviderExample.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/configs/CustomProviderExample.py | Apache-2.0 |
def HandleTcp(sock):
"""Handle a TCP buffer.
Parameters
----------
sock : socket
The connected socket with which to recv and send data
"""
while True:
try:
data = None
data = sock.recv(1024)
except socket.timeout:
pass
if not ... | Handle a TCP buffer.
Parameters
----------
sock : socket
The connected socket with which to recv and send data
| HandleTcp | python | mandiant/flare-fakenet-ng | fakenet/configs/CustomProviderExample.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/configs/CustomProviderExample.py | Apache-2.0 |
def HandleUdp(sock, data, addr):
"""Handle a UDP buffer.
Parameters
----------
sock : socket
The connected socket with which to recv and send data
data : str
The data received
addr : tuple
The host and port of the remote peer
"""
if data:
resp = input('\n... | Handle a UDP buffer.
Parameters
----------
sock : socket
The connected socket with which to recv and send data
data : str
The data received
addr : tuple
The host and port of the remote peer
| HandleUdp | python | mandiant/flare-fakenet-ng | fakenet/configs/CustomProviderExample.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/configs/CustomProviderExample.py | Apache-2.0 |
def first_packet_new_session(self):
"""Is this the first datagram from this conversation?
Returns:
True if this pair of endpoints hasn't conversed before, else False
"""
# sessions.get returns (dst_ip, dport, pid, comm, dport0, proto) or
# None. We just want dst_ip a... | Is this the first datagram from this conversation?
Returns:
True if this pair of endpoints hasn't conversed before, else False
| first_packet_new_session | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def _validateBlackWhite(self):
"""Validate that only a black or a white list of either type (host or
process) is configured.
Side-effect:
Raises ListenerBlackWhiteList if invalid
"""
msg = None
fmt = 'Cannot specify both %s blacklist and whitelist for port %d... | Validate that only a black or a white list of either type (host or
process) is configured.
Side-effect:
Raises ListenerBlackWhiteList if invalid
| _validateBlackWhite | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def addListener(self, listener):
"""Add a ListenerMeta under the corresponding protocol and port."""
proto = listener.proto
port = listener.port
if not proto in self.protos:
self.protos[proto] = {}
if port in self.protos[proto]:
raise ListenerAlreadyBoun... | Add a ListenerMeta under the corresponding protocol and port. | addListener | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
def isHidden(self, proto, port):
"""Is this port associated with a listener that is hidden?"""
listener = self.getListenerMeta(proto, port)
return listener.hidden if listener else False | Is this port associated with a listener that is hidden? | isHidden | python | mandiant/flare-fakenet-ng | fakenet/diverters/diverterbase.py | https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.