input
stringlengths
33
5k
output
stringlengths
32
5k
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp import xml.etree.ElementTree as ET from mmengine.dist import is_main_process from mmengine.fileio import get_local_path, list_from_file from mmengine.utils import ProgressBar from mmdet.registry import DATASETS from mmdet.utils.typing_utils import ...
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp import xml.etree.ElementTree as ET from mmengine.fileio import list_from_file from mmdet.registry import DATASETS from .xml_style import XMLDataset @DATASETS.register_module() class WIDERFaceDataset(XMLDataset): """Reader for the WIDER Face d...
from enum import Enum from typing import Callable, Union from numpy import ndarray from torch import Tensor from .util import ( cos_sim, dot_score, euclidean_sim, manhattan_sim, pairwise_cos_sim, pairwise_dot_score, pairwise_euclidean_sim, pairwise_manhattan_sim, ) class SimilarityFu...
from enum import Enum from typing import Callable, Union from numpy import ndarray from torch import Tensor from .util import ( cos_sim, manhattan_sim, euclidean_sim, dot_score, pairwise_cos_sim, pairwise_manhattan_sim, pairwise_euclidean_sim, pairwise_dot_score, ) class SimilarityFun...
from __future__ import annotations import logging import torch from torch import Tensor, nn from sentence_transformers.models.Module import Module logger = logging.getLogger(__name__) class WordWeights(Module): """This model can weight word embeddings, for example, with idf-values.""" config_keys: list[s...
from __future__ import annotations import json import logging import os import torch from torch import Tensor, nn logger = logging.getLogger(__name__) class WordWeights(nn.Module): """This model can weight word embeddings, for example, with idf-values.""" def __init__(self, vocab: list[str], word_weights:...
from typing import Any, Optional, Type, TypeVar, Union import numpy as np from docarray.base_document import BaseDocument from docarray.typing import AnyEmbedding, AudioUrl from docarray.typing.bytes.audio_bytes import AudioBytes from docarray.typing.tensor.abstract_tensor import AbstractTensor from docarray.typing.t...
from typing import Any, Optional, Type, TypeVar, Union import numpy as np from docarray.base_document import BaseDocument from docarray.typing import AnyEmbedding, AudioUrl from docarray.typing.bytes.audio_bytes import AudioBytes from docarray.typing.tensor.abstract_tensor import AbstractTensor from docarray.typing.t...
import subprocess import sys import pytest from pytest_benchmark.fixture import BenchmarkFixture # type: ignore[import-untyped] @pytest.mark.parametrize( "import_path", [ pytest.param( "from langchain_core.messages import HumanMessage", id="HumanMessage" ), pytest.param("...
import subprocess import sys import pytest from pytest_benchmark.fixture import BenchmarkFixture # type: ignore[import-untyped] @pytest.mark.parametrize( "import_path", [ pytest.param( "from langchain_core.messages import HumanMessage", id="HumanMessage" ), pytest.param("...
import gzip import logging import os import sys from datetime import datetime from torch.utils.data import DataLoader from sentence_transformers import LoggingHandler, SentenceTransformer, datasets, evaluation, losses, models, util #### Just some code to print debug information to stdout logging.basicConfig( for...
import gzip import logging import os import sys from datetime import datetime from torch.utils.data import DataLoader from sentence_transformers import LoggingHandler, SentenceTransformer, datasets, evaluation, losses, models, util #### Just some code to print debug information to stdout logging.basicConfig( for...
import asyncio import logging import os from jina import __default_host__ from jina.importer import ImportExtensions from jina.serve.runtimes.gateway import GatewayRuntime from jina.serve.runtimes.gateway.http.app import get_fastapi_app __all__ = ['HTTPGatewayRuntime'] class HTTPGatewayRuntime(GatewayRuntime): ...
import asyncio import logging import os from jina import __default_host__ from jina.importer import ImportExtensions from jina.serve.runtimes.gateway import GatewayRuntime from jina.serve.runtimes.gateway.http.app import get_fastapi_app __all__ = ['HTTPGatewayRuntime'] class HTTPGatewayRuntime(GatewayRuntime): ...
import asyncio import pytest from llama_index.core.workflow.context import Context from llama_index.core.workflow.decorators import step from llama_index.core.workflow.errors import WorkflowRuntimeError, WorkflowTimeoutError from llama_index.core.workflow.events import Event, StartEvent, StopEvent from llama_index.cor...
import asyncio import pytest from llama_index.core.workflow.context import Context from llama_index.core.workflow.decorators import step from llama_index.core.workflow.errors import WorkflowRuntimeError, WorkflowTimeoutError from llama_index.core.workflow.events import Event, StartEvent, StopEvent from llama_index.cor...
# Copyright (c) OpenMMLab. All rights reserved. from unittest.mock import Mock import pytest from mmengine.hooks import ParamSchedulerHook from mmengine.optim import _ParamScheduler class TestParamSchedulerHook: error_msg = ('runner.param_schedulers should be list of ParamScheduler or ' 'a dict...
# Copyright (c) OpenMMLab. All rights reserved. from unittest.mock import Mock import pytest from mmengine.hooks import ParamSchedulerHook class TestParamSchedulerHook: error_msg = ('runner.param_schedulers should be list of ParamScheduler or ' 'a dict containing list of ParamScheduler') d...
import numpy as np import pytest from pydantic.tools import parse_obj_as, schema_json_of from docarray.base_document.io.json import orjson_dumps from docarray.typing import Mesh3DUrl from tests import TOYDATA_DIR MESH_FILES = { 'obj': str(TOYDATA_DIR / 'tetrahedron.obj'), 'glb': str(TOYDATA_DIR / 'test.glb'),...
import numpy as np import pytest from pydantic.tools import parse_obj_as, schema_json_of from docarray.document.io.json import orjson_dumps from docarray.typing import Mesh3DUrl from tests import TOYDATA_DIR MESH_FILES = { 'obj': str(TOYDATA_DIR / 'tetrahedron.obj'), 'glb': str(TOYDATA_DIR / 'test.glb'), ...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import subprocess from typing import Iterable, Optional import torch from jina import DocumentArray, Executor, requests from jina.logging.logger import JinaLogger from laserembeddings import Laser class Laser...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import subprocess from typing import Iterable, Optional import torch from jina import DocumentArray, Executor, requests from jina.logging.logger import JinaLogger from laserembeddings import Laser class Laser...
import os import random import time from typing import Dict, OrderedDict import numpy as np import pytest from jina import Document, DocumentArray, Executor, Flow, requests from jina_commons.indexers.dump import dump_docs from jinahub.indexers.compound.FaissLMDBSearcher.faiss_lmdb import FaissLMDBSearcher from jinahu...
import os import random import time from typing import Dict, OrderedDict import numpy as np import pytest from jina import Document, Flow, DocumentArray, requests, Executor from jina_commons.indexers.dump import dump_docs from jinahub.indexers.searcher.compound.FaissLMDBSearcher.faiss_lmdb import FaissLMDBSearcher fr...
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 RescalingTest(testing.TestCase): @pytest.mark.requires_trainable_backend def test_rescaling_basics(self): self.run_layer_test( ...
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 RescalingTest(testing.TestCase): @pytest.mark.requires_trainable_backend def test_rescaling_basics(self): self.run_layer_test( ...
# 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...
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 multi-level features as inputs and gather them in...
import json import pytest import xgboost from xgboost import testing as tm from xgboost.testing.metrics import ( check_precision_score, check_quantile_error, run_pr_auc_binary, run_pr_auc_ltr, run_pr_auc_multi, run_roc_auc_binary, run_roc_auc_multi, ) class TestGPUEvalMetrics: @pytes...
import json import sys import pytest import xgboost from xgboost import testing as tm from xgboost.testing.metrics import check_precision_score, check_quantile_error sys.path.append("tests/python") import test_eval_metrics as test_em # noqa class TestGPUEvalMetrics: cpu_test = test_em.TestEvalMetrics() @...
from pathlib import Path from typing import List import numpy as np import pytest import torch from jina import Document, DocumentArray, Executor from ...transform_encoder import TransformerTorchEncoder from ..integration.test_integration import filter_none def test_config(): ex = Executor.load_config(str(Path(...
from pathlib import Path from typing import List import numpy as np import pytest import torch from jina import Document, DocumentArray, Executor from ...transform_encoder import TransformerTorchEncoder from ..integration.test_integration import filter_none def test_config(): ex = Executor.load_config(str(Path(...
from langchain_core.prompts.prompt import PromptTemplate API_URL_PROMPT_TEMPLATE = """You are given the below API Documentation: {api_docs} Using this documentation, generate the full API url to call for answering the user question. You should build the API url in order to get a response that is as short as possible, ...
# flake8: noqa from langchain_core.prompts.prompt import PromptTemplate API_URL_PROMPT_TEMPLATE = """You are given the below API Documentation: {api_docs} Using this documentation, generate the full API url to call for answering the user question. You should build the API url in order to get a response that is as shor...
import itertools from typing import ( TYPE_CHECKING, Union, Sequence, overload, Any, List, ) import numpy as np from docarray import Document from docarray.helper import typename if TYPE_CHECKING: from docarray.typing import ( DocumentArrayIndexType, DocumentArraySingleton...
import itertools from typing import ( TYPE_CHECKING, Union, Sequence, overload, Any, List, ) import numpy as np from docarray import Document from docarray.helper import typename if TYPE_CHECKING: from docarray.typing import ( DocumentArrayIndexType, DocumentArraySingleton...
# coding=utf-8 # Copyright 2025 Cohere 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 app...
# coding=utf-8 # Copyright 2025 Cohere 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 app...
# Copyright (c) OpenMMLab. All rights reserved. from mmcv.cnn import ConvModule, Linear from mmengine.model import ModuleList from torch import Tensor from mmdet.registry import MODELS from mmdet.utils import MultiConfig from .fcn_mask_head import FCNMaskHead @MODELS.register_module() class CoarseMaskHead(FCNMaskHea...
# Copyright (c) OpenMMLab. All rights reserved. from mmcv.cnn import ConvModule, Linear from mmengine.model import ModuleList from torch import Tensor from mmdet.registry import MODELS from mmdet.utils import MultiConfig from .fcn_mask_head import FCNMaskHead @MODELS.register_module() class CoarseMaskHead(FCNMaskHea...
"""OpenAI Image Generation tool spec.""" import base64 import os import time from typing import Optional from llama_index.core.tools.tool_spec.base import BaseToolSpec DEFAULT_CACHE_DIR = "../../../img_cache" DEFAULT_SIZE = "1024x1024" valid_sizes = { "dall-e-2": ["256x256", "512x512", "1024x1024"], "dall-e...
"""OpenAI Image Generation tool spec.""" import base64 import os import time from typing import Optional from llama_index.core.tools.tool_spec.base import BaseToolSpec DEFAULT_CACHE_DIR = "../../../img_cache" DEFAULT_SIZE = "1024x1024" valid_sizes = { "dall-e-2": ["256x256", "512x512", "1024x1024"], "dall-e...
"""**Prompt** is the input to the model. Prompt is often constructed from multiple components and prompt values. Prompt classes and functions make constructing and working with prompts easy. **Class hierarchy:** .. code-block:: BasePromptTemplate --> PipelinePromptTemplate StringProm...
"""**Prompt** is the input to the model. Prompt is often constructed from multiple components and prompt values. Prompt classes and functions make constructing and working with prompts easy. **Class hierarchy:** .. code-block:: BasePromptTemplate --> PipelinePromptTemplate StringProm...
from torchvision.transforms import InterpolationMode # usort: skip from ._utils import is_simple_tensor # usort: skip from ._meta import ( clamp_bounding_boxes, convert_format_bounding_boxes, get_dimensions_image_tensor, get_dimensions_image_pil, get_dimensions, get_num_frames_video, get...
from torchvision.transforms import InterpolationMode # usort: skip from ._utils import is_simple_tensor # usort: skip from ._meta import ( clamp_bounding_box, convert_format_bounding_box, get_dimensions_image_tensor, get_dimensions_image_pil, get_dimensions, get_num_frames_video, get_num...
__version__ = '0.30.0a3' from docarray.array import DocumentArray, DocumentArrayStacked from docarray.base_document.document import BaseDocument __all__ = ['BaseDocument', 'DocumentArray', 'DocumentArrayStacked']
__version__ = '0.30.0a3' from docarray.array.array.array import DocumentArray from docarray.base_document.document import BaseDocument __all__ = [ 'BaseDocument', 'DocumentArray', ]
from contextlib import suppress from docutils import nodes from docutils.parsers.rst import Directive from sklearn.utils import all_estimators from sklearn.utils._test_common.instance_generator import _construct_instances from sklearn.utils._testing import SkipTest class AllowNanEstimators(Directive): @staticme...
from contextlib import suppress from docutils import nodes from docutils.parsers.rst import Directive from sklearn.utils import all_estimators from sklearn.utils._test_common.instance_generator import _construct_instances from sklearn.utils._testing import SkipTest class AllowNanEstimators(Directive): @staticme...
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import copy from typing import Dict from jina import requests, DocumentArray, Executor from jina_commons import get_logger from jinahub.indexers.searcher.NumpySearcher.numpy_searcher import NumpySearcher from jinahu...
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import copy from typing import Dict from jina import requests, DocumentArray, Executor from jina_commons import get_logger from jinahub.indexers.searcher.NumpySearcher import NumpySearcher from jinahub.indexers.stor...
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmengine.data import InstanceData from mmdet.core.bbox.assigners import AssignResult from mmdet.registry import TASK_UTILS from .base_sampler import BaseSampler from .sampling_result import SamplingResult @TASK_UTILS.register_module() class PseudoSamp...
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmengine.data import InstanceData from mmdet.core.bbox.assigners import AssignResult from mmdet.registry import TASK_UTILS from .base_sampler import BaseSampler from .sampling_result import SamplingResult @TASK_UTILS.register_module() class PseudoSamp...
"""Tool for the SearxNG search API.""" from typing import Optional, Type from langchain_core.callbacks import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain_core.tools import BaseTool from pydantic import BaseModel, ConfigDict, Field from langchain_community.utilities.searx_sea...
"""Tool for the SearxNG search API.""" from typing import Optional, Type from langchain_core.callbacks import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain_core.tools import BaseTool from pydantic import BaseModel, ConfigDict, Field from langchain_community.utilities.searx_sea...
# Copyright (c) OpenMMLab. All rights reserved. __version__ = '0.5.0' def parse_version_info(version_str): """Parse the version information. Args: version_str (str): version string like '0.1.0'. Returns: tuple: version information contains major, minor, micro version. """ versio...
# Copyright (c) OpenMMLab. All rights reserved. __version__ = '0.4.0' def parse_version_info(version_str): """Parse the version information. Args: version_str (str): version string like '0.1.0'. Returns: tuple: version information contains major, minor, micro version. """ versio...
""" This examples trains a CrossEncoder for the NLI task. A CrossEncoder takes a sentence pair as input and outputs a label. Here, it learns to predict the labels: "contradiction": 0, "entailment": 1, "neutral": 2. It does NOT produce a sentence embedding and does NOT work for individual sentences. Usage: python trai...
""" This examples trains a CrossEncoder for the NLI task. A CrossEncoder takes a sentence pair as input and outputs a label. Here, it learns to predict the labels: "contradiction": 0, "entailment": 1, "neutral": 2. It does NOT produce a sentence embedding and does NOT work for individual sentences. Usage: python trai...
import os from pathlib import Path import cv2 import pytest from jina import Document, DocumentArray, Executor from ...yolov5_segmenter import YoloV5Segmenter cur_dir = os.path.dirname(os.path.abspath(__file__)) def test_load(): segmenter = Executor.load_config(str(Path(__file__).parents[2] / 'config.yml')) ...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import os from pathlib import Path import cv2 import pytest from jina import Executor, Document, DocumentArray from ...yolov5_segmenter import YoloV5Segmenter cur_dir = os.path.dirname(os.path.abspath(__file__...
""" Top-level module of Jina. The primary function of this module is to import all of the public Jina interfaces into a single place. The interfaces themselves are located in sub-modules, as described below. """ import os as _os import platform as _platform import signal as _signal import sys as _sys import warnings...
""" Top-level module of Jina. The primary function of this module is to import all of the public Jina interfaces into a single place. The interfaces themselves are located in sub-modules, as described below. """ import os as _os import platform as _platform import signal as _signal import sys as _sys import warnings...
import os from time import time import numpy as np import pytest from docarray import BaseDoc, DocArray from docarray.documents import ImageDoc from docarray.typing import NdArray from docarray.utils.map import map_docs, map_docs_batch from tests.units.typing.test_bytes import IMAGE_PATHS pytestmark = [pytest.mark.b...
import os from time import time import numpy as np import pytest from docarray import BaseDocument, DocumentArray from docarray.documents import ImageDoc from docarray.typing import NdArray from docarray.utils.map import map_docs, map_docs_batch from tests.units.typing.test_bytes import IMAGE_PATHS pytestmark = [pyt...
"""Utilities for environment variables.""" from __future__ import annotations import os from typing import Any, Optional, Union def env_var_is_set(env_var: str) -> bool: """Check if an environment variable is set. Args: env_var (str): The name of the environment variable. Returns: bool...
"""Utilities for environment variables.""" from __future__ import annotations import os from typing import Any, Optional, Union def env_var_is_set(env_var: str) -> bool: """Check if an environment variable is set. Args: env_var (str): The name of the environment variable. Returns: bool...
import pytest from llama_index.llms.nvidia import NVIDIA as Interface from pytest_httpx import HTTPXMock @pytest.fixture() def mock_local_models(httpx_mock: HTTPXMock, base_url: str) -> None: mock_response = { "data": [ { "id": "dummy", "object": "model", ...
import pytest from llama_index.llms.nvidia import NVIDIA as Interface from pytest_httpx import HTTPXMock @pytest.fixture() def mock_local_models(httpx_mock: HTTPXMock, base_url: str) -> None: mock_response = { "data": [ { "id": "dummy", "object": "model", ...
from __future__ import annotations from typing import Any, List, Optional, Tuple, Union import PIL.Image import torch from torchvision.transforms import InterpolationMode from ._datapoint import Datapoint, FillTypeJIT class Mask(Datapoint): @classmethod def _wrap(cls, tensor: torch.Tensor) -> Mask: ...
from __future__ import annotations from typing import Any, List, Optional, Tuple, Union import PIL.Image import torch from torchvision.transforms import InterpolationMode from ._datapoint import Datapoint, FillTypeJIT class Mask(Datapoint): @classmethod def _wrap(cls, tensor: torch.Tensor) -> Mask: ...
from __future__ import annotations import pytest from sentence_transformers import SentenceTransformer, SentenceTransformerTrainer from sentence_transformers.model_card import generate_model_card from sentence_transformers.util import is_datasets_available, is_training_available if is_datasets_available(): from ...
from __future__ import annotations import pytest from datasets import Dataset, DatasetDict from sentence_transformers import SentenceTransformer, SentenceTransformerTrainer from sentence_transformers.model_card import generate_model_card @pytest.fixture(scope="session") def dummy_dataset(): """ Dummy datase...
from typing import TypeVar from docarray.typing.proto_register import _register_proto from docarray.typing.tensor.image.abstract_image_tensor import AbstractImageTensor from docarray.typing.tensor.torch_tensor import TorchTensor, metaTorchAndNode T = TypeVar('T', bound='ImageTorchTensor') @_register_proto(proto_typ...
from typing import TypeVar from docarray.typing.proto_register import _register_proto from docarray.typing.tensor.image.abstract_image_tensor import AbstractImageTensor from docarray.typing.tensor.torch_tensor import TorchTensor, metaTorchAndNode T = TypeVar('T', bound='ImageTorchTensor') @_register_proto(proto_typ...
from typing import Dict, Iterable import torch from torch import Tensor, nn from sentence_transformers import SentenceTransformer class MSELoss(nn.Module): def __init__(self, model: SentenceTransformer) -> None: """ Computes the MSE loss between the computed sentence embedding and a target sente...
from typing import Dict, Iterable import torch from torch import Tensor, nn class MSELoss(nn.Module): def __init__(self, model): """ Computes the MSE loss between the computed sentence embedding and a target sentence embedding. This loss is used when extending sentence embeddings to new l...
from typing import Optional from typing_extensions import Protocol, runtime_checkable from torch.distributed._state_dict_utils import _copy_state_dict, _create_cpu_state_dict from torch.distributed.checkpoint.metadata import STATE_DICT_TYPE __all__ = ["AsyncStager", "BlockingAsyncStager"] @runtime_checkable class ...
from typing import Optional from typing_extensions import Protocol, runtime_checkable from torch.distributed._state_dict_utils import _copy_state_dict, _create_cpu_state_dict from torch.distributed.checkpoint.metadata import STATE_DICT_TYPE __all__ = ["AsyncStager", "BlockingAsyncStager"] @runtime_checkable class ...
_base_ = 'grounding_dino_swin-t_pretrain_obj365.py' o365v1_od_dataset = dict( type='ODVGDataset', data_root='data/objects365v1/', ann_file='o365v1_train_odvg.json', label_map_file='o365v1_label_map.json', data_prefix=dict(img='train/'), filter_cfg=dict(filter_empty_gt=False), pipeline=_base...
_base_ = 'grounding_dino_swin-t_pretrain_obj365.py' o365v1_od_dataset = dict( type='ODVGDataset', data_root='data/objects365v1/', ann_file='o365v1_train_odvg.jsonl', label_map_file='o365v1_label_map.json', data_prefix=dict(img='train/'), filter_cfg=dict(filter_empty_gt=False), pipeline=_bas...
from abc import ABC from collections import namedtuple from dataclasses import is_dataclass, asdict from typing import Dict, Optional, TYPE_CHECKING if TYPE_CHECKING: from ....typing import DocumentArraySourceType, ArrayType TypeMap = namedtuple('TypeMap', ['type', 'converter']) class BaseBackendMixin(ABC): ...
from abc import ABC from dataclasses import is_dataclass, asdict from typing import Dict, Optional, TYPE_CHECKING if TYPE_CHECKING: from ....typing import DocumentArraySourceType, ArrayType class BaseBackendMixin(ABC): TYPE_MAP: Dict def _init_storage( self, _docs: Optional['DocumentArra...
"""Argparser module for WorkerRuntime""" from jina import __default_host__, helper from jina.parsers.helper import KVAppendAction, add_arg_group def mixin_worker_runtime_parser(parser): """Mixing in arguments required by :class:`WorkerRuntime` into the given parser. :param parser: the parser instance to which...
"""Argparser module for WorkerRuntime""" from jina import __default_host__, helper from jina.parsers.helper import KVAppendAction, add_arg_group def mixin_worker_runtime_parser(parser): """Mixing in arguments required by :class:`WorkerRuntime` into the given parser. :param parser: the parser instance to which...
from typing import TYPE_CHECKING, Type, TypeVar, Union from uuid import UUID from pydantic import BaseConfig, parse_obj_as from pydantic.fields import ModelField if TYPE_CHECKING: from docarray.proto import NodeProto from docarray.typing.abstract_type import AbstractType T = TypeVar('T', bound='ID') class ID(...
from typing import Type, TypeVar, Union from uuid import UUID from pydantic import BaseConfig, parse_obj_as from pydantic.fields import ModelField from docarray.proto import NodeProto from docarray.typing.abstract_type import AbstractType T = TypeVar('T', bound='ID') class ID(str, AbstractType): """ Represe...
""" Top-level module of Jina. The primary function of this module is to import all of the public Jina interfaces into a single place. The interfaces themselves are located in sub-modules, as described below. """ import os as _os import platform as _platform import signal as _signal import sys as _sys import warnings...
""" Top-level module of Jina. The primary function of this module is to import all of the public Jina interfaces into a single place. The interfaces themselves are located in sub-modules, as described below. """ import os as _os import platform as _platform import signal as _signal import sys as _sys import warnings...
_base_ = [ '../_base_/models/faster-rcnn_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] checkpoint = 'https://download.pytorch.org/models/resnet50-11ad3fa6.pth' model = dict( backbone=dict(init_cfg=dict(type='Pretrained', chec...
_base_ = [ '../_base_/models/faster-rcnn_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] checkpoint = 'https://download.pytorch.org/models/resnet50-11ad3fa6.pth' model = dict( backbone=dict(init_cfg=dict(type='Pretrained', chec...
_base_ = './mask_rcnn_r50_fpn_1x_coco.py' 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( # use caffe img_norm preprocess_cfg=preprocess_cfg, backbone=dict( norm_cfg=dict(requires_grad=False), styl...
_base_ = './mask_rcnn_r50_fpn_1x_coco.py' model = dict( backbone=dict( norm_cfg=dict(requires_grad=False), style='caffe', init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://detectron2/resnet50_caffe'))) # use caffe img_norm img_norm_cfg = dict( mean=[103.5...
_base_ = './retinanet_r50-caffe_fpn_1x_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://detectron2/resnet101_caffe')))
_base_ = './retinanet_r50_caffe_fpn_1x_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://detectron2/resnet101_caffe')))
# 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 abc import ABC, abstractmethod from typing import Dict, Iterator, List, Type from typing_extensions import TYPE_CHECKING if TYPE_CHECKING: from docarray import BaseDoc, DocList class AbstractDocStore(ABC): @staticmethod @abstractmethod def list(namespace: str, show_table: bool) -> List[str]: ...
import os from typing import Optional import pytest from docarray import BaseDocument, DocumentArray from docarray.documents import ImageDoc from tests import TOYDATA_DIR @pytest.fixture() def nested_doc_cls(): class MyDoc(BaseDocument): count: Optional[int] text: str class MyDocNested(MyDo...
import os from typing import Optional import pytest from docarray import BaseDocument, DocumentArray from docarray.documents import Image from tests import TOYDATA_DIR @pytest.fixture() def nested_doc_cls(): class MyDoc(BaseDocument): count: Optional[int] text: str class MyDocNested(MyDoc):...
from enum import Enum from typing import Dict, Iterable import torch.nn.functional as F from torch import Tensor, nn from sentence_transformers.SentenceTransformer import SentenceTransformer class SiameseDistanceMetric(Enum): """The metric for the contrastive loss""" EUCLIDEAN = lambda x, y: F.pairwise_dis...
from enum import Enum from typing import Iterable, Dict import torch.nn.functional as F from torch import nn, Tensor from sentence_transformers.SentenceTransformer import SentenceTransformer class SiameseDistanceMetric(Enum): """ The metric for the contrastive loss """ EUCLIDEAN = lambda x, y: F.pairw...
# Copyright (c) OpenMMLab. All rights reserved. from mmengine.device import (get_device, is_cuda_available, is_mlu_available, is_mps_available, is_npu_available) def test_get_device(): device = get_device() if is_npu_available(): assert device == 'npu' elif is_cuda_ava...
# Copyright (c) OpenMMLab. All rights reserved. from mmengine.device import (get_device, is_cuda_available, is_mlu_available, is_mps_available) def test_get_device(): device = get_device() if is_cuda_available(): assert device == 'cuda' elif is_mlu_available(): ...
import logging import re from typing import Any import uvicorn.config from colorama import Fore def remove_color_codes(s: str) -> str: return re.sub(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])", "", s) def fmt_kwargs(kwargs: dict) -> str: return ", ".join(f"{n}={repr(v)}" for n, v in kwargs.items()) def print...
import logging import re from typing import Any from colorama import Fore def remove_color_codes(s: str) -> str: return re.sub(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])", "", s) def fmt_kwargs(kwargs: dict) -> str: return ", ".join(f"{n}={repr(v)}" for n, v in kwargs.items()) def print_attribute( title...
from __future__ import annotations import pytest from torch import Tensor from sentence_transformers import SparseEncoder @pytest.mark.parametrize( "model_name", [ ("sentence-transformers/all-MiniLM-L6-v2"), ], ) def test_load_and_encode(model_name: str) -> None: # Ensure that SparseEncoder ...
from __future__ import annotations import pytest from torch import Tensor from sentence_transformers import SparseEncoder @pytest.mark.parametrize( "model_name", [ ("sentence-transformers/all-MiniLM-L6-v2"), ], ) def test_load_and_encode(model_name: str) -> None: # Ensure that SparseEncoder ...
# Copyright 2018 The TensorFlow Authors. 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 applica...
# Copyright 2018 The TensorFlow Authors. 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 applica...
from typing import Any, Union, Optional from vertexai.generative_models._generative_models import SafetySettingsType from google.cloud.aiplatform_v1beta1.types import content as gapic_content_types from llama_index.core.llms import ChatMessage, MessageRole, ImageBlock, TextBlock def is_gemini_model(model: str) -> boo...
import base64 from typing import Any, Dict, Union, Optional from vertexai.generative_models._generative_models import SafetySettingsType from google.cloud.aiplatform_v1beta1.types import content as gapic_content_types from llama_index.core.llms import ChatMessage, MessageRole def is_gemini_model(model: str) -> bool: ...
"""Test LLMSummarization functionality.""" import pytest from langchain.chains.llm_summarization_checker.base import ( ARE_ALL_TRUE_PROMPT, CHECK_ASSERTIONS_PROMPT, CREATE_ASSERTIONS_PROMPT, REVISED_SUMMARY_PROMPT, LLMSummarizationCheckerChain, ) from tests.unit_tests.llms.fake_llm import FakeLLM ...
# flake8: noqa E501 """Test LLMSummarization functionality.""" import pytest from langchain.chains.llm_summarization_checker.base import ( ARE_ALL_TRUE_PROMPT, CHECK_ASSERTIONS_PROMPT, CREATE_ASSERTIONS_PROMPT, REVISED_SUMMARY_PROMPT, LLMSummarizationCheckerChain, ) from tests.unit_tests.llms.fak...
_base_ = './htc-without-semantic_r50_fpn_1x_coco.py' model = dict( data_preprocessor=dict(pad_seg=True), roi_head=dict( semantic_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0), out_channels=256, ...
_base_ = './htc-without-semantic_r50_fpn_1x_coco.py' model = dict( data_preprocessor=dict(pad_seg=True), roi_head=dict( semantic_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0), out_channels=256, ...
from langchain.indexes import __all__ def test_all() -> None: """Use to catch obvious breaking changes.""" expected = [ "aindex", "GraphIndexCreator", "index", "IndexingResult", "SQLRecordManager", "VectorstoreIndexCreator", ] assert sorted(__all__) == s...
from langchain.indexes import __all__ def test_all() -> None: """Use to catch obvious breaking changes.""" expected = [ "aindex", "GraphIndexCreator", "index", "IndexingResult", "SQLRecordManager", "VectorstoreIndexCreator", ] assert __all__ == sorted(ex...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.tools import GoogleSerperResults, GoogleSerperRun # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling optio...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.tools import GoogleSerperResults, GoogleSerperRun # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling optio...
import types from keras.src.activations.activations import celu from keras.src.activations.activations import elu from keras.src.activations.activations import exponential from keras.src.activations.activations import gelu from keras.src.activations.activations import glu from keras.src.activations.activations import ...
import types from keras.src.activations.activations import celu from keras.src.activations.activations import elu from keras.src.activations.activations import exponential from keras.src.activations.activations import gelu from keras.src.activations.activations import glu from keras.src.activations.activations import ...
import asyncio import pytest from grpc import ChannelConnectivity from jina.serve.networking.connection_stub import _ConnectionStubs from jina.serve.networking.instrumentation import _NetworkingHistograms from jina.serve.networking.replica_list import _ReplicaList @pytest.fixture() def replica_list(logger, metrics)...
import asyncio import pytest from grpc import ChannelConnectivity from jina.serve.networking.connection_stub import _ConnectionStubs from jina.serve.networking.instrumentation import _NetworkingHistograms from jina.serve.networking.replica_list import _ReplicaList @pytest.fixture() def replica_list(logger, metrics)...
import numpy as np import pytest import xgboost as xgb from xgboost import testing as tm pytestmark = pytest.mark.skipif(**tm.no_pandas()) dpath = 'demo/data/' rng = np.random.RandomState(1994) class TestTreesToDataFrame: def build_model(self, max_depth, num_round): dtrain, _ = tm.load_agaricus(__file...
import numpy as np import pytest import xgboost as xgb from xgboost import testing as tm pytestmark = pytest.mark.skipif(**tm.no_pandas()) dpath = 'demo/data/' rng = np.random.RandomState(1994) class TestTreesToDataFrame: def build_model(self, max_depth, num_round): dtrain, _ = tm.load_agaricus(__file...
from abc import ABC, abstractmethod from typing import Dict, Iterator, List, Type from typing_extensions import TYPE_CHECKING if TYPE_CHECKING: from docarray import BaseDoc, DocList class AbstractDocStore(ABC): @staticmethod @abstractmethod def list(namespace: str, show_table: bool) -> List[str]: ...
from abc import ABC, abstractmethod from typing import Dict, Iterator, List, Optional, Type from typing_extensions import TYPE_CHECKING if TYPE_CHECKING: from docarray import BaseDoc, DocList class AbstractDocStore(ABC): @staticmethod @abstractmethod def list(namespace: str, show_table: bool) -> Lis...
_base_ = [ '../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # please install mmpretrain # import mmpretrain.models to trigger register_module in mmpretrain custom_imports = dict( imports=['mmpretrain....
_base_ = [ '../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # TODO: delete custom_imports after mmcls supports auto import # please install mmcls>=1.0 # import mmcls.models to trigger register_module in m...
# Copyright (c) OpenMMLab. All rights reserved. import argparse import cv2 import mmcv import numpy as np import torch import torch.nn as nn from mmcv.transforms import Compose from mmengine.utils import track_iter_progress from mmdet.apis import init_detector from mmdet.registry import VISUALIZERS from mmdet.structu...
# Copyright (c) OpenMMLab. All rights reserved. import argparse import cv2 import mmcv import numpy as np import torch import torch.nn as nn from mmcv.transforms import Compose from mmengine.utils import track_iter_progress from mmdet.apis import init_detector from mmdet.registry import VISUALIZERS from mmdet.structu...
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( type='YOLOF', data_preprocessor=dict( type='DetDataPreprocessor', mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], bgr_to_rgb=Fals...
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( type='YOLOF', data_preprocessor=dict( type='DetDataPreprocessor', mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], bgr_to_rgb=Fals...
_base_ = '../_base_/default_runtime.py' # model settings model = dict( type='YOLOV3', backbone=dict( type='MobileNetV2', out_indices=(2, 4, 6), act_cfg=dict(type='LeakyReLU', negative_slope=0.1), init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://mmdet/mobilen...
_base_ = '../_base_/default_runtime.py' # model settings model = dict( type='YOLOV3', backbone=dict( type='MobileNetV2', out_indices=(2, 4, 6), act_cfg=dict(type='LeakyReLU', negative_slope=0.1), init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://mmdet/mobilen...
from typing import List, TYPE_CHECKING if TYPE_CHECKING: # pragma: no cover from docarray.typing import T, Document def _reduce_doc_props(doc1: 'Document', doc2: 'Document'): doc1_fields = set(doc1.non_empty_fields) doc2_fields = set(doc2.non_empty_fields) # update only fields that are set in doc2 ...
from typing import List, TYPE_CHECKING if TYPE_CHECKING: from docarray.typing import T, Document def _reduce_doc_props(doc1: 'Document', doc2: 'Document'): doc1_fields = set(doc1.non_empty_fields) doc2_fields = set(doc2.non_empty_fields) # update only fields that are set in doc2 and not set in doc1 ...
_base_ = './faster-rcnn_r50_fpn_1x_coco.py' model = dict( data_preprocessor=dict( type='DetDataPreprocessor', 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(requires_grad=False), ...
_base_ = './faster-rcnn_r50_fpn_1x_coco.py' model = dict( data_preprocessor=dict( type='DetDataPreprocessor', 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(requires_grad=False), ...
import json from jina.orchestrate.flow.base import Flow from jina.orchestrate.deployments import Deployment from jina.jaml import JAML from jina.logging.predefined import default_logger from jina.schemas import get_full_schema from jina_cli.export import api_to_dict def export_kubernetes(args): """Export to k8s ...
import json from jina.orchestrate.flow.base import Flow from jina.orchestrate.deployments import Deployment from jina.jaml import JAML from jina.logging.predefined import default_logger from jina.schemas import get_full_schema from jina_cli.export import api_to_dict def export_kubernetes(args): """Export to k8s ...
import numpy as np import pytest from pydantic import Field from docarray import BaseDoc, DocList from docarray.index.backends.in_memory import InMemoryExactNNIndex from docarray.typing import NdArray class SchemaDoc(BaseDoc): text: str price: int tensor: NdArray[10] @pytest.fixture def docs(): doc...
import numpy as np import pytest from pydantic import Field from docarray import BaseDoc, DocList from docarray.index.backends.in_memory import InMemoryDocIndex from docarray.typing import NdArray class SchemaDoc(BaseDoc): text: str price: int tensor: NdArray[10] @pytest.fixture def docs(): docs = ...
from typing import TYPE_CHECKING, TypeVar import numpy as np from docarray.typing.url.url_3d.url_3d import Url3D if TYPE_CHECKING: from docarray.proto import NodeProto T = TypeVar('T', bound='PointCloud3DUrl') class PointCloud3DUrl(Url3D): """ URL to a .obj, .glb, or .ply file containing point cloud i...
from typing import TYPE_CHECKING, TypeVar import numpy as np from docarray.typing.url.url_3d.url_3d import Url3D if TYPE_CHECKING: from docarray.proto import NodeProto T = TypeVar('T', bound='PointCloud3DUrl') class PointCloud3DUrl(Url3D): """ URL to a .obj, .glb, or .ply file containing point cloud i...
# Copyright (c) OpenMMLab. All rights reserved. from .history_buffer import HistoryBuffer from .log_processor import LogProcessor from .logger import MMLogger, print_log from .message_hub import MessageHub __all__ = [ 'HistoryBuffer', 'MessageHub', 'MMLogger', 'print_log', 'LogProcessor' ]
# Copyright (c) OpenMMLab. All rights reserved. from .history_buffer import HistoryBuffer from .logger import MMLogger, print_log from .message_hub import MessageHub __all__ = ['HistoryBuffer', 'MessageHub', 'MMLogger', 'print_log']
from __future__ import annotations from collections.abc import Iterable import torch import torch.nn as nn import torch.nn.functional as F from sentence_transformers.sparse_encoder import SparseEncoder class ReconstructionLoss(nn.Module): """ Reconstruction Loss module for Sparse AutoEncoder. This mod...
from __future__ import annotations from collections.abc import Iterable import torch import torch.nn as nn import torch.nn.functional as F from sentence_transformers.sparse_encoder import SparseEncoder class ReconstructionLoss(nn.Module): """ Reconstruction Loss module for Sparse AutoEncoder. This mod...
import warnings from typing import Any, Callable, List, Optional, Sequence, Union import torch from torch import nn from torchvision.prototype.transforms import Transform class Compose(Transform): def __init__(self, transforms: Sequence[Callable]) -> None: super().__init__() if not isinstance(tr...
import warnings from typing import Any, Callable, List, Optional, Sequence import torch from torchvision.prototype.transforms import Transform class Compose(Transform): def __init__(self, transforms: Sequence[Callable]) -> None: super().__init__() if not isinstance(transforms, Sequence): ...
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import subprocess from pathlib import Path import pytest @pytest.fixture(scope='session') def docker_image_name() -> str: return Path(__file__).parents[1].stem.lower() @pytest.fixture(scope='session') def bui...
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import subprocess from pathlib import Path import pytest @pytest.fixture(scope='session') def docker_image_name() -> str: return Path(__file__).parents[1].stem.lower() @pytest.fixture(scope='session') def bui...
import os from pathlib import Path import pytest from jina import Flow from jina.excepts import RuntimeFailToStart from jina.orchestrate.deployments import Deployment from jina.parsers import set_deployment_parser from jina.serve.executors import BaseExecutor cur_dir = os.path.dirname(os.path.abspath(__file__)) de...
import os from pathlib import Path import pytest from jina import Flow from jina.excepts import RuntimeFailToStart from jina.orchestrate.deployments import Deployment from jina.parsers import set_deployment_parser from jina.serve.executors import BaseExecutor cur_dir = os.path.dirname(os.path.abspath(__file__)) de...
"""Image prompt template for a multimodal model.""" from typing import Any from pydantic import Field from langchain_core.prompt_values import ImagePromptValue, ImageURL, PromptValue from langchain_core.prompts.base import BasePromptTemplate from langchain_core.prompts.string import ( DEFAULT_FORMATTER_MAPPING, ...
"""Image prompt template for a multimodal model.""" from typing import Any from pydantic import Field from langchain_core.prompt_values import ImagePromptValue, ImageURL, PromptValue from langchain_core.prompts.base import BasePromptTemplate from langchain_core.prompts.string import ( DEFAULT_FORMATTER_MAPPING, ...
import http.client import json from typing import Optional def list_packages(*, contains: Optional[str] = None): conn = http.client.HTTPSConnection("api.github.com") headers = { "Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", "User-Agent": "langchain-cli...
import http.client import json from typing import Optional def list_packages(*, contains: Optional[str] = None): conn = http.client.HTTPSConnection("api.github.com") headers = { "Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", "User-Agent": "langchain-cli...
from __future__ import annotations from collections.abc import Iterable from typing import Any import torch from torch import Tensor, nn from sentence_transformers.SentenceTransformer import SentenceTransformer from sentence_transformers.util import fullname class CosineSimilarityLoss(nn.Module): def __init__(...
from __future__ import annotations from collections.abc import Iterable from typing import Any import torch from torch import Tensor, nn from sentence_transformers.SentenceTransformer import SentenceTransformer from sentence_transformers.util import fullname class CosineSimilarityLoss(nn.Module): def __init__(...
_base_ = [ '../common/ms_3x_coco-instance.py', '../_base_/models/cascade-mask-rcnn_r50_fpn.py' ]
_base_ = [ '../common/mstrain_3x_coco_instance.py', '../_base_/models/cascade_mask_rcnn_r50_fpn.py' ]
import grpc from grpc_health.v1 import health, health_pb2, health_pb2_grpc from grpc_reflection.v1alpha import reflection from pydantic import BaseModel from uvicorn import Config, Server from jina import Gateway, __default_host__ from jina.proto import jina_pb2, jina_pb2_grpc class DummyResponseModel(BaseModel): ...
import grpc from grpc_health.v1 import health, health_pb2, health_pb2_grpc from grpc_reflection.v1alpha import reflection from pydantic import BaseModel from uvicorn import Config, Server from jina import Gateway, __default_host__ from jina.proto import jina_pb2, jina_pb2_grpc class DummyResponseModel(BaseModel): ...
from jina.clients.base.grpc import GRPCBaseClient from jina.clients.mixin import ( AsyncHealthCheckMixin, AsyncPostMixin, HealthCheckMixin, PostMixin, ) class GRPCClient(GRPCBaseClient, PostMixin, HealthCheckMixin): """A client connecting to a Gateway using gRPC protocol. Instantiate this cla...
from jina.clients.base.grpc import GRPCBaseClient from jina.clients.mixin import AsyncPostMixin, HealthCheckMixin, PostMixin class GRPCClient(GRPCBaseClient, PostMixin, HealthCheckMixin): """A client connecting to a Gateway using gRPC protocol. Instantiate this class through the :meth:`jina.Client` convenien...
from torchaudio._internal.module_utils import dropping_support, dropping_class_support import inspect _CTC_DECODERS = [ "CTCHypothesis", "CTCDecoder", "CTCDecoderLM", "CTCDecoderLMState", "ctc_decoder", "download_pretrained_files", ] _CUDA_CTC_DECODERS = [ "CUCTCDecoder", "CUCTCHypothesi...
from torchaudio._internal.module_utils import dropping_support _CTC_DECODERS = [ "CTCHypothesis", "CTCDecoder", "CTCDecoderLM", "CTCDecoderLMState", "ctc_decoder", "download_pretrained_files", ] _CUDA_CTC_DECODERS = [ "CUCTCDecoder", "CUCTCHypothesis", "cuda_ctc_decoder", ] def __g...
# Copyright (c) OpenMMLab. All rights reserved. from .image import (color_val_matplotlib, imshow_det_bboxes, imshow_gt_det_bboxes) __all__ = ['imshow_det_bboxes', 'imshow_gt_det_bboxes', 'color_val_matplotlib']
from .image import (color_val_matplotlib, imshow_det_bboxes, imshow_gt_det_bboxes) __all__ = ['imshow_det_bboxes', 'imshow_gt_det_bboxes', 'color_val_matplotlib']
_base_ = '../mask_rcnn/mask-rcnn_r101_fpn_1x_coco.py' model = dict( backbone=dict(plugins=[ dict( cfg=dict(type='ContextBlock', ratio=1. / 4), stages=(False, True, True, True), position='after_conv3') ]))
_base_ = '../mask_rcnn/mask_rcnn_r101_fpn_1x_coco.py' model = dict( backbone=dict(plugins=[ dict( cfg=dict(type='ContextBlock', ratio=1. / 4), stages=(False, True, True, True), position='after_conv3') ]))
import os import numpy as np import pytest import torch from pydantic.tools import parse_obj_as from docarray import BaseDocument from docarray.typing import ( AudioNdArray, AudioTorchTensor, VideoNdArray, VideoTorchTensor, ) @pytest.mark.parametrize( 'tensor,cls_video_tensor,cls_tensor', [ ...
import os import numpy as np import pytest import torch from pydantic.tools import parse_obj_as from docarray import BaseDocument from docarray.typing import ( AudioNdArray, AudioTorchTensor, VideoNdArray, VideoTorchTensor, ) @pytest.mark.parametrize( 'tensor,cls_video_tensor,cls_tensor', [ ...
import copy from dataclasses import dataclass, field from pathlib import Path from typing import Any, Optional, Union from .. import config @dataclass class DownloadConfig: """Configuration for our cached path manager. Attributes: cache_dir (`str` or `Path`, *optional*): Specify a cache ...
import copy from dataclasses import dataclass, field from pathlib import Path from typing import Any, Optional, Union from .. import config @dataclass class DownloadConfig: """Configuration for our cached path manager. Attributes: cache_dir (`str` or `Path`, *optional*): Specify a cache ...
from __future__ import annotations from dataclasses import dataclass, field from typing import Any, Callable import torch from sentence_transformers.data_collator import SentenceTransformerDataCollator @dataclass class CrossEncoderDataCollator(SentenceTransformerDataCollator): """Collator for a CrossEncoder mo...
from __future__ import annotations from dataclasses import dataclass, field from typing import Any, Callable import torch from sentence_transformers.data_collator import SentenceTransformerDataCollator @dataclass class CrossEncoderDataCollator(SentenceTransformerDataCollator): """Collator for a CrossEncoder mo...
import pathlib from typing import Any, Dict, List, Tuple, Union import torch from torchdata.datapipes.iter import CSVParser, IterDataPipe, Mapper from torchvision.prototype.datapoints import Image, OneHotLabel from torchvision.prototype.datasets.utils import Dataset, HttpResource, OnlineResource from torchvision.proto...
import pathlib from typing import Any, Dict, List, Tuple, Union import torch from torchdata.datapipes.iter import CSVParser, IterDataPipe, Mapper from torchvision.prototype.datasets.utils import Dataset, HttpResource, OnlineResource from torchvision.prototype.datasets.utils._internal import hint_sharding, hint_shuffli...
import asyncio from itertools import cycle from typing import Any, Optional, Union from uuid import UUID import pytest from pytest_benchmark.fixture import BenchmarkFixture # type: ignore[import-untyped] from typing_extensions import override from langchain_core.callbacks.base import AsyncCallbackHandler from langch...
import asyncio from itertools import cycle from typing import Any, Optional, Union from uuid import UUID import pytest from pytest_benchmark.fixture import BenchmarkFixture # type: ignore[import-untyped] from typing_extensions import override from langchain_core.callbacks.base import AsyncCallbackHandler from langch...
__version__ = '0.13.3' import os from .document import Document from .array import DocumentArray from .dataclasses import dataclass, field if 'DA_NO_RICH_HANDLER' not in os.environ: from rich.traceback import install install()
__version__ = '0.13.2' import os from .document import Document from .array import DocumentArray from .dataclasses import dataclass, field if 'DA_NO_RICH_HANDLER' not in os.environ: from rich.traceback import install install()
from docarray.array.mixins.attribute import GetAttributeArrayMixin from docarray.array.mixins.proto import ProtoArrayMixin __all__ = ['ProtoArrayMixin', 'GetAttributeArrayMixin']
from docarray.array.mixins.proto import ProtoArrayMixin __all__ = ['ProtoArrayMixin']
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.registry import MODELS from mmdet.utils.typing import ConfigType, OptConfigType, OptMultiConfig from .single_stage_instance_seg import SingleStageInstanceSegmentor @MODELS.register_module() class YOLACT(SingleStageInstanceSegmentor): """Implementation of...
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmdet.data_elements.bbox import bbox2result from mmdet.registry import MODELS from .single_stage import SingleStageDetector @MODELS.register_module() class YOLACT(SingleStageDetector): """Implementation of `YOLACT <https://arxiv.org/abs/1904.02689...
"""Init params.""" from llama_index.finetuning.cross_encoders.cross_encoder import ( CrossEncoderFinetuneEngine, ) __all__ = ["CrossEncoderFinetuneEngine"]
"""Init params.""" from llama_index.finetuning.cross_encoders.cross_encoder import ( CrossEncoderFinetuneEngine, ) __all__ = ["CrossEncoderFinetuneEngine"]
# Copyright 2024 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 2024 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...
import colorsys from rich.color import Color from rich.console import Console from rich.console import ConsoleOptions, RenderResult from rich.measure import Measurement from rich.segment import Segment from rich.style import Style from docarray.math.helper import minmax_normalize from docarray.math.ndarray import to_...
import colorsys from rich.color import Color from rich.console import Console from rich.console import ConsoleOptions, RenderResult from rich.measure import Measurement from rich.segment import Segment from rich.style import Style from ...math.helper import minmax_normalize from ...math.ndarray import to_numpy_array ...
# 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_...
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_argument('--port', type=int, default=29666, help...
from langchain_core.prompts.prompt import PromptTemplate _PROMPT_TEMPLATE = """Translate a math problem into a expression that can be executed using Python's numexpr library. Use the output of running this code to answer the question. Question: ${{Question with math problem.}} ```text ${{single line mathematical expr...
# flake8: noqa from langchain_core.prompts.prompt import PromptTemplate _PROMPT_TEMPLATE = """Translate a math problem into a expression that can be executed using Python's numexpr library. Use the output of running this code to answer the question. Question: ${{Question with math problem.}} ```text ${{single line ma...