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 test_load_and_run_multi_agent_a2a_sync(agent_framework: AgentFramework) -> None: """Tests that an agent contacts another using A2A using the sync adapter tool. Note that there is an issue when using Google ADK: https://github.com/google/adk-python/pull/566 """ if agent_framework in [ # asyn...
Tests that an agent contacts another using A2A using the sync adapter tool. Note that there is an issue when using Google ADK: https://github.com/google/adk-python/pull/566
test_load_and_run_multi_agent_a2a_sync
python
mozilla-ai/any-agent
tests/integration/test_load_and_run_multi_agent_a2a_tool.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/integration/test_load_and_run_multi_agent_a2a_tool.py
Apache-2.0
async def test_agent_serving_and_communication(test_port): """This test can be refactored to remove the need for multiproc, once we have support for control of the uvicorn server.""" # Start the agent in a subprocess proc = multiprocessing.Process(target=run_agent, args=(test_port,), daemon=True) proc.s...
This test can be refactored to remove the need for multiproc, once we have support for control of the uvicorn server.
test_agent_serving_and_communication
python
mozilla-ai/any-agent
tests/integration/test_serve_agent.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/integration/test_serve_agent.py
Apache-2.0
def test_evaluate_runs_all_evaluators( evaluation_case: EvaluationCase, agent_trace: AgentTrace ) -> None: """This unit test checks that all evaluators are called when evaluating a trace.""" #### Set up the mocks for the evaluators so that we don't actually call LLMs. mock_checkpoint_evaluate = MagicMoc...
This unit test checks that all evaluators are called when evaluating a trace.
test_evaluate_runs_all_evaluators
python
mozilla-ai/any-agent
tests/unit/evaluation/test_evaluate.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/evaluation/test_evaluate.py
Apache-2.0
def test_evaluate_when_no_final_output( evaluation_case: EvaluationCase, agent_trace: AgentTrace ) -> None: """This unit test checks that the hypothesis and qa evaluators are not called when there is no final output.""" #### Set up the mocks for the evaluators so that we don't actually call LLMs. mock_c...
This unit test checks that the hypothesis and qa evaluators are not called when there is no final output.
test_evaluate_when_no_final_output
python
mozilla-ai/any-agent
tests/unit/evaluation/test_evaluate.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/evaluation/test_evaluate.py
Apache-2.0
def test_trace_evaluation_result_score_calculation(agent_trace: AgentTrace) -> None: """Test that the score property of TraceEvaluationResult correctly calculates the ratio of passed points to total points.""" # Create evaluation results with different point values and pass status checkpoint_results = [ ...
Test that the score property of TraceEvaluationResult correctly calculates the ratio of passed points to total points.
test_trace_evaluation_result_score_calculation
python
mozilla-ai/any-agent
tests/unit/evaluation/test_evaluate.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/evaluation/test_evaluate.py
Apache-2.0
def create_agent_with_model_args(framework: AgentFramework) -> AnyAgent: """Helper function to create an agent with test model arguments""" return AnyAgent.create( framework, AgentConfig( model_id="gpt-4o", model_args={ "temperature": TEST_TEMPERATURE, ...
Helper function to create an agent with test model arguments
create_agent_with_model_args
python
mozilla-ai/any-agent
tests/unit/frameworks/test_any_agent.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/frameworks/test_any_agent.py
Apache-2.0
def test_get_agent_card_with_explicit_skills(agent_framework: AgentFramework) -> None: """Test that when skills are explicitly provided in A2AServingConfig, they are used instead of inferring from tools.""" agent = MagicMock() agent.config = AgentConfig(model_id="foo", description="test agent") agent.fr...
Test that when skills are explicitly provided in A2AServingConfig, they are used instead of inferring from tools.
test_get_agent_card_with_explicit_skills
python
mozilla-ai/any-agent
tests/unit/serving/test_agent_card.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/serving/test_agent_card.py
Apache-2.0
def test_bad_functions(agent_framework: AgentFramework) -> None: """Test the verify_callable function with various bad functions.""" # Test missing return type def missing_return_type(foo: str): # type: ignore[no-untyped-def] """Docstring for foo.""" return foo with pytest.raises(Valu...
Test the verify_callable function with various bad functions.
test_bad_functions
python
mozilla-ai/any-agent
tests/unit/tools/test_unit_wrappers.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tools/test_unit_wrappers.py
Apache-2.0
async def test_agno_client_session_timeout_passed(): """Test that client_session_timeout_seconds parameter is properly passed to AgnoMCPTools (STDIO only).""" custom_timeout = 15 stdio_params = MCPStdio( command="echo", args=["test"], client_session_timeout_seconds=custom_timeout, ...
Test that client_session_timeout_seconds parameter is properly passed to AgnoMCPTools (STDIO only).
test_agno_client_session_timeout_passed
python
mozilla-ai/any-agent
tests/unit/tools/mcp/test_unit_agno_mcp.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tools/mcp/test_unit_agno_mcp.py
Apache-2.0
async def test_langchain_client_session_timeout_passed(): """Test that client_session_timeout_seconds parameter is properly passed to LangChain ClientSession (STDIO and SSE).""" custom_timeout = 15.0 stdio_params = MCPStdio( command="echo", args=["test"], client_session_timeout_secon...
Test that client_session_timeout_seconds parameter is properly passed to LangChain ClientSession (STDIO and SSE).
test_langchain_client_session_timeout_passed
python
mozilla-ai/any-agent
tests/unit/tools/mcp/test_unit_langchain_mcp.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tools/mcp/test_unit_langchain_mcp.py
Apache-2.0
async def test_llamaindex_client_session_timeout_passed(): """Test that client_session_timeout_seconds parameter is properly passed to LlamaIndex BasicMCPClient (STDIO only).""" custom_timeout = 15.0 stdio_params = MCPStdio( command="echo", args=["test"], client_session_timeout_secon...
Test that client_session_timeout_seconds parameter is properly passed to LlamaIndex BasicMCPClient (STDIO only).
test_llamaindex_client_session_timeout_passed
python
mozilla-ai/any-agent
tests/unit/tools/mcp/test_unit_llama_index_mcp.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tools/mcp/test_unit_llama_index_mcp.py
Apache-2.0
def test_openai_mcpsse( mcp_sse_params_no_tools: MCPSse, ) -> None: """This is a test kept for legacy purposes.""" agent_config = AgentConfig(model_id="gpt-4o", tools=[mcp_sse_params_no_tools]) agent = AnyAgent.create("openai", agent_config) servers = agent._mcp_servers assert servers ser...
This is a test kept for legacy purposes.
test_openai_mcpsse
python
mozilla-ai/any-agent
tests/unit/tools/mcp/test_unit_openai_mcp.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tools/mcp/test_unit_openai_mcp.py
Apache-2.0
def test_openai_client_session_timeout_passed(): """Test that client_session_timeout_seconds parameter is properly passed to OpenAI MCPServerStdio and MCPServerSse.""" custom_timeout = 15.0 stdio_params = MCPStdio( command="echo", args=["test"], client_session_timeout_seconds=custom_...
Test that client_session_timeout_seconds parameter is properly passed to OpenAI MCPServerStdio and MCPServerSse.
test_openai_client_session_timeout_passed
python
mozilla-ai/any-agent
tests/unit/tools/mcp/test_unit_openai_mcp.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tools/mcp/test_unit_openai_mcp.py
Apache-2.0
def test_set_llm_input_missing_fields() -> None: """It should not fail when missing fields.""" span = MagicMock() _set_llm_input([Message(role="user")], span) span.set_attribute.assert_called_with( "gen_ai.input.messages", '[{"role": "user", "content": null}]' )
It should not fail when missing fields.
test_set_llm_input_missing_fields
python
mozilla-ai/any-agent
tests/unit/tracing/instrumentation/test_unit_agno_instrumentation.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tracing/instrumentation/test_unit_agno_instrumentation.py
Apache-2.0
def test_set_llm_output_missing_fields() -> None: """It should not fail when missing fields.""" span = MagicMock() _set_llm_output(Message(role="assistant"), span) span.set_attributes.assert_called_once_with( {"gen_ai.usage.input_tokens": 0, "gen_ai.usage.output_tokens": 0} )
It should not fail when missing fields.
test_set_llm_output_missing_fields
python
mozilla-ai/any-agent
tests/unit/tracing/instrumentation/test_unit_agno_instrumentation.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tracing/instrumentation/test_unit_agno_instrumentation.py
Apache-2.0
def test_set_llm_input_missing_fields() -> None: """It should not fail when missing fields.""" span = MagicMock() _set_llm_input(LlmRequest(), span) span.set_attribute.assert_not_called()
It should not fail when missing fields.
test_set_llm_input_missing_fields
python
mozilla-ai/any-agent
tests/unit/tracing/instrumentation/test_unit_google_instrumentation.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tracing/instrumentation/test_unit_google_instrumentation.py
Apache-2.0
def test_set_llm_output_missing_fields() -> None: """It should not fail when missing fields.""" span = MagicMock() _set_llm_output(LlmResponse(), span) span.set_attributes.assert_not_called()
It should not fail when missing fields.
test_set_llm_output_missing_fields
python
mozilla-ai/any-agent
tests/unit/tracing/instrumentation/test_unit_google_instrumentation.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tracing/instrumentation/test_unit_google_instrumentation.py
Apache-2.0
def test_set_llm_input_missing_fields() -> None: """It should not fail when missing fields.""" span = MagicMock() _set_llm_input([[BaseMessage(content="foo", type="human")]], span) span.set_attribute.assert_called_with( "gen_ai.input.messages", '[{"role": "user", "content": "foo"}]' )
It should not fail when missing fields.
test_set_llm_input_missing_fields
python
mozilla-ai/any-agent
tests/unit/tracing/instrumentation/test_unit_langchain_instrumentation.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tracing/instrumentation/test_unit_langchain_instrumentation.py
Apache-2.0
def test_set_llm_output_missing_fields() -> None: """It should not fail when missing fields.""" span = MagicMock() _set_llm_output(LLMResult(generations=[[Generation(text="")]]), span) span.set_attributes.assert_not_called()
It should not fail when missing fields.
test_set_llm_output_missing_fields
python
mozilla-ai/any-agent
tests/unit/tracing/instrumentation/test_unit_langchain_instrumentation.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tracing/instrumentation/test_unit_langchain_instrumentation.py
Apache-2.0
def test_set_llm_input_missing_fields() -> None: """It should not fail when missing fields.""" span = MagicMock() _set_llm_input([ChatMessage()], span) span.set_attribute.assert_called_with( "gen_ai.input.messages", '[{"role": "user", "content": "No content"}]' )
It should not fail when missing fields.
test_set_llm_input_missing_fields
python
mozilla-ai/any-agent
tests/unit/tracing/instrumentation/test_unit_llama_index_instrumentation.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tracing/instrumentation/test_unit_llama_index_instrumentation.py
Apache-2.0
def test_set_llm_output_missing_fields() -> None: """It should not fail when missing fields.""" span = MagicMock() _set_llm_output( AgentOutput( response=ChatMessage(), tool_calls=[], raw=None, current_agent_name="foo" ), span, ) span.set_attributes.assert_not_ca...
It should not fail when missing fields.
test_set_llm_output_missing_fields
python
mozilla-ai/any-agent
tests/unit/tracing/instrumentation/test_unit_llama_index_instrumentation.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tracing/instrumentation/test_unit_llama_index_instrumentation.py
Apache-2.0
def test_set_llm_input_missing_fields() -> None: """It should not fail when missing fields.""" span = MagicMock() _set_llm_input(GenerationSpanData(), span) span.set_attribute.assert_not_called()
It should not fail when missing fields.
test_set_llm_input_missing_fields
python
mozilla-ai/any-agent
tests/unit/tracing/instrumentation/test_unit_openai_instrumentation.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tracing/instrumentation/test_unit_openai_instrumentation.py
Apache-2.0
def test_set_llm_output_missing_fields() -> None: """It should not fail when missing fields.""" span = MagicMock() _set_llm_output(GenerationSpanData(), span) span.set_attributes.assert_not_called()
It should not fail when missing fields.
test_set_llm_output_missing_fields
python
mozilla-ai/any-agent
tests/unit/tracing/instrumentation/test_unit_openai_instrumentation.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tracing/instrumentation/test_unit_openai_instrumentation.py
Apache-2.0
def test_set_llm_input_missing_fields() -> None: """It should not fail when missing fields.""" span = MagicMock() _set_llm_input([], span) span.set_attribute.assert_not_called()
It should not fail when missing fields.
test_set_llm_input_missing_fields
python
mozilla-ai/any-agent
tests/unit/tracing/instrumentation/test_unit_smolagents_instrumentation.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tracing/instrumentation/test_unit_smolagents_instrumentation.py
Apache-2.0
def test_set_llm_output_missing_fields() -> None: """It should not fail when missing fields.""" span = MagicMock() _set_llm_output(ChatMessage("assistant"), span) span.set_attributes.assert_not_called()
It should not fail when missing fields.
test_set_llm_output_missing_fields
python
mozilla-ai/any-agent
tests/unit/tracing/instrumentation/test_unit_smolagents_instrumentation.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tracing/instrumentation/test_unit_smolagents_instrumentation.py
Apache-2.0
def experiment_setup(models: Sequence[ModelInfo], c_ref: int, batch_size: int): """Return information related to training `models` under compute budget `c_ref`.""" data = [] for m in models: c_self_per_token = m.self_attn_flops() d_iso = c_ref / c_self_per_token s_iso = num_traini...
Return information related to training `models` under compute budget `c_ref`.
experiment_setup
python
krasserm/perceiver-io
examples/scaling/clm/article.py
https://github.com/krasserm/perceiver-io/blob/master/examples/scaling/clm/article.py
Apache-2.0
def experiment_ratios(models: Sequence[ModelInfo]): """Return compute- and parameter-related ratios, independent of compute budget.""" data = [] for m in models: c_self_approx_per_token = m.self_attn_flops_approx() c_self_per_token = m.self_attn_flops() c_cross_per_token = m.cross_...
Return compute- and parameter-related ratios, independent of compute budget.
experiment_ratios
python
krasserm/perceiver-io
examples/scaling/clm/article.py
https://github.com/krasserm/perceiver-io/blob/master/examples/scaling/clm/article.py
Apache-2.0
def self_attn(self, num_channels, num_layers): """Self-attention FLOPs per latent token. Equivalent to a decoder-only transformer. :param num_channels: model dimension :param num_layers: number of self attention layers incl hybrid layer """ embed = self._input_embed(num...
Self-attention FLOPs per latent token. Equivalent to a decoder-only transformer. :param num_channels: model dimension :param num_layers: number of self attention layers incl hybrid layer
self_attn
python
krasserm/perceiver-io
examples/scaling/clm/scaling/flops.py
https://github.com/krasserm/perceiver-io/blob/master/examples/scaling/clm/scaling/flops.py
Apache-2.0
def cross_attn(self, num_channels, prefix_dropout=0.5): """Prefix cross-attention FLOPS per latent token. Perceiver AR extra compute compared to a decoder-only transformer. :param num_channels: model dimension :param prefix_dropout: dropout probability of prefix positions """ ...
Prefix cross-attention FLOPS per latent token. Perceiver AR extra compute compared to a decoder-only transformer. :param num_channels: model dimension :param prefix_dropout: dropout probability of prefix positions
cross_attn
python
krasserm/perceiver-io
examples/scaling/clm/scaling/flops.py
https://github.com/krasserm/perceiver-io/blob/master/examples/scaling/clm/scaling/flops.py
Apache-2.0
def _self_attn_layer(self, num_channels): """Self-attention FLOPs per latent token per layer.""" qkv = 6 * num_channels**2 attn = 2 * num_channels * self.num_latents out = 2 * num_channels**2 return qkv + attn + out
Self-attention FLOPs per latent token per layer.
_self_attn_layer
python
krasserm/perceiver-io
examples/scaling/clm/scaling/flops.py
https://github.com/krasserm/perceiver-io/blob/master/examples/scaling/clm/scaling/flops.py
Apache-2.0
def _cross_attn_layer(self, num_channels): """Cross-attention FLOPs per prefix token per layer.""" kv = 4 * num_channels**2 attn = 2 * num_channels * self.num_latents return kv + attn
Cross-attention FLOPs per prefix token per layer.
_cross_attn_layer
python
krasserm/perceiver-io
examples/scaling/clm/scaling/flops.py
https://github.com/krasserm/perceiver-io/blob/master/examples/scaling/clm/scaling/flops.py
Apache-2.0
def __init__(self, num_channels: int, num_layers: int, compute_estimator: ComputeEstimator): """... :param num_channels: model dimension. :param num_layers: number of self attention layers incl hybrid layer. """ self.num_channels = num_channels self.num_layers = num_laye...
... :param num_channels: model dimension. :param num_layers: number of self attention layers incl hybrid layer.
__init__
python
krasserm/perceiver-io
examples/scaling/clm/scaling/flops.py
https://github.com/krasserm/perceiver-io/blob/master/examples/scaling/clm/scaling/flops.py
Apache-2.0
def num_self_attn_params(self): """Parameter count of self-attention part. Equivalent to a decoder-only transformer. """ return num_self_attn_params( num_channels=self.num_channels, num_layers=self.num_layers, num_latents=self.num_latents, ...
Parameter count of self-attention part. Equivalent to a decoder-only transformer.
num_self_attn_params
python
krasserm/perceiver-io
examples/scaling/clm/scaling/flops.py
https://github.com/krasserm/perceiver-io/blob/master/examples/scaling/clm/scaling/flops.py
Apache-2.0
def num_cross_attn_params(self): """Parameter count of cross-attention part..""" # parameters for prefix position embedding return num_cross_attn_params(self.num_channels, self.num_prefix)
Parameter count of cross-attention part..
num_cross_attn_params
python
krasserm/perceiver-io
examples/scaling/clm/scaling/flops.py
https://github.com/krasserm/perceiver-io/blob/master/examples/scaling/clm/scaling/flops.py
Apache-2.0
def encode_midi_files(files: List[Path], num_workers: int) -> List[np.ndarray]: """Encode a list of midi files using multiple cpu workers.""" with Pool(processes=num_workers) as pool: res = list(tqdm(pool.imap(_encode_midi_file, files), total=len(files))) return [r for r in res if r is not None]
Encode a list of midi files using multiple cpu workers.
encode_midi_files
python
krasserm/perceiver-io
perceiver/data/audio/midi_processor.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/audio/midi_processor.py
Apache-2.0
def __init__( self, dataset_dir: str, max_seq_len: int, min_seq_len: Optional[int] = None, padding_side: str = "left", batch_size: int = 16, num_workers: int = 1, preproc_workers: Optional[int] = None, pin_memory: bool = True, ): """Bas...
Base class for data preprocessing and loading across different audio data sources using MIDI as the source data format. :param dataset_dir: Directory for storing the preprocessed dataset. :param max_seq_len: Maximum sequence length generated by this data module. :param min_seq_len: Mini...
__init__
python
krasserm/perceiver-io
perceiver/data/audio/symbolic.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/audio/symbolic.py
Apache-2.0
def mask_words(self, examples): """A modified version of whole word masking as described in https://huggingface.co/course/chapter7/3. The implementation in the linked document replaces words, randomly selected with `wwm_probability`, with mask tokens (one or more per word). The implementation h...
A modified version of whole word masking as described in https://huggingface.co/course/chapter7/3. The implementation in the linked document replaces words, randomly selected with `wwm_probability`, with mask tokens (one or more per word). The implementation here, however, only replaces 80% of selected...
mask_words
python
krasserm/perceiver-io
perceiver/data/text/collator.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/text/collator.py
Apache-2.0
def __init__( self, dataset_dir: str, tokenizer: str, max_seq_len: int, task: Task = Task.mlm, mask_prob: float = 0.15, mask_words: bool = True, static_masking: bool = False, add_special_tokens: bool = False, add_eos_token: bool = False, ...
Base class for consistent data preprocessing and loading across different text data sources. :param dataset_dir: Directory for storing the preprocessed dataset. :param tokenizer: Reference to a Hugging Face fast tokenizer (or the `deepmind/language-perceiver` tokenizer). :param max_seq_len: Max...
__init__
python
krasserm/perceiver-io
perceiver/data/text/common.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/text/common.py
Apache-2.0
def word_ids(self, token_ids): """Creates word ids from `token_ids`. Words boundaries are defined using whitespace boundaries. Whitespaces preceding a word have the same word id as the actual word following these whitespaces. Special tokens are assigned a `None` word id. Consecutive words do ...
Creates word ids from `token_ids`. Words boundaries are defined using whitespace boundaries. Whitespaces preceding a word have the same word id as the actual word following these whitespaces. Special tokens are assigned a `None` word id. Consecutive words do not necessarily have consecutive wor...
word_ids
python
krasserm/perceiver-io
perceiver/data/text/utils.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/text/utils.py
Apache-2.0
def _extract_image_patches(self, x: torch.Tensor, kernel: int, stride: int = 1, dilation: int = 1): """Equivalent to the implementation of https://www.tensorflow.org/api_docs/python/tf/image/extract_patches using "SAME" padding. From: https://discuss.pytorch.org/t/tf-extract-image-patches-in-py...
Equivalent to the implementation of https://www.tensorflow.org/api_docs/python/tf/image/extract_patches using "SAME" padding. From: https://discuss.pytorch.org/t/tf-extract-image-patches-in-pytorch/43837/9
_extract_image_patches
python
krasserm/perceiver-io
perceiver/data/vision/optical_flow.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/vision/optical_flow.py
Apache-2.0
def _pad(x: torch.Tensor, kernel: int, stride: int = 1, dilation: int = 1) -> torch.Tensor: """Applies a pad to the input using "SAME" strategy.""" *_, h, w = x.shape h2 = math.ceil(h / stride) w2 = math.ceil(w / stride) pad_row = (h2 - 1) * stride + (kernel - 1) * dilation + 1 -...
Applies a pad to the input using "SAME" strategy.
_pad
python
krasserm/perceiver-io
perceiver/data/vision/optical_flow.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/vision/optical_flow.py
Apache-2.0
def _compute_patch_grid_indices(self, img_shape: Tuple[int, ...]) -> List[Tuple[int, int]]: """From https://github.com/deepmind/deepmind-research/blob/master/perceiver/colabs/optical_flow.ipynb.""" ys = list(range(0, img_shape[0], self.patch_size[0] - self.patch_min_overlap)) xs = list(range(0, ...
From https://github.com/deepmind/deepmind-research/blob/master/perceiver/colabs/optical_flow.ipynb.
_compute_patch_grid_indices
python
krasserm/perceiver-io
perceiver/data/vision/optical_flow.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/vision/optical_flow.py
Apache-2.0
def preprocess( self, image_pair: Union[Tuple[np.ndarray, np.ndarray], Tuple[torch.Tensor, torch.Tensor]] ) -> torch.Tensor: """Creates the input features for the model for a pair of images. The input images are stacked and split into image patches of size `patch_size`. For each pixel of ea...
Creates the input features for the model for a pair of images. The input images are stacked and split into image patches of size `patch_size`. For each pixel of each individual patch, 3x3 patches are extracted and stacked in the channel dimension. Output shape: torch.Size(nr_patches, 2, 27, pa...
preprocess
python
krasserm/perceiver-io
perceiver/data/vision/optical_flow.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/vision/optical_flow.py
Apache-2.0
def preprocess_batch( self, image_pairs: Union[List[Tuple[np.ndarray, np.ndarray]], List[Tuple[torch.Tensor, torch.Tensor]]], ) -> torch.Tensor: """Creates the input features for the model for a batch of image pairs. For each image pair the images are stacked and split into image pa...
Creates the input features for the model for a batch of image pairs. For each image pair the images are stacked and split into image patches of size `patch_size`. For each pixel of each individual patch, 3x3 patches are extracted and stacked in the channel dimension. Output shape: torch.Size(b...
preprocess_batch
python
krasserm/perceiver-io
perceiver/data/vision/optical_flow.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/vision/optical_flow.py
Apache-2.0
def postprocess(self, predictions: torch.Tensor, img_shape: Tuple[int, ...]) -> torch.Tensor: """Combines optical flow predictions for individual image patches into a single prediction per image pair. Predictions can be supplied for a single image pair or a batch of image pairs, hence the supported inp...
Combines optical flow predictions for individual image patches into a single prediction per image pair. Predictions can be supplied for a single image pair or a batch of image pairs, hence the supported input shapes are: * (nr_patches, patch_size[0], patch_size[1], 2) and * (batch_size,...
postprocess
python
krasserm/perceiver-io
perceiver/data/vision/optical_flow.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/vision/optical_flow.py
Apache-2.0
def process( self, model, image_pairs: Union[List[Tuple[np.ndarray, np.ndarray]], List[Tuple[torch.Tensor, torch.Tensor]]], batch_size: int, ) -> torch.Tensor: """Combines preprocessing, inference and postprocessing steps for the optical flow. The input features for ...
Combines preprocessing, inference and postprocessing steps for the optical flow. The input features for model are created by stacking each image pair in the channel dimension and splitting the result into image patches of size `patch_size`. For each pixel in each individual patch, 3x3 patches a...
process
python
krasserm/perceiver-io
perceiver/data/vision/optical_flow.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/vision/optical_flow.py
Apache-2.0
def render_optical_flow(flow: np.ndarray) -> np.ndarray: """Renders optical flow predictions produced by an optical flow model.""" hsv = np.zeros((flow.shape[0], flow.shape[1], 3), dtype=np.uint8) mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1]) hsv[..., 0] = ang / np.pi / 2 * 180 hsv[..., 1...
Renders optical flow predictions produced by an optical flow model.
render_optical_flow
python
krasserm/perceiver-io
perceiver/data/vision/optical_flow.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/data/vision/optical_flow.py
Apache-2.0
def __init__(self, num_input_channels: int, *args, **kwargs): """Transforms and position-encodes task-specific input to generic encoder input. :param num_input_channels: Number of channels of the generic encoder input produced by this adapter. """ super().__init__() self._num_in...
Transforms and position-encodes task-specific input to generic encoder input. :param num_input_channels: Number of channels of the generic encoder input produced by this adapter.
__init__
python
krasserm/perceiver-io
perceiver/model/core/adapter.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/adapter.py
Apache-2.0
def __init__(self, rotated_channels_per_head: int, *args, **kwargs): """An input adapter mixin that additionally generates a frequency position encoding for input sequence `x`.""" super().__init__(*args, **kwargs) self.frq_pos_encoding = FrequencyPositionEncoding(dim=rotated_channels_per...
An input adapter mixin that additionally generates a frequency position encoding for input sequence `x`.
__init__
python
krasserm/perceiver-io
perceiver/model/core/adapter.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/adapter.py
Apache-2.0
def generate( self, inputs: Optional[torch.Tensor] = None, input_ids: Optional[torch.Tensor] = None, num_latents: int = 1, **kwargs, ): """Augments `GenerationMixin.generate` to support a `num_latents` argument. This argument determines the initial number of ...
Augments `GenerationMixin.generate` to support a `num_latents` argument. This argument determines the initial number of latents positions assigned to the end of a prompt. During generation, first, the number of latent positions grows until `self.backend_model.max_latents` is reached, then the p...
generate
python
krasserm/perceiver-io
perceiver/model/core/huggingface.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/huggingface.py
Apache-2.0
def __init__( self, num_heads: int, num_q_input_channels: int, num_kv_input_channels: int, num_qk_channels: Optional[int] = None, num_v_channels: Optional[int] = None, num_output_channels: Optional[int] = None, max_heads_parallel: Optional[int] = None, ...
Multi-head attention as specified in https://arxiv.org/abs/2107.14795 Appendix E plus support for rotary position embeddings (https://arxiv.org/abs/2104.09864) and causal attention. Causal attention requires queries and keys to be right-aligned, if they have different length. :param num_heads: ...
__init__
python
krasserm/perceiver-io
perceiver/model/core/modules.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/modules.py
Apache-2.0
def forward( self, x_q: torch.Tensor, x_kv: torch.Tensor, pad_mask: Optional[torch.Tensor] = None, rot_pos_emb_q: Optional[RotaryPositionEmbedding] = None, rot_pos_emb_k: Optional[RotaryPositionEmbedding] = None, kv_cache: Optional[KVCache] = None, ): ...
... :param x_q: Query input of shape (B, N, D) where B is the batch size, N the query sequence length and D the number of query input channels (= `num_q_input_channels`) :param x_kv: Key/value input of shape (B, L, C) where B is the batch size, L the key/value sequence length and C ...
forward
python
krasserm/perceiver-io
perceiver/model/core/modules.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/modules.py
Apache-2.0
def __init__( self, num_heads: int, num_q_input_channels: int, num_kv_input_channels: int, num_qk_channels: Optional[int] = None, num_v_channels: Optional[int] = None, max_heads_parallel: Optional[int] = None, causal_attention: bool = False, dropou...
Pre-layer-norm cross-attention (see `MultiHeadAttention` for attention details).
__init__
python
krasserm/perceiver-io
perceiver/model/core/modules.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/modules.py
Apache-2.0
def forward( self, x_q: torch.Tensor, x_kv: Optional[torch.Tensor] = None, x_kv_prefix: Optional[torch.Tensor] = None, pad_mask: Optional[torch.Tensor] = None, rot_pos_emb_q: Optional[RotaryPositionEmbedding] = None, rot_pos_emb_k: Optional[RotaryPositionEmbedding...
Pre-layer-norm cross-attention of query input `x_q` to key/value input (`x_kv` or `x_kv_prefix`). If `x_kv_prefix` is defined, the entire key/value input is a concatenation of `x_kv_prefix` and `x_q` along the sequence dimension. In this case, the query attends to itself at the end of the key/value seq...
forward
python
krasserm/perceiver-io
perceiver/model/core/modules.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/modules.py
Apache-2.0
def __init__( self, num_heads: int, num_channels: int, num_qk_channels: Optional[int] = None, num_v_channels: Optional[int] = None, max_heads_parallel: Optional[int] = None, causal_attention: bool = False, dropout: float = 0.0, qkv_bias: bool = Tru...
Pre-layer norm self-attention (see `MultiHeadAttention` and for attention details).
__init__
python
krasserm/perceiver-io
perceiver/model/core/modules.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/modules.py
Apache-2.0
def forward( self, x: torch.Tensor, pad_mask: Optional[torch.Tensor] = None, rot_pos_emb: Optional[RotaryPositionEmbedding] = None, kv_cache: Optional[KVCache] = None, ): """Pre-layer-norm self-attention of input `x`.""" x = self.norm(x) return self.at...
Pre-layer-norm self-attention of input `x`.
forward
python
krasserm/perceiver-io
perceiver/model/core/modules.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/modules.py
Apache-2.0
def __init__( self, input_adapter: InputAdapter, num_latents: int, num_latent_channels: int, num_cross_attention_heads: int = 4, num_cross_attention_qk_channels: Optional[int] = None, num_cross_attention_v_channels: Optional[int] = None, num_cross_attentio...
Generic Perceiver IO encoder. :param input_adapter: Transforms and position-encodes task-specific input to generic encoder input of shape (B, M, C) where B is the batch size, M the input sequence length and C the number of key/value input channels. C is determined by the `num_in...
__init__
python
krasserm/perceiver-io
perceiver/model/core/modules.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/modules.py
Apache-2.0
def __init__( self, output_adapter: OutputAdapter, output_query_provider: QueryProvider, num_latent_channels: int, num_cross_attention_heads: int = 4, num_cross_attention_qk_channels: Optional[int] = None, num_cross_attention_v_channels: Optional[int] = None, ...
Generic Perceiver IO decoder. :param output_adapter: Transforms generic decoder cross-attention output of shape (B, O, F) to task-specific output. B is the batch size, O the output sequence length and F the number of cross-attention output channels. :param output_query_p...
__init__
python
krasserm/perceiver-io
perceiver/model/core/modules.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/modules.py
Apache-2.0
def __init__( self, input_adapter: RotarySupport, num_heads: int = 8, max_heads_parallel: Optional[int] = None, num_self_attention_layers: int = 6, num_self_attention_rotary_layers: int = 1, self_attention_widening_factor: int = 4, cross_attention_widening...
Implementation of Perceiver AR (https://arxiv.org/abs/2202.07765). :param input_adapter: Transforms an input sequence to generic Perceiver AR input. An input adapter may choose to add (absolute) position information to transformed inputs while `PerceiverAR` additionally computes a ...
__init__
python
krasserm/perceiver-io
perceiver/model/core/modules.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/modules.py
Apache-2.0
def _positions(self, v_min=-1.0, v_max=1.0): """Create evenly spaced position coordinates for self.spatial_shape with values in [v_min, v_max]. :param v_min: minimum coordinate value per dimension. :param v_max: maximum coordinate value per dimension. :return: position coordinates tenso...
Create evenly spaced position coordinates for self.spatial_shape with values in [v_min, v_max]. :param v_min: minimum coordinate value per dimension. :param v_max: maximum coordinate value per dimension. :return: position coordinates tensor of shape (*shape, len(shape)).
_positions
python
krasserm/perceiver-io
perceiver/model/core/position.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/position.py
Apache-2.0
def _position_encodings( self, p: torch.Tensor, max_frequencies: Optional[Tuple[int, ...]] = None, include_positions: bool = True ) -> torch.Tensor: """Fourier-encode positions p using self.num_bands frequency bands. :param p: positions of shape (*d, c) where c = len(d). :param max_...
Fourier-encode positions p using self.num_bands frequency bands. :param p: positions of shape (*d, c) where c = len(d). :param max_frequencies: maximum frequency for each dimension (1-tuple for sequences, 2-tuple for images, ...). If `None` values are derived from shape of p. :p...
_position_encodings
python
krasserm/perceiver-io
perceiver/model/core/position.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/core/position.py
Apache-2.0
def convert_checkpoint(save_dir, ckpt_url, tokenizer_name, id2label=None, label2id=None, **kwargs): """Convert a `LitTextClassifier` checkpoint to a persistent `PerceiverTextClassifier`.""" tokenizer = AutoTokenizer.from_pretrained(tokenizer_name, verbose=False) tokenizer.save_pretrained(save_dir, **kwargs...
Convert a `LitTextClassifier` checkpoint to a persistent `PerceiverTextClassifier`.
convert_checkpoint
python
krasserm/perceiver-io
perceiver/model/text/classifier/huggingface.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/text/classifier/huggingface.py
Apache-2.0
def convert_checkpoint(save_dir, ckpt_url, tokenizer_name, **kwargs): """Convert a `LitCausalLanguageModel` checkpoint to a persistent `PerceiverCausalLanguageModel`.""" tokenizer = AutoTokenizer.from_pretrained(tokenizer_name, padding_side="left", verbose=False) tokenizer.save_pretrained(save_dir, **kwarg...
Convert a `LitCausalLanguageModel` checkpoint to a persistent `PerceiverCausalLanguageModel`.
convert_checkpoint
python
krasserm/perceiver-io
perceiver/model/text/clm/huggingface.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/text/clm/huggingface.py
Apache-2.0
def convert_checkpoint(save_dir, ckpt_url, tokenizer_name, **kwargs): """Convert a `LitMaskedLanguageModel` checkpoint to a persistent `PerceiverMaskedLanguageModel`.""" tokenizer = AutoTokenizer.from_pretrained(tokenizer_name, verbose=False) tokenizer.save_pretrained(save_dir, **kwargs) model = Perce...
Convert a `LitMaskedLanguageModel` checkpoint to a persistent `PerceiverMaskedLanguageModel`.
convert_checkpoint
python
krasserm/perceiver-io
perceiver/model/text/mlm/huggingface.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/text/mlm/huggingface.py
Apache-2.0
def convert_model(save_dir, source_repo_id="deepmind/language-perceiver", **kwargs): """Convert a Hugging Face `PerceiverForMaskedLM` to a persistent `PerceiverMaskedLanguageModel`.""" src_model = transformers.PerceiverForMaskedLM.from_pretrained(source_repo_id) tgt_config = PerceiverMaskedLanguageModelCon...
Convert a Hugging Face `PerceiverForMaskedLM` to a persistent `PerceiverMaskedLanguageModel`.
convert_model
python
krasserm/perceiver-io
perceiver/model/text/mlm/huggingface.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/text/mlm/huggingface.py
Apache-2.0
def convert_config(config: transformers.PerceiverConfig) -> MaskedLanguageModelConfig: """Convert a Hugging Face `PerceiverConfig` to a `PerceiverMaskedLanguageModelConfig`.""" assert config.hidden_act == "gelu" assert config.tie_word_embeddings encoder_config = TextEncoderConfig( vocab_size=c...
Convert a Hugging Face `PerceiverConfig` to a `PerceiverMaskedLanguageModelConfig`.
convert_config
python
krasserm/perceiver-io
perceiver/model/text/mlm/huggingface.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/text/mlm/huggingface.py
Apache-2.0
def convert_checkpoint(save_dir, ckpt_url, image_processor, id2label=None, label2id=None, **kwargs): """Convert a `LitImageClassifier` checkpoint to a persistent `PerceiverImageClassifier`.""" image_processor.save_pretrained(save_dir, **kwargs) model = PerceiverImageClassifier.from_checkpoint(ckpt_url) ...
Convert a `LitImageClassifier` checkpoint to a persistent `PerceiverImageClassifier`.
convert_checkpoint
python
krasserm/perceiver-io
perceiver/model/vision/image_classifier/huggingface.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/vision/image_classifier/huggingface.py
Apache-2.0
def convert_config(config: transformers.PerceiverConfig) -> ImageClassifierConfig: """Convert a Hugging Face `PerceiverConfig` to a `PerceiverImageClassifierConfig`.""" assert config.hidden_act == "gelu" encoder_config = ImageEncoderConfig( image_shape=(224, 224, 3), num_frequency_bands=64...
Convert a Hugging Face `PerceiverConfig` to a `PerceiverImageClassifierConfig`.
convert_config
python
krasserm/perceiver-io
perceiver/model/vision/image_classifier/huggingface.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/vision/image_classifier/huggingface.py
Apache-2.0
def convert_model(save_dir, source_repo_id="deepmind/vision-perceiver-fourier", **kwargs): """Convert a Hugging Face `PerceiverForImageClassificationFourier` to a persistent `PerceiverImageClassifier`.""" src_model = transformers.PerceiverForImageClassificationFourier.from_pretrained(source_repo_id) tg...
Convert a Hugging Face `PerceiverForImageClassificationFourier` to a persistent `PerceiverImageClassifier`.
convert_model
python
krasserm/perceiver-io
perceiver/model/vision/image_classifier/huggingface.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/vision/image_classifier/huggingface.py
Apache-2.0
def convert_model(save_dir, source_repo_id="deepmind/optical-flow-perceiver", **kwargs): """Convert a Hugging Face `PerceiverForOpticalFlow` to a persistent `OpticalFlowPerceiver`.""" src_model = transformers.PerceiverForOpticalFlow.from_pretrained(source_repo_id) tgt_config = OpticalFlowPerceiverConfig(co...
Convert a Hugging Face `PerceiverForOpticalFlow` to a persistent `OpticalFlowPerceiver`.
convert_model
python
krasserm/perceiver-io
perceiver/model/vision/optical_flow/huggingface.py
https://github.com/krasserm/perceiver-io/blob/master/perceiver/model/vision/optical_flow/huggingface.py
Apache-2.0
def is_datetime_naive(dt): """ This method returns true if the datetime is naive else returns false """ if dt.tzinfo is None: return True else: return False
This method returns true if the datetime is naive else returns false
is_datetime_naive
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def _move_datetime(dt, direction, delta): """ Move datetime given delta by given direction """ if direction == 'next': dt = dt + delta elif direction == 'last': dt = dt - delta else: pass # raise some delorean error here return dt
Move datetime given delta by given direction
_move_datetime
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def move_datetime_month(dt, direction, num_shifts): """ Move datetime 1 month in the chosen direction. unit is a no-op, to keep the API the same as the day case """ delta = relativedelta(months=+num_shifts) return _move_datetime(dt, direction, delta)
Move datetime 1 month in the chosen direction. unit is a no-op, to keep the API the same as the day case
move_datetime_month
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def move_datetime_week(dt, direction, num_shifts): """ Move datetime 1 week in the chosen direction. unit is a no-op, to keep the API the same as the day case """ delta = relativedelta(weeks=+num_shifts) return _move_datetime(dt, direction, delta)
Move datetime 1 week in the chosen direction. unit is a no-op, to keep the API the same as the day case
move_datetime_week
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def move_datetime_year(dt, direction, num_shifts): """ Move datetime 1 year in the chosen direction. unit is a no-op, to keep the API the same as the day case """ delta = relativedelta(years=+num_shifts) return _move_datetime(dt, direction, delta)
Move datetime 1 year in the chosen direction. unit is a no-op, to keep the API the same as the day case
move_datetime_year
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def datetime_timezone(tz): """ This method given a timezone returns a localized datetime object. """ utc_datetime_naive = datetime.utcnow() # return a localized datetime to UTC utc_localized_datetime = localize(utc_datetime_naive, 'UTC') # normalize the datetime to given timezone normali...
This method given a timezone returns a localized datetime object.
datetime_timezone
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def localize(dt, tz): """ Given a naive datetime object this method will return a localized datetime object """ if not isinstance(tz, tzinfo): tz = pytz.timezone(tz) return tz.localize(dt)
Given a naive datetime object this method will return a localized datetime object
localize
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def normalize(dt, tz): """ Given a object with a timezone return a datetime object normalized to the proper timezone. This means take the give localized datetime and returns the datetime normalized to match the specified timezone. """ if not isinstance(tz, tzinfo): tz = pytz.timezon...
Given a object with a timezone return a datetime object normalized to the proper timezone. This means take the give localized datetime and returns the datetime normalized to match the specified timezone.
normalize
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def __getattr__(self, name): """ Implement __getattr__ to call `shift_date` function when function called does not exist """ func_parts = name.split('_') # is the func we are trying to call the right length? if len(func_parts) != 2: raise AttributeErro...
Implement __getattr__ to call `shift_date` function when function called does not exist
__getattr__
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def _shift_date(self, direction, unit, *args): """ Shift datetime in `direction` in _VALID_SHIFT_DIRECTIONS and by some unit in _VALID_SHIFTS and shift that amount by some multiple, defined by by args[0] if it exists """ this_module = sys.modules[__name__] num_sh...
Shift datetime in `direction` in _VALID_SHIFT_DIRECTIONS and by some unit in _VALID_SHIFTS and shift that amount by some multiple, defined by by args[0] if it exists
_shift_date
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def truncate(self, s): """ Truncate the delorian object to the nearest s (second, minute, hour, day, month, year) This is a destructive method, modifies the internal datetime object associated with the Delorean object. .. testsetup:: from datetime import da...
Truncate the delorian object to the nearest s (second, minute, hour, day, month, year) This is a destructive method, modifies the internal datetime object associated with the Delorean object. .. testsetup:: from datetime import datetime from delorean i...
truncate
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def shift(self, timezone): """ Shifts the timezone from the current timezone to the specified timezone associated with the Delorean object, modifying the Delorean object and returning the modified object. .. testsetup:: from datetime import datetime from delorea...
Shifts the timezone from the current timezone to the specified timezone associated with the Delorean object, modifying the Delorean object and returning the modified object. .. testsetup:: from datetime import datetime from delorean import Delorean .. doctest:...
shift
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def epoch(self): """ Returns the total seconds since epoch associated with the Delorean object. .. testsetup:: from datetime import datetime from delorean import Delorean .. doctest:: >>> d = Delorean(datetime(2015, 1, 1), timezone='US/Paci...
Returns the total seconds since epoch associated with the Delorean object. .. testsetup:: from datetime import datetime from delorean import Delorean .. doctest:: >>> d = Delorean(datetime(2015, 1, 1), timezone='US/Pacific') >>> d.epoc...
epoch
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def humanize(self): """ Humanize relative to now: .. testsetup:: from datetime import timedelta from delorean import Delorean .. doctest:: >>> past = Delorean.utcnow() - timedelta(hours=1) >>> past.humanize() 'an hour ago' ...
Humanize relative to now: .. testsetup:: from datetime import timedelta from delorean import Delorean .. doctest:: >>> past = Delorean.utcnow() - timedelta(hours=1) >>> past.humanize() 'an hour ago'
humanize
python
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/master/delorean/dates.py
MIT
def parse(datetime_str, timezone=None, isofirst=True, dayfirst=True, yearfirst=True): """ Parses a datetime string and returns a `Delorean` object. :param datetime_str: The string to be interpreted into a `Delorean` object. :param timezone: Pass this parameter and the returned Delorean object will be n...
Parses a datetime string and returns a `Delorean` object. :param datetime_str: The string to be interpreted into a `Delorean` object. :param timezone: Pass this parameter and the returned Delorean object will be normalized to this timezone. Any offsets passed as part of datetime_str will be ignore...
parse
python
myusuf3/delorean
delorean/interface.py
https://github.com/myusuf3/delorean/blob/master/delorean/interface.py
MIT
def stops(freq, interval=1, count=None, wkst=None, bysetpos=None, bymonth=None, bymonthday=None, byyearday=None, byeaster=None, byweekno=None, byweekday=None, byhour=None, byminute=None, bysecond=None, timezone='UTC', start=None, stop=None): """ This will create a list of delorean ...
This will create a list of delorean objects the apply to setting possed in.
stops
python
myusuf3/delorean
delorean/interface.py
https://github.com/myusuf3/delorean/blob/master/delorean/interface.py
MIT
def test_timezone_delorean_to_datetime_to_delorean_non_utc(self): """Test if when you create Delorean object from Delorean's datetime it still behaves the same """ d1 = delorean.Delorean(timezone='America/Chicago') d2 = delorean.Delorean(d1.datetime) # these deloreans sh...
Test if when you create Delorean object from Delorean's datetime it still behaves the same
test_timezone_delorean_to_datetime_to_delorean_non_utc
python
myusuf3/delorean
tests/delorean_tests.py
https://github.com/myusuf3/delorean/blob/master/tests/delorean_tests.py
MIT
def test_stops_bymonth(self): """Test if create stops, checks bymonth, bymonthday, count and start parameters work properly """ days = list(delorean.interface.stops( delorean.MONTHLY, bymonth=(1, 4, 7, 10), bymonthday=15, count=4, ...
Test if create stops, checks bymonth, bymonthday, count and start parameters work properly
test_stops_bymonth
python
myusuf3/delorean
tests/delorean_tests.py
https://github.com/myusuf3/delorean/blob/master/tests/delorean_tests.py
MIT
def create_table(): """ Creates the 'images' table in the SQLite database if it doesn't exist. """ with connection: connection.execute(''' CREATE TABLE IF NOT EXISTS images ( id INTEGER PRIMARY KEY, filename TEXT NOT NULL, file_path TEX...
Creates the 'images' table in the SQLite database if it doesn't exist.
create_table
python
harperreed/photo-similarity-search
generate_embeddings.py
https://github.com/harperreed/photo-similarity-search/blob/master/generate_embeddings.py
MIT
def file_generator(directory): """ Generates file paths for all files in the specified directory and its subdirectories. :param directory: The directory path to search for files. :return: A generator yielding file paths. """ logger.debug(f"Generating file paths for directory: {directory}") ...
Generates file paths for all files in the specified directory and its subdirectories. :param directory: The directory path to search for files. :return: A generator yielding file paths.
file_generator
python
harperreed/photo-similarity-search
generate_embeddings.py
https://github.com/harperreed/photo-similarity-search/blob/master/generate_embeddings.py
MIT
def hydrate_cache(directory, cache_file_path): """ Loads or generates a cache of file paths for the specified directory. :param directory: The directory path to search for files. :param cache_file_path: The path to the cache file. :return: A list of cached file paths. """ logger.info(f"Hydr...
Loads or generates a cache of file paths for the specified directory. :param directory: The directory path to search for files. :param cache_file_path: The path to the cache file. :return: A list of cached file paths.
hydrate_cache
python
harperreed/photo-similarity-search
generate_embeddings.py
https://github.com/harperreed/photo-similarity-search/blob/master/generate_embeddings.py
MIT
def update_db(image): """ Updates the database with the image embeddings. :param image: A dictionary containing image information. """ try: embeddings_blob = sqlite3.Binary(msgpack.dumps(image.get('embeddings', []))) with sqlite3.connect(SQLITE_DB_FILEPATH) as conn: conn...
Updates the database with the image embeddings. :param image: A dictionary containing image information.
update_db
python
harperreed/photo-similarity-search
generate_embeddings.py
https://github.com/harperreed/photo-similarity-search/blob/master/generate_embeddings.py
MIT
def process_image(file_path): """ Processes an image file by extracting metadata and inserting it into the database. :param file_path: The path to the image file. """ file = os.path.basename(file_path) file_date = time.ctime(os.path.getmtime(file_path)) with open(file_path, 'rb') as f: ...
Processes an image file by extracting metadata and inserting it into the database. :param file_path: The path to the image file.
process_image
python
harperreed/photo-similarity-search
generate_embeddings.py
https://github.com/harperreed/photo-similarity-search/blob/master/generate_embeddings.py
MIT
def process_embeddings(photo): """ Processes image embeddings by uploading them to the embedding server and updating the database. :param photo: A dictionary containing photo information. """ logger.debug(f"Processing photo: {photo['filename']}") if photo['embeddings']: logger.debug(f"P...
Processes image embeddings by uploading them to the embedding server and updating the database. :param photo: A dictionary containing photo information.
process_embeddings
python
harperreed/photo-similarity-search
generate_embeddings.py
https://github.com/harperreed/photo-similarity-search/blob/master/generate_embeddings.py
MIT
def main(): """ Main function to process images and embeddings. """ cache_start_time = time.time() cached_files = hydrate_cache(SOURCE_IMAGE_DIRECTORY, FILELIST_CACHE_FILEPATH) cache_end_time = time.time() logger.info(f"Cache operation took {cache_end_time - cache_start_time:.2f} seconds") ...
Main function to process images and embeddings.
main
python
harperreed/photo-similarity-search
generate_embeddings.py
https://github.com/harperreed/photo-similarity-search/blob/master/generate_embeddings.py
MIT
def serve_image(filename): """ Serve a resized image directly from the filesystem outside of the static directory. """ # Construct the full file path. Be careful with security implications. # Ensure that you validate `filename` to prevent directory traversal attacks. filepath = os.path.join(SO...
Serve a resized image directly from the filesystem outside of the static directory.
serve_image
python
harperreed/photo-similarity-search
start_web.py
https://github.com/harperreed/photo-similarity-search/blob/master/start_web.py
MIT
def cfg_from_file(filename): """Load a config file and merge it into the default options.""" import yaml with open(filename, 'r') as f: yaml_cfg = edict(yaml.load(f)) _merge_a_into_b(yaml_cfg, __C)
Load a config file and merge it into the default options.
cfg_from_file
python
sshaoshuai/PointRCNN
lib/config.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/config.py
MIT
def _merge_a_into_b(a, b): """Merge config dictionary a into config dictionary b, clobbering the options in b whenever they are also specified in a. """ if type(a) is not edict: return for k, v in a.items(): # a must specify keys that are in b if k not in b: rais...
Merge config dictionary a into config dictionary b, clobbering the options in b whenever they are also specified in a.
_merge_a_into_b
python
sshaoshuai/PointRCNN
lib/config.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/config.py
MIT
def cfg_from_list(cfg_list): """Set config keys via list (e.g., from command line).""" from ast import literal_eval assert len(cfg_list) % 2 == 0 for k, v in zip(cfg_list[0::2], cfg_list[1::2]): key_list = k.split('.') d = __C for subkey in key_list[:-1]: assert subke...
Set config keys via list (e.g., from command line).
cfg_from_list
python
sshaoshuai/PointRCNN
lib/config.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/config.py
MIT
def preprocess_rpn_training_data(self): """ Discard samples which don't have current classes, which will not be used for training. Valid sample_id is stored in self.sample_id_list """ self.logger.info('Loading %s samples from %s ...' % (self.mode, self.label_dir)) for idx...
Discard samples which don't have current classes, which will not be used for training. Valid sample_id is stored in self.sample_id_list
preprocess_rpn_training_data
python
sshaoshuai/PointRCNN
lib/datasets/kitti_rcnn_dataset.py
https://github.com/sshaoshuai/PointRCNN/blob/master/lib/datasets/kitti_rcnn_dataset.py
MIT