input
stringlengths
33
5k
output
stringlengths
32
5k
from enum import Enum # --8<-- [start:ProviderName] class ProviderName(str, Enum): AIML_API = "aiml_api" ANTHROPIC = "anthropic" APOLLO = "apollo" COMPASS = "compass" DISCORD = "discord" D_ID = "d_id" E2B = "e2b" EXA = "exa" FAL = "fal" GENERIC_WEBHOOK = "generic_webhook" G...
from enum import Enum # --8<-- [start:ProviderName] class ProviderName(str, Enum): AIML_API = "aiml_api" ANTHROPIC = "anthropic" APOLLO = "apollo" COMPASS = "compass" DISCORD = "discord" D_ID = "d_id" E2B = "e2b" EXA = "exa" FAL = "fal" GENERIC_WEBHOOK = "generic_webhook" G...
from __future__ import annotations __version__ = "3.5.0.dev0" __MODEL_HUB_ORGANIZATION__ = "sentence-transformers" import importlib import os from sentence_transformers.backend import ( export_dynamic_quantized_onnx_model, export_optimized_onnx_model, export_static_quantized_openvino_model, ) from senten...
from __future__ import annotations __version__ = "3.4.0.dev0" __MODEL_HUB_ORGANIZATION__ = "sentence-transformers" import importlib import os from sentence_transformers.backend import ( export_dynamic_quantized_onnx_model, export_optimized_onnx_model, export_static_quantized_openvino_model, ) from senten...
from docarray.typing.bytes import ImageBytes from docarray.typing.id import ID from docarray.typing.tensor import ImageNdArray, ImageTensor from docarray.typing.tensor.audio import AudioNdArray from docarray.typing.tensor.embedding.embedding import AnyEmbedding, NdArrayEmbedding from docarray.typing.tensor.ndarray impo...
from docarray.typing.bytes import ImageBytes from docarray.typing.id import ID from docarray.typing.tensor import ImageNdArray, ImageTensor from docarray.typing.tensor.audio import AudioNdArray from docarray.typing.tensor.embedding.embedding import AnyEmbedding, NdArrayEmbedding from docarray.typing.tensor.ndarray impo...
import itertools import numpy as np from keras.src import tree from keras.src.trainers.data_adapters import data_adapter_utils from keras.src.trainers.data_adapters.data_adapter import DataAdapter class TorchDataLoaderAdapter(DataAdapter): """Adapter that handles `torch.utils.data.DataLoader`.""" def __ini...
import itertools import numpy as np from keras.src import tree from keras.src.trainers.data_adapters import data_adapter_utils from keras.src.trainers.data_adapters.data_adapter import DataAdapter class TorchDataLoaderAdapter(DataAdapter): """Adapter that handles `torch.utils.data.DataLoader`.""" def __ini...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.ops.nn import average_pool from keras.src.ops.nn import batch_normalization from keras.src.ops.nn import binary_crossentropy from keras.src.ops.nn import categorical_crossentropy from...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.ops.nn import average_pool from keras.src.ops.nn import batch_normalization from keras.src.ops.nn import binary_crossentropy from keras.src.ops.nn import categorical_crossentropy from...
from typing import Any, Optional, Type, TypeVar, Union import numpy as np from docarray.base_document import BaseDocument from docarray.documents import Audio from docarray.typing import AnyEmbedding, AnyTensor from docarray.typing.tensor.abstract_tensor import AbstractTensor from docarray.typing.tensor.video.video_t...
from typing import Any, Optional, Type, TypeVar, Union import numpy as np from docarray.base_document import BaseDocument from docarray.documents import Audio from docarray.typing import AnyEmbedding, AnyTensor from docarray.typing.tensor.abstract_tensor import AbstractTensor from docarray.typing.tensor.video.video_t...
from docarray import DocumentArray from jina import Executor, requests class ProcessExecutor(Executor): @requests(on='/') def process(self, docs: DocumentArray, **kwargs): for doc in docs: doc.text = doc.text + 'world' doc.tags['processed'] = True def _validate_dummy_custom_...
def _validate_dummy_custom_gateway_response(port, expected): import requests resp = requests.get(f'http://127.0.0.1:{port}/').json() assert resp == expected def _validate_custom_gateway_process(port, text, expected): import requests resp = requests.get(f'http://127.0.0.1:{port}/stream?text={text...
from typing import Any, Optional, Type, TypeVar, Union from docarray.base_document import BaseDocument from docarray.typing import TextUrl from docarray.typing.tensor.embedding import AnyEmbedding T = TypeVar('T', bound='TextDoc') class TextDoc(BaseDocument): """ Document for handling text. It can conta...
from typing import Any, Optional, Type, TypeVar, Union from docarray.base_document import BaseDocument from docarray.typing import TextUrl from docarray.typing.tensor.embedding import AnyEmbedding T = TypeVar('T', bound='TextDoc') class TextDoc(BaseDocument): """ Document for handling text. It can conta...
from __future__ import annotations import logging import tqdm class LoggingHandler(logging.Handler): def __init__(self, level=logging.NOTSET) -> None: super().__init__(level) def emit(self, record) -> None: try: msg = self.format(record) tqdm.tqdm.write(msg) ...
import logging import tqdm class LoggingHandler(logging.Handler): def __init__(self, level=logging.NOTSET) -> None: super().__init__(level) def emit(self, record) -> None: try: msg = self.format(record) tqdm.tqdm.write(msg) self.flush() except (Key...
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
import re from langchain_core.output_parsers import BaseOutputParser class BooleanOutputParser(BaseOutputParser[bool]): """Parse the output of an LLM call to a boolean.""" true_val: str = "YES" """The string value that should be parsed as True.""" false_val: str = "NO" """The string value that s...
import re from langchain_core.output_parsers import BaseOutputParser class BooleanOutputParser(BaseOutputParser[bool]): """Parse the output of an LLM call to a boolean.""" true_val: str = "YES" """The string value that should be parsed as True.""" false_val: str = "NO" """The string value that s...
from docarray import Document, DocumentArray import numpy as np import pytest @pytest.mark.filterwarnings('ignore::UserWarning') def test_add_ignore_existing_doc_id(start_storage): elastic_doc = DocumentArray( storage='elasticsearch', config={ 'n_dim': 3, 'columns': [('pri...
from docarray import Document, DocumentArray import pytest @pytest.mark.filterwarnings('ignore::UserWarning') def test_add_ignore_existing_doc_id(start_storage): elastic_doc = DocumentArray( storage='elasticsearch', config={ 'n_dim': 3, 'columns': [('price', 'int')], ...
"""Load agent.""" from collections.abc import Sequence from typing import Any, Optional from langchain_core._api import deprecated from langchain_core.callbacks import BaseCallbackManager from langchain_core.language_models import BaseLanguageModel from langchain_core.tools import BaseTool from langchain._api.deprec...
"""Load agent.""" from typing import Any, Optional, Sequence from langchain_core._api import deprecated from langchain_core.callbacks import BaseCallbackManager from langchain_core.language_models import BaseLanguageModel from langchain_core.tools import BaseTool from langchain._api.deprecation import AGENT_DEPRECAT...
""" This examples demonstrates the setup for Question-Answer-Retrieval. You can input a query or a question. The script then uses semantic search to find relevant passages in Simple English Wikipedia (as it is smaller and fits better in RAM). As model, we use: nq-distilbert-base-v1 It was trained on the Natural Ques...
""" This examples demonstrates the setup for Question-Answer-Retrieval. You can input a query or a question. The script then uses semantic search to find relevant passages in Simple English Wikipedia (as it is smaller and fits better in RAM). As model, we use: nq-distilbert-base-v1 It was trained on the Natural Ques...
from __future__ import annotations import json import os import torch from safetensors.torch import load_model as load_safetensors_model from safetensors.torch import save_model as save_safetensors_model from torch import nn class CNN(nn.Module): """CNN-layer with multiple kernel-sizes over the word embeddings"...
import json import os from typing import List import torch from safetensors.torch import load_model as load_safetensors_model from safetensors.torch import save_model as save_safetensors_model from torch import nn class CNN(nn.Module): """CNN-layer with multiple kernel-sizes over the word embeddings""" def ...
"""Utilities for the XGBoost Dask interface.""" import logging import warnings from typing import Any, Dict, Optional, Tuple import distributed from ..collective import Config LOGGER = logging.getLogger("[xgboost.dask]") def get_n_threads(local_param: Dict[str, Any], worker: "distributed.Worker") -> int: """G...
"""Utilities for the XGBoost Dask interface.""" import logging from typing import TYPE_CHECKING, Any, Dict LOGGER = logging.getLogger("[xgboost.dask]") if TYPE_CHECKING: import distributed def get_n_threads(local_param: Dict[str, Any], worker: "distributed.Worker") -> int: """Get the number of threads fro...
# dataset settings dataset_type = 'VOCDataset' data_root = 'data/VOCdevkit/' # Example to use different file client # Method 1: simply set the data root and let the file I/O module # automatically Infer from prefix (not support LMDB and Memcache yet) # data_root = 's3://openmmlab/datasets/detection/segmentation/VOCde...
# dataset settings dataset_type = 'VOCDataset' data_root = 'data/VOCdevkit/' # file_client_args = dict( # backend='petrel', # path_mapping=dict({ # './data/': 's3://openmmlab/datasets/detection/', # 'data/': 's3://openmmlab/datasets/detection/' # })) file_client_args = dict(backend='disk') ...
from __future__ import annotations from typing import Any, Optional, Union import PIL.Image import torch from ._datapoint import Datapoint class Image(Datapoint): """[BETA] :class:`torch.Tensor` subclass for images. Args: data (tensor-like, PIL.Image.Image): Any data that can be turned into a tens...
from __future__ import annotations from typing import Any, Optional, Union import PIL.Image import torch from ._datapoint import Datapoint class Image(Datapoint): """[BETA] :class:`torch.Tensor` subclass for images. Args: data (tensor-like, PIL.Image.Image): Any data that can be turned into a tens...
from __future__ import annotations from sentence_transformers.sparse_encoder.callbacks.splade_callbacks import ( SchedulerType, SpladeLambdaSchedulerCallback, ) from sentence_transformers.sparse_encoder.data_collator import SparseEncoderDataCollator from sentence_transformers.sparse_encoder.evaluation import (...
from __future__ import annotations from sentence_transformers.sparse_encoder.data_collator import SparseEncoderDataCollator from sentence_transformers.sparse_encoder.evaluation import ( SparseBinaryClassificationEvaluator, SparseEmbeddingSimilarityEvaluator, SparseInformationRetrievalEvaluator, SparseM...
import numpy as np from absl.testing import parameterized from keras.src import backend from keras.src import dtype_policies from keras.src import layers from keras.src import testing class ZeroPadding3DTest(testing.TestCase, parameterized.TestCase): @parameterized.parameters( {"data_format": "channels_f...
import numpy as np from absl.testing import parameterized from keras.src import backend from keras.src import layers from keras.src import testing class ZeroPadding3DTest(testing.TestCase, parameterized.TestCase): @parameterized.parameters( {"data_format": "channels_first"}, {"data_format": "channels_las...
"""Google Universal Sentence Encoder Embedding Wrapper Module.""" import deprecated from typing import Any, List, Optional from llama_index.core.base.embeddings.base import ( DEFAULT_EMBED_BATCH_SIZE, BaseEmbedding, ) from llama_index.core.bridge.pydantic import PrivateAttr from llama_index.core.callbacks imp...
"""Google Universal Sentence Encoder Embedding Wrapper Module.""" from typing import Any, List, Optional from llama_index.core.base.embeddings.base import ( DEFAULT_EMBED_BATCH_SIZE, BaseEmbedding, ) from llama_index.core.bridge.pydantic import PrivateAttr from llama_index.core.callbacks import CallbackManage...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.document_loaders.parsers.generic import MimeTypeBasedParser # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # hand...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.document_loaders.parsers.generic import MimeTypeBasedParser # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # hand...
from typing import Union from docarray.typing.tensor.image.image_ndarray import ImageNdArray from docarray.utils.misc import is_tf_available, is_torch_available torch_available = is_torch_available() if torch_available: from docarray.typing.tensor.image.image_torch_tensor import ImageTorchTensor tf_available = ...
from typing import Union from docarray.typing.tensor.image.image_ndarray import ImageNdArray try: import torch # noqa: F401 except ImportError: ImageTensor = ImageNdArray else: from docarray.typing.tensor.image.image_torch_tensor import ImageTorchTensor ImageTensor = Union[ImageNdArray, ImageTorchT...
"""LLM Prompt Program.""" from abc import abstractmethod from typing import Any, Generic, Optional, Type, TypeVar from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.prompts.base import PromptTemplate from llama_index.core.types import BasePydanticProgram, Model LM = TypeVar("LM") class Ba...
"""LLM Prompt Program.""" from abc import abstractmethod from typing import Any, Generic, Optional, Type, TypeVar from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.prompts.base import PromptTemplate from llama_index.core.types import BasePydanticProgram, Model LM = TypeVar("LM") class Bas...
_base_ = './rpn_r50-caffe_fpn_1x_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://detectron2/resnet101_caffe')))
_base_ = './rpn_r50_caffe_fpn_1x_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://detectron2/resnet101_caffe')))
_base_ = './panoptic-fpn_r50_fpn_1x_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
_base_ = './panoptic_fpn_r50_fpn_1x_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
from __future__ import annotations import inspect from typing import Any, Union import torch try: import triton except ImportError: triton = None if triton is not None: import triton.language as tl from triton import Config from triton.compiler import CompiledKernel from triton.runtime.aut...
from __future__ import annotations import inspect from typing import Any, Union import torch try: import triton except ImportError: triton = None if triton is not None: import triton.language as tl from triton import Config from triton.compiler import CompiledKernel from triton.runtime.aut...
from __future__ import annotations from .BinaryCrossEntropyLoss import BinaryCrossEntropyLoss from .CachedMultipleNegativesRankingLoss import CachedMultipleNegativesRankingLoss from .CrossEntropyLoss import CrossEntropyLoss from .LambdaLoss import ( LambdaLoss, LambdaRankScheme, NDCGLoss1Scheme, NDCGLo...
from __future__ import annotations from .BinaryCrossEntropyLoss import BinaryCrossEntropyLoss from .CachedMultipleNegativesRankingLoss import CachedMultipleNegativesRankingLoss from .CrossEntropyLoss import CrossEntropyLoss from .MarginMSELoss import MarginMSELoss from .MSELoss import MSELoss from .MultipleNegativesRa...
_base_ = './retinanet_r50_fpn_1x_coco.py' model = dict( data_preprocessor=dict( type='DetDataPreprocessor', # use caffe img_norm mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], bgr_to_rgb=False, pad_size_divisor=32), backbone=dict( norm_cfg=dict(req...
_base_ = './retinanet_r50_fpn_1x_coco.py' # use caffe img_norm preprocess_cfg = dict( mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False, pad_size_divisor=32) model = dict( preprocess_cfg=preprocess_cfg, backbone=dict( norm_cfg=dict(requires_grad=False), norm_ev...
from enum import Enum from fsspec import AbstractFileSystem from pathlib import Path from typing import Any, Dict, Iterable, Optional, Protocol, runtime_checkable import json import uuid from docling.document_converter import DocumentConverter from docling_core.types import DoclingDocument as DLDocument from llama_ind...
from enum import Enum from fsspec import AbstractFileSystem from pathlib import Path from typing import Any, Dict, Iterable, Optional, Protocol, runtime_checkable import json import uuid from docling.document_converter import DocumentConverter from docling_core.types import DoclingDocument as DLDocument from llama_ind...
# mypy: allow-untyped-defs import torch._C._lazy def reset(): """Resets all metric counters.""" torch._C._lazy._reset_metrics() def counter_names(): """Retrieves all the currently active counter names.""" return torch._C._lazy._counter_names() def counter_value(name: str): """Return the value ...
# mypy: allow-untyped-defs import torch._C._lazy def reset(): """Resets all metric counters.""" torch._C._lazy._reset_metrics() def counter_names(): """Retrieves all the currently active counter names.""" return torch._C._lazy._counter_names() def counter_value(name: str): """Return the value ...
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from typing import Dict, Iterable, List, Optional, Tuple import numpy as np import torch import torchvision.transforms as T from jina import DocumentArray, Executor, requests from jina.logging.logger import JinaLogge...
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from typing import Optional, List, Dict, Iterable, Tuple import numpy as np import torchvision.transforms as T import torch from jina import Executor, requests, DocumentArray from jina_commons.batching import get_d...
import os from typing import Any, List, Optional from llama_index.core.bridge.pydantic import Field, PrivateAttr from llama_index.core.callbacks import CBEventType, EventPayload from llama_index.core.instrumentation import get_dispatcher from llama_index.core.instrumentation.events.rerank import ( ReRankEndEvent, ...
import os from typing import Any, List, Optional from llama_index.core.bridge.pydantic import Field, PrivateAttr from llama_index.core.callbacks import CBEventType, EventPayload from llama_index.core.instrumentation import get_dispatcher from llama_index.core.instrumentation.events.rerank import ( ReRankEndEvent, ...
# Licensed to the LF AI & Data foundation under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the "License"); # you may not use this fil...
import numpy as np from docarray import BaseDoc, DocList from docarray.index import InMemoryExactNNIndex from docarray.typing import NdArray class SimpleDoc(BaseDoc): embedding: NdArray[128] text: str def test_update_payload(): docs = DocList[SimpleDoc]( [SimpleDoc(embedding=np.random.rand(128)...
from abc import abstractmethod from typing import Iterable, Iterator from qdrant_client import QdrantClient from qdrant_client.http.exceptions import UnexpectedResponse from qdrant_client.http.models.models import ( PointIdsList, PointsList, ScrollRequest, PointStruct, ) from docarray import Document ...
from abc import abstractmethod from typing import Iterable, Iterator from qdrant_client import QdrantClient from qdrant_client.http.exceptions import UnexpectedResponse from qdrant_client.http.models.models import ( PointIdsList, PointsList, ScrollRequest, PointStruct, ) from docarray import Document ...
import numpy as np import pytest from tensorflow import data as tf_data from keras.src import backend from keras.src import layers from keras.src import testing from keras.src.ops import convert_to_tensor class StringLookupTest(testing.TestCase): # TODO: increase coverage. Most features aren't being tested. ...
import numpy as np import pytest from tensorflow import data as tf_data from keras.src import backend from keras.src import layers from keras.src import testing class StringLookupTest(testing.TestCase): # TODO: increase coverage. Most features aren't being tested. def test_config(self): layer = laye...
import textwrap import pyarrow as pa import pytest from datasets import Features, Value from datasets.packaged_modules.json.json import Json @pytest.fixture def jsonl_file(tmp_path): filename = tmp_path / "file.jsonl" data = textwrap.dedent( """\ {"col_1": -1} {"col_1": 1, "col_2": 2...
import textwrap import pyarrow as pa import pytest from datasets import Features, Value from datasets.packaged_modules.json.json import Json @pytest.fixture def jsonl_file(tmp_path): filename = tmp_path / "file.jsonl" data = textwrap.dedent( """\ {"col_1": 1, "col_2": 2} {"col_1": 10...
# Copyright (c) OpenMMLab. All rights reserved. from .activations import SiLU from .bbox_nms import fast_nms, multiclass_nms from .brick_wrappers import AdaptiveAvgPool2d, adaptive_avg_pool2d from .conv_upsample import ConvUpsample from .csp_layer import CSPLayer from .dropblock import DropBlock from .ema import ExpMom...
# Copyright (c) OpenMMLab. All rights reserved. from .activations import SiLU from .bbox_nms import fast_nms, multiclass_nms from .brick_wrappers import AdaptiveAvgPool2d, adaptive_avg_pool2d from .conv_upsample import ConvUpsample from .csp_layer import CSPLayer from .dropblock import DropBlock from .ema import ExpMom...
__version__ = '0.1.0' from docarray.array import DocumentArray from docarray.document.document import BaseDocument as Document from docarray.predefined_document import Image, Mesh3D, PointCloud3D, Text __all__ = ['Document', 'DocumentArray', 'Image', 'Text', 'Mesh3D', 'PointCloud3D']
__version__ = '0.1.0' from docarray.array import DocumentArray from docarray.document.document import BaseDocument as Document from docarray.predefined_document import Image, Text __all__ = ['Document', 'DocumentArray', 'Image', 'Text']
import re from typing import Union from langchain_core.agents import AgentAction, AgentFinish from langchain_core.exceptions import OutputParserException from langchain.agents.agent import AgentOutputParser from langchain.agents.conversational.prompt import FORMAT_INSTRUCTIONS class ConvoOutputParser(AgentOutputPar...
import re from typing import Union from langchain_core.agents import AgentAction, AgentFinish from langchain_core.exceptions import OutputParserException from langchain.agents.agent import AgentOutputParser from langchain.agents.conversational.prompt import FORMAT_INSTRUCTIONS class ConvoOutputParser(AgentOutputPar...
import torch _TORCHFUNCTION_SUBCLASS = False class _ReturnTypeCM: def __init__(self, to_restore): self.to_restore = to_restore def __enter__(self): return self def __exit__(self, *args): global _TORCHFUNCTION_SUBCLASS _TORCHFUNCTION_SUBCLASS = self.to_restore def set_r...
import torch _TORCHFUNCTION_SUBCLASS = False class _ReturnTypeCM: def __init__(self, to_restore): self.to_restore = to_restore def __enter__(self): return self def __exit__(self, *args): global _TORCHFUNCTION_SUBCLASS _TORCHFUNCTION_SUBCLASS = self.to_restore def set_r...
from ._hubert_datamodule import HuBERTDataModule __all__ = [ "HuBERTDataModule", "Wav2Vec2DataModule", ]
from ._hubert_datamodule import HuBERTDataModule __all__ = [ "HuBERTDataModule", ]
"""**Callback handlers** allow listening to events in LangChain. **Class hierarchy:** .. code-block:: BaseCallbackHandler --> <name>CallbackHandler # Example: AimCallbackHandler """ from langchain_core.callbacks.base import ( AsyncCallbackHandler, BaseCallbackHandler, BaseCallbackManager, Callb...
"""**Callback handlers** allow listening to events in LangChain. **Class hierarchy:** .. code-block:: BaseCallbackHandler --> <name>CallbackHandler # Example: AimCallbackHandler """ from langchain_core.callbacks.base import ( AsyncCallbackHandler, BaseCallbackHandler, BaseCallbackManager, Callb...
tta_model = dict( type='DetTTAModel', tta_cfg=dict(nms=dict(type='nms', iou_threshold=0.6), max_per_img=100)) img_scales = [(640, 640), (320, 320), (960, 960)] tta_pipeline = [ dict(type='LoadImageFromFile', backend_args=None), dict( type='TestTimeAug', transforms=[ [ ...
tta_model = dict( type='DetTTAModel', tta_cfg=dict(nms=dict(type='nms', iou_threshold=0.6), max_per_img=100)) img_scales = [(640, 640), (320, 320), (960, 960)] tta_pipeline = [ dict(type='LoadImageFromFile', file_client_args=dict(backend='disk')), dict( type='TestTimeAug', transforms=[ ...
_base_ = '../mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py' model = dict( backbone=dict( norm_cfg=dict(type='SyncBN', requires_grad=True), norm_eval=False, plugins=[ dict( cfg=dict(type='ContextBlock', ratio=1. / 4), stages=(False, True, True, True), ...
_base_ = '../mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py' model = dict( backbone=dict( norm_cfg=dict(type='SyncBN', requires_grad=True), norm_eval=False, plugins=[ dict( cfg=dict(type='ContextBlock', ratio=1. / 4), stages=(False, True, True, True), ...
# Copyright 2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
# Copyright 2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn.functional as F from mmcv.cnn import ConvModule from mmcv.cnn.bricks import NonLocal2d from mmcv.runner import BaseModule from mmdet.registry import MODELS @MODELS.register_module() class BFP(BaseModule): """BFP (Balanced Feature Pyramids) BFP ...
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn.functional as F from mmcv.cnn import ConvModule from mmcv.cnn.bricks import NonLocal2d from mmcv.runner import BaseModule from ..builder import NECKS @NECKS.register_module() class BFP(BaseModule): """BFP (Balanced Feature Pyramids) BFP takes m...
_base_ = './yolov3_d53_mstrain-608_273e_coco.py' # dataset settings # file_client_args = dict( # backend='petrel', # path_mapping=dict({ # './data/': 's3://openmmlab/datasets/detection/', # 'data/': 's3://openmmlab/datasets/detection/' # })) file_client_args = dict(backend='disk') train_pip...
_base_ = './yolov3_d53_mstrain-608_273e_coco.py' # dataset settings # file_client_args = dict( # backend='petrel', # path_mapping=dict({ # './data/': 's3://openmmlab/datasets/detection/', # 'data/': 's3://openmmlab/datasets/detection/' # })) file_client_args = dict(backend='disk') train_pip...
"""Matrix decomposition algorithms. These include PCA, NMF, ICA, and more. Most of the algorithms of this module can be regarded as dimensionality reduction techniques. """ # Authors: The scikit-learn developers # SPDX-License-Identifier: BSD-3-Clause from ..utils.extmath import randomized_svd from ._dict_learning i...
"""Matrix decomposition algorithms. These include PCA, NMF, ICA, and more. Most of the algorithms of this module can be regarded as dimensionality reduction techniques. """ # Authors: The scikit-learn developers # SPDX-License-Identifier: BSD-3-Clause from ..utils.extmath import randomized_svd from ._dict_learning i...
import numpy as np import pytest import torch from docarray.typing import ( AudioNdArray, AudioTorchTensor, NdArrayEmbedding, TorchEmbedding, ) from docarray.utils.misc import is_tf_available tf_available = is_tf_available() if tf_available: import tensorflow as tf from docarray.typing import...
import numpy as np import torch from docarray.typing import ( AudioNdArray, AudioTorchTensor, NdArrayEmbedding, TorchEmbedding, ) def test_torch_tensors_interop(): t1 = AudioTorchTensor(torch.rand(128)) t2 = TorchEmbedding(torch.rand(128)) t_result = t1 + t2 assert isinstance(t_resul...
from typing import Iterable, Dict import torch.nn.functional as F from torch import nn, Tensor from .ContrastiveLoss import SiameseDistanceMetric from sentence_transformers.SentenceTransformer import SentenceTransformer class OnlineContrastiveLoss(nn.Module): def __init__( self, model: SentenceTransformer...
from typing import Iterable, Dict import torch.nn.functional as F from torch import nn, Tensor from .ContrastiveLoss import SiameseDistanceMetric from sentence_transformers.SentenceTransformer import SentenceTransformer class OnlineContrastiveLoss(nn.Module): def __init__( self, model: SentenceTransformer...
# Copyright (c) OpenMMLab. All rights reserved. from typing import Optional import torch def get_max_cuda_memory(device: Optional[torch.device] = None) -> int: """Returns the maximum GPU memory occupied by tensors in megabytes (MB) for a given device. By default, this returns the peak allocated memory since ...
# Copyright (c) OpenMMLab. All rights reserved. from typing import Optional import torch def get_max_cuda_memory(device: Optional[torch.device] = None) -> int: """Returns the maximum GPU memory occupied by tensors in megabytes (MB) for a given device. By default, this returns the peak allocated memory since ...
from keras.src import activations from keras.src import constraints from keras.src import initializers from keras.src import regularizers from keras.src.api_export import keras_export from keras.src.layers.input_spec import InputSpec from keras.src.layers.layer import Layer @keras_export("keras.layers.PReLU") class P...
from keras.src import activations from keras.src import constraints from keras.src import initializers from keras.src import regularizers from keras.src.api_export import keras_export from keras.src.layers.input_spec import InputSpec from keras.src.layers.layer import Layer @keras_export("keras.layers.PReLU") class P...
from pathlib import Path from typing import Any, Callable, Optional, Tuple import PIL.Image from .utils import check_integrity, download_and_extract_archive, download_url, verify_str_arg from .vision import VisionDataset class Flowers102(VisionDataset): """`Oxford 102 Flower <https://www.robots.ox.ac.uk/~vgg/da...
from pathlib import Path from typing import Any, Callable, Optional, Tuple import PIL.Image from .utils import check_integrity, download_and_extract_archive, download_url, verify_str_arg from .vision import VisionDataset class Flowers102(VisionDataset): """`Oxford 102 Flower <https://www.robots.ox.ac.uk/~vgg/da...
from jina.parsers.helper import add_arg_group def mixin_head_parser(parser): """Mixing in arguments required by head pods and runtimes into the given parser. :param parser: the parser instance to which we add arguments """ gp = add_arg_group(parser, title='Head') gp.add_argument( '--comp...
from jina.parsers.helper import add_arg_group def mixin_head_parser(parser): """Mixing in arguments required by head pods and runtimes into the given parser. :param parser: the parser instance to which we add arguments """ gp = add_arg_group(parser, title='Head') gp.add_argument( '--comp...
from typing_extensions import TYPE_CHECKING from docarray.typing.bytes import AudioBytes, ImageBytes, VideoBytes from docarray.typing.id import ID from docarray.typing.tensor import ImageNdArray, ImageTensor from docarray.typing.tensor.audio import AudioNdArray, AudioTensor from docarray.typing.tensor.embedding.embedd...
from typing import ( Union, TYPE_CHECKING, TypeVar, Sequence, Optional, List, Dict, Generator, Iterable, Tuple, ForwardRef, ) if TYPE_CHECKING: # pragma: no cover import scipy.sparse import tensorflow import torch import numpy as np from PIL.Image import...
import collections import json import os import string from typing import Iterable, List from .WordTokenizer import ENGLISH_STOP_WORDS, WordTokenizer class WhitespaceTokenizer(WordTokenizer): """ Simple and fast white-space tokenizer. Splits sentence based on white spaces. Punctuation are stripped from t...
from typing import Union, Tuple, List, Iterable, Dict import collections import string import os import json from .WordTokenizer import WordTokenizer, ENGLISH_STOP_WORDS class WhitespaceTokenizer(WordTokenizer): """ Simple and fast white-space tokenizer. Splits sentence based on white spaces. Punctuation a...
__copyright__ = 'Copyright (c) 2020-2021 Jina AI Limited. All rights reserved.' __license__ = 'Apache-2.0' from typing import Any, Iterable, Optional import librosa as lr import numpy as np import torch from jina import DocumentArray, Executor, requests from jina.excepts import BadDocType from .audio_clip.model impo...
__copyright__ = 'Copyright (c) 2020-2021 Jina AI Limited. All rights reserved.' __license__ = 'Apache-2.0' from typing import Any, Iterable, Optional import librosa as lr import numpy as np import torch from jina import DocumentArray, Executor, requests from jina.excepts import BadDocType from .audio_clip.model impo...
from __future__ import annotations from typing import Any, Optional, Union import PIL.Image import torch from ._datapoint import Datapoint class Image(Datapoint): """[BETA] :class:`torch.Tensor` subclass for images. .. note:: In the :ref:`transforms <transforms>`, ``Image`` instances are largely ...
from __future__ import annotations from typing import Any, Optional, Union import PIL.Image import torch from ._datapoint import Datapoint class Image(Datapoint): """[BETA] :class:`torch.Tensor` subclass for images. Args: data (tensor-like, PIL.Image.Image): Any data that can be turned into a tens...
import os import subprocess import pytest from xgboost import testing as tm pytestmark = [ pytest.mark.skipif(**tm.no_dask()), pytest.mark.skipif(**tm.no_dask_cuda()), tm.timeout(60), ] @pytest.mark.skipif(**tm.no_cupy()) @pytest.mark.mgpu def test_dask_training(): script = os.path.join(tm.demo_dir...
import os import subprocess import pytest from xgboost import testing as tm pytestmark = [ pytest.mark.skipif(**tm.no_dask()), pytest.mark.skipif(**tm.no_dask_cuda()), tm.timeout(60), ] @pytest.mark.skipif(**tm.no_cupy()) @pytest.mark.mgpu def test_dask_training(): script = os.path.join(tm.demo_dir...
from __future__ import annotations from .BinaryCrossEntropyLoss import BinaryCrossEntropyLoss from .CachedMultipleNegativesRankingLoss import CachedMultipleNegativesRankingLoss from .CrossEntropyLoss import CrossEntropyLoss from .MarginMSELoss import MarginMSELoss from .MSELoss import MSELoss from .MultipleNegativesRa...
from __future__ import annotations from .BinaryCrossEntropyLoss import BinaryCrossEntropyLoss from .CachedMultipleNegativesRankingLoss import CachedMultipleNegativesRankingLoss from .CrossEntropyLoss import CrossEntropyLoss from .MSELoss import MSELoss from .MultipleNegativesRankingLoss import MultipleNegativesRanking...
from typing import List, Optional from llama_index.core.base.base_retriever import BaseRetriever from llama_index.core.callbacks.base import CallbackManager from llama_index.core.indices.query.query_transform.base import BaseQueryTransform from llama_index.core.prompts.mixin import PromptMixinType from llama_index.cor...
from typing import List, Optional from llama_index.core.base.base_retriever import BaseRetriever from llama_index.core.callbacks.base import CallbackManager from llama_index.core.indices.query.query_transform.base import BaseQueryTransform from llama_index.core.prompts.mixin import PromptMixinType from llama_index.cor...
""" This examples trains BERT (or any other transformer model like RoBERTa, DistilBERT etc.) for the STSbenchmark from scratch. It generates sentence embeddings that can be compared using cosine-similarity to measure the similarity. Usage: python training_stsbenchmark.py OR python training_stsbenchmark.py pretrained_...
""" This examples trains BERT (or any other transformer model like RoBERTa, DistilBERT etc.) for the STSbenchmark from scratch. It generates sentence embeddings that can be compared using cosine-similarity to measure the similarity. Usage: python training_nli.py OR python training_nli.py pretrained_transformer_model_...
import logging from datasets import load_dataset from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseEmbeddingSimilarityEvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Load a model model = SparseEncoder("naver/splade-cocondenser...
import logging from datasets import load_dataset from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseEmbeddingSimilarityEvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Load a model model = SparseEncoder("naver/splade-cocondenser...
# Copyright (c) OpenMMLab. All rights reserved. from ..builder import BBOX_SAMPLERS, build_sampler from .base_sampler import BaseSampler @BBOX_SAMPLERS.register_module() class CombinedSampler(BaseSampler): """A sampler that combines positive sampler and negative sampler.""" def __init__(self, pos_sampler, ne...
from ..builder import BBOX_SAMPLERS, build_sampler from .base_sampler import BaseSampler @BBOX_SAMPLERS.register_module() class CombinedSampler(BaseSampler): """A sampler that combines positive sampler and negative sampler.""" def __init__(self, pos_sampler, neg_sampler, **kwargs): super(CombinedSamp...
from docarray.document.mixins.proto import ProtoMixin __all__ = ['ProtoMixin']
from docarray.document.mixins.proto import ProtoMixin
# Copyright (c) OpenMMLab. All rights reserved. import argparse import os import os.path as osp from mmengine import Config def parse_args(): parser = argparse.ArgumentParser( description='Convert benchmark model list to script') parser.add_argument('config', help='test config file path') parser....
# Copyright (c) OpenMMLab. All rights reserved. import argparse import os import os.path as osp from mmcv import Config def parse_args(): parser = argparse.ArgumentParser( description='Convert benchmark model list to script') parser.add_argument('config', help='test config file path') parser.add_...
"""Base classes for chain routing.""" from __future__ import annotations from abc import ABC from collections.abc import Mapping from typing import Any, NamedTuple, Optional from langchain_core.callbacks import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, Callbacks, ) from pydantic impo...
"""Base classes for chain routing.""" from __future__ import annotations from abc import ABC from collections.abc import Mapping from typing import Any, NamedTuple, Optional from langchain_core.callbacks import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, Callbacks, ) from pydantic impo...
from collections import defaultdict import torch import transforms as reference_transforms def get_modules(use_v2): # We need a protected import to avoid the V2 warning in case just V1 is used if use_v2: import torchvision.datapoints import torchvision.transforms.v2 return torchvisio...
import torch import transforms as T class DetectionPresetTrain: def __init__(self, *, data_augmentation, hflip_prob=0.5, mean=(123.0, 117.0, 104.0)): if data_augmentation == "hflip": self.transforms = T.Compose( [ T.RandomHorizontalFlip(p=hflip_prob), ...
from .CEBinaryAccuracyEvaluator import CEBinaryAccuracyEvaluator from .CEBinaryClassificationEvaluator import CEBinaryClassificationEvaluator from .CECorrelationEvaluator import CECorrelationEvaluator from .CEF1Evaluator import CEF1Evaluator from .CERerankingEvaluator import CERerankingEvaluator from .CESoftmaxAccuracy...
from .CEBinaryAccuracyEvaluator import CEBinaryAccuracyEvaluator from .CEBinaryClassificationEvaluator import CEBinaryClassificationEvaluator from .CEF1Evaluator import CEF1Evaluator from .CECorrelationEvaluator import CECorrelationEvaluator from .CESoftmaxAccuracyEvaluator import CESoftmaxAccuracyEvaluator from .CERer...
#!/usr/bin/env python3 # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. """ Run infe...
#!/usr/bin/env python3 # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. """ Run infe...
# dataset settings dataset_type = 'CocoPanopticDataset' data_root = 'data/coco/' # file_client_args = dict( # backend='petrel', # path_mapping=dict({ # './data/': 's3://openmmlab/datasets/detection/', # 'data/': 's3://openmmlab/datasets/detection/' # })) file_client_args = dict(backend='dis...
# dataset settings dataset_type = 'CocoPanopticDataset' data_root = 'data/coco/' train_pipeline = [ dict(type='LoadImageFromFile'), dict( type='LoadPanopticAnnotations', with_bbox=True, with_mask=True, with_seg=True), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True...
from ._bounding_box import BoundingBox, BoundingBoxFormat from ._datapoint import _FillType, _FillTypeJIT, _InputType, _InputTypeJIT from ._image import _ImageType, _ImageTypeJIT, _TensorImageType, _TensorImageTypeJIT, Image from ._mask import Mask from ._video import _TensorVideoType, _TensorVideoTypeJIT, _VideoType, ...
from ._bounding_box import BoundingBox, BoundingBoxFormat from ._datapoint import _FillType, _FillTypeJIT, _InputType, _InputTypeJIT from ._image import _ImageType, _ImageTypeJIT, _TensorImageType, _TensorImageTypeJIT, Image from ._mask import Mask from ._video import _TensorVideoType, _TensorVideoTypeJIT, _VideoType, ...
from typing import Any, Dict, Iterable import torch from torch import Tensor, nn from sentence_transformers import util from sentence_transformers.SentenceTransformer import SentenceTransformer class CoSENTLoss(nn.Module): def __init__(self, model: SentenceTransformer, scale: float = 20.0, similarity_fct=util.p...
from typing import Dict, Iterable import torch from torch import Tensor, nn from sentence_transformers import util from sentence_transformers.SentenceTransformer import SentenceTransformer class CoSENTLoss(nn.Module): def __init__(self, model: SentenceTransformer, scale: float = 20.0, similarity_fct=util.pairwi...
# Copyright (c) OpenMMLab. All rights reserved. import unittest from unittest import TestCase import torch from parameterized import parameterized from mmdet.registry import MODELS from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg from mmdet.utils import register_all_modules class TestDy...
# Copyright (c) OpenMMLab. All rights reserved. import unittest from unittest import TestCase import torch from mmdet.registry import MODELS from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg from mmdet.utils import register_all_modules class TestDynamicRoIHead(TestCase): def setUp(s...
# coding=utf-8 # Copyright 2025 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
# coding=utf-8 # Copyright 2024 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn from mmdet.registry import MODELS from .utils import weighted_loss @weighted_loss def smooth_l1_loss(pred, target, beta=1.0): """Smooth L1 loss. Args: pred (torch.Tensor): The prediction. target (torch.Tensor)...
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import torch import torch.nn as nn from mmdet.registry import MODELS from .utils import weighted_loss @mmcv.jit(derivate=True, coderize=True) @weighted_loss def smooth_l1_loss(pred, target, beta=1.0): """Smooth L1 loss. Args: pred (torch.Te...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import subprocess from typing import Dict, Iterable, Optional import spacy from jina import DocumentArray, Executor, requests _EXCLUDE_COMPONENTS = [ 'tagger', 'parser', 'ner', 'senter', 'le...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import subprocess from typing import Dict, Iterable, Optional import spacy from jina import DocumentArray, Executor, requests from jina_commons.batching import get_docs_batch_generator _EXCLUDE_COMPONENTS = [ ...
from langchain_core.runnables.base import ( Other, Runnable, RunnableBinding, RunnableBindingBase, RunnableEach, RunnableEachBase, RunnableGenerator, RunnableLambda, RunnableLike, RunnableParallel, RunnableSequence, RunnableSerializable, coerce_to_runnable, ) from lan...
from langchain_core.runnables.base import ( Other, Runnable, RunnableBinding, RunnableBindingBase, RunnableEach, RunnableEachBase, RunnableGenerator, RunnableLambda, RunnableLike, RunnableParallel, RunnableSequence, RunnableSerializable, coerce_to_runnable, ) from lan...
from typing import Union, Iterable, Dict from ..base.seqlike import BaseSequenceLikeMixin from .... import Document class SequenceLikeMixin(BaseSequenceLikeMixin): """Implement sequence-like methods for DocumentArray with Elastic as storage""" def __eq__(self, other): """Compare this object to the o...
from typing import Union, Iterable from ..base.seqlike import BaseSequenceLikeMixin from .... import Document class SequenceLikeMixin(BaseSequenceLikeMixin): """Implement sequence-like methods for DocumentArray with Elastic as storage""" def __eq__(self, other): """Compare this object to the other, ...
import threading from typing import Callable, ParamSpec, TypeVar P = ParamSpec("P") R = TypeVar("R") def thread_cached(func: Callable[P, R]) -> Callable[P, R]: thread_local = threading.local() def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: cache = getattr(thread_local, "cache", None) i...
from typing import Callable, TypeVar, ParamSpec import threading P = ParamSpec("P") R = TypeVar("R") def thread_cached(func: Callable[P, R]) -> Callable[P, R]: thread_local = threading.local() def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: cache = getattr(thread_local, "cache", None) i...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.callbacks.whylabs_callback import WhyLabsCallbackHandler # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handlin...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.callbacks.whylabs_callback import WhyLabsCallbackHandler # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handlin...
from __future__ import annotations __version__ = "4.1.0.dev0" __MODEL_HUB_ORGANIZATION__ = "sentence-transformers" import importlib import os import warnings from sentence_transformers.backend import ( export_dynamic_quantized_onnx_model, export_optimized_onnx_model, export_static_quantized_openvino_mode...
from __future__ import annotations __version__ = "4.1.0.dev0" __MODEL_HUB_ORGANIZATION__ = "sentence-transformers" import importlib import os from sentence_transformers.backend import ( export_dynamic_quantized_onnx_model, export_optimized_onnx_model, export_static_quantized_openvino_model, ) from senten...
_base_ = '../fast_rcnn/fast_rcnn_r50_fpn_1x_coco.py' model = dict( backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=False), norm_eval=True, style='caffe', in...
_base_ = '../fast_rcnn/fast_rcnn_r50_fpn_1x_coco.py' model = dict( backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=False), norm_eval=True, style='caffe', in...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from typing import Optional, Iterable, Any from jina import Executor, DocumentArray, requests import torch from .audio_clip.model import AudioCLIP from .audio_clip.utils.transforms import ToTensor1D class Aud...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from typing import Optional, Iterable, Any from jina import Executor, DocumentArray, requests import torch from model import AudioCLIP from utils.transforms import ToTensor1D class AudioCLIPEncoder(Executor):...
import logging import pathlib from postmarker.core import PostmarkClient from postmarker.models.emails import EmailManager from prisma.enums import NotificationType from pydantic import BaseModel from backend.data.notifications import ( NotificationEventModel, NotificationTypeOverride, T_co, ) from backen...
import logging import pathlib from postmarker.core import PostmarkClient from postmarker.models.emails import EmailManager from prisma.enums import NotificationType from pydantic import BaseModel from backend.data.notifications import ( NotificationEventModel, NotificationTypeOverride, T_co, ) from backen...
from __future__ import annotations import numpy as np from torch.utils.data import Dataset from transformers.utils.import_utils import NLTK_IMPORT_ERROR, is_nltk_available from sentence_transformers.readers.InputExample import InputExample class DenoisingAutoEncoderDataset(Dataset): """ The DenoisingAutoEnc...
from typing import List import numpy as np from torch.utils.data import Dataset from transformers.utils.import_utils import NLTK_IMPORT_ERROR, is_nltk_available from sentence_transformers.readers.InputExample import InputExample class DenoisingAutoEncoderDataset(Dataset): """ The DenoisingAutoEncoderDataset...
# Licensed to the LF AI & Data foundation under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the "License"); # you may not use this fil...
from typing import Any, ForwardRef, Optional, Union from typing_extensions import get_origin from typing_inspect import get_args, is_typevar, is_union_type def is_type_tensor(type_: Any) -> bool: """Return True if type is a type Tensor or an Optional Tensor type.""" from docarray.typing.tensor.abstract_tenso...
# Copyright (c) OpenMMLab. All rights reserved. import asyncio from argparse import ArgumentParser from mmdet.apis import (async_inference_detector, inference_detector, init_detector, show_result_pyplot) def parse_args(): parser = ArgumentParser() parser.add_argument('img', help='Imag...
# Copyright (c) OpenMMLab. All rights reserved. import asyncio from argparse import ArgumentParser from mmdet.apis import (async_inference_detector, inference_detector, init_detector, show_result_pyplot) def parse_args(): parser = ArgumentParser() parser.add_argument('img', help='Imag...
#!/usr/bin/env python import distutils.command.clean import os import re import shutil import subprocess from pathlib import Path import torch from setuptools import find_packages, setup from tools import setup_helpers ROOT_DIR = Path(__file__).parent.resolve() def _run_cmd(cmd): try: return subprocess....
#!/usr/bin/env python import distutils.command.clean import os import re import shutil import subprocess from pathlib import Path import torch from setuptools import find_packages, setup from tools import setup_helpers ROOT_DIR = Path(__file__).parent.resolve() def _run_cmd(cmd): try: return subprocess....
# Authors: The scikit-learn developers # SPDX-License-Identifier: BSD-3-Clause from numbers import Real import numpy as np from ..base import BaseEstimator, _fit_context from ..utils._param_validation import Interval from ..utils.sparsefuncs import mean_variance_axis, min_max_axis from ..utils.validation import chec...
# Authors: The scikit-learn developers # SPDX-License-Identifier: BSD-3-Clause from numbers import Real import numpy as np from ..base import BaseEstimator, _fit_context from ..utils._param_validation import Interval from ..utils.sparsefuncs import mean_variance_axis, min_max_axis from ..utils.validation import chec...
"""**Tools** are classes that an Agent uses to interact with the world. Each tool has a **description**. Agent uses the description to choose the right tool for the job. **Class hierarchy:** .. code-block:: RunnableSerializable --> BaseTool --> <name>Tool # Examples: AIPluginTool, BaseGraphQLTool ...
"""**Tools** are classes that an Agent uses to interact with the world. Each tool has a **description**. Agent uses the description to choose the right tool for the job. **Class hierarchy:** .. code-block:: RunnableSerializable --> BaseTool --> <name>Tool # Examples: AIPluginTool, BaseGraphQLTool ...
"""Output parsers using Pydantic.""" import json from typing import Annotated, Generic, Optional import pydantic from pydantic import SkipValidation from typing_extensions import override from langchain_core.exceptions import OutputParserException from langchain_core.output_parsers import JsonOutputParser from langc...
"""Output parsers using Pydantic.""" import json from typing import Annotated, Generic, Optional import pydantic from pydantic import SkipValidation from typing_extensions import override from langchain_core.exceptions import OutputParserException from langchain_core.output_parsers import JsonOutputParser from langc...
from ._presets import StereoMatching # usort: skip from ._augment import RandomCutmix, RandomMixup, SimpleCopyPaste from ._geometry import FixedSizeCrop from ._misc import PermuteDimensions, TransposeDimensions from ._type_conversion import LabelToOneHot
from torchvision.transforms import AutoAugmentPolicy, InterpolationMode # usort: skip from . import functional, utils # usort: skip from ._transform import Transform # usort: skip from ._presets import StereoMatching # usort: skip from ._augment import RandomCutmix, RandomErasing, RandomMixup, SimpleCopyPaste fr...
# Copyright (c) OpenMMLab. All rights reserved. import numpy as np import pytest import torch from mmdet.core.bbox import distance2bbox from mmdet.core.mask.structures import BitmapMasks, PolygonMasks from mmdet.core.utils import mask2ndarray def dummy_raw_polygon_masks(size): """ Args: size (tuple):...
import numpy as np import pytest import torch from mmdet.core.bbox import distance2bbox from mmdet.core.mask.structures import BitmapMasks, PolygonMasks from mmdet.core.utils import mask2ndarray def dummy_raw_polygon_masks(size): """ Args: size (tuple): expected shape of dummy masks, (N, H, W) R...
""" In this example we train a semantic search model to search through Wikipedia articles about programming articles & technologies. We use the text paragraphs from the following Wikipedia articles: Assembly language, C , C Sharp , C++, Go , Java , JavaScript, Keras, Laravel, MATLAB, Matplotlib, MongoDB, MySQL, Natura...
""" In this example we train a semantic search model to search through Wikipedia articles about programming articles & technologies. We use the text paragraphs from the following Wikipedia articles: Assembly language, C , C Sharp , C++, Go , Java , JavaScript, Keras, Laravel, MATLAB, Matplotlib, MongoDB, MySQL, Natura...
_base_ = './mask_rcnn_r101_fpn_gn-all_2x_coco.py' # learning policy max_epochs = 36 train_cfg = dict(max_epochs=max_epochs) # learning rate param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', begin=0, end=m...
_base_ = './mask_rcnn_r101_fpn_gn-all_2x_coco.py' # learning policy lr_config = dict(step=[28, 34]) runner = dict(type='EpochBasedRunner', max_epochs=36)
""" Functions for building sdist """ import logging import pathlib from .util import copy_with_logging, copytree_with_logging def copy_cpp_src_tree( cpp_src_dir: pathlib.Path, target_dir: pathlib.Path, logger: logging.Logger ) -> None: """Copy C++ source tree into build directory""" for subdir in [ ...
""" Functions for building sdist """ import logging import pathlib from .util import copy_with_logging, copytree_with_logging def copy_cpp_src_tree( cpp_src_dir: pathlib.Path, target_dir: pathlib.Path, logger: logging.Logger ) -> None: """Copy C++ source tree into build directory""" for subdir in [ ...
_base_ = [ '../_base_/models/mask-rcnn_r50_fpn.py', '../_base_/datasets/lvis_v1_instance.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( roi_head=dict( bbox_head=dict(num_classes=1203), mask_head=dict(num_classes=1203)), test_cfg=dict( rcnn=d...
_base_ = [ '../_base_/models/mask_rcnn_r50_fpn.py', '../_base_/datasets/lvis_v1_instance.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( roi_head=dict( bbox_head=dict(num_classes=1203), mask_head=dict(num_classes=1203)), test_cfg=dict( rcnn=d...
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import os import subprocess from pathlib import Path from typing import Dict import numpy as np import pytest import torch from jina import Document, DocumentArray from PIL import Image from torchvision.models.mobile...
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import os from typing import Dict import pytest import torch import numpy as np from torchvision.models.mobilenetv2 import model_urls from PIL import Image from jina import DocumentArray, Document @pytest.fixture(...