input
stringlengths
33
5k
output
stringlengths
32
5k
from typing import TYPE_CHECKING, Union, BinaryIO from docarray.document.mixins.helper import _uri_to_blob, _to_datauri, _get_file_context if TYPE_CHECKING: # pragma: no cover from docarray.typing import T class BlobDataMixin: """Provide helper functions for :class:`Document` to handle binary data.""" ...
from typing import TYPE_CHECKING, Union, BinaryIO from docarray.document.mixins.helper import _uri_to_blob, _to_datauri, _get_file_context if TYPE_CHECKING: from docarray.typing import T class BlobDataMixin: """Provide helper functions for :class:`Document` to handle binary data.""" def load_uri_to_blo...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import re from typing import Dict, List, Optional from jina import Document, DocumentArray, Executor, requests from jina.logging.logger import JinaLogger class Sentencizer(Executor): """ :class:`Senten...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import re from typing import Dict, List, Optional, Tuple from jina import Document, DocumentArray, Executor, requests from jina.logging.logger import JinaLogger class Sentencizer(Executor): """ :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...
_base_ = '../cascade_rcnn/cascade-mask-rcnn_x101-32x4d_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,...
_base_ = '../cascade_rcnn/cascade_mask_rcnn_x101_32x4d_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,...
# flake8: noqa # Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors. # # 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/LI...
# flake8: noqa # Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors. # # 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/LI...
"""Argparser module for WorkerRuntime""" from jina.parsers.helper import KVAppendAction, add_arg_group from jina.parsers.orchestrate.runtimes.runtime import mixin_base_runtime_parser def mixin_worker_runtime_parser(parser): """Mixing in arguments required by :class:`WorkerRuntime` into the given parser. :par...
"""Argparser module for WorkerRuntime""" from jina.parsers.helper import KVAppendAction, add_arg_group from jina.parsers.orchestrate.runtimes.runtime import mixin_base_runtime_parser def mixin_worker_runtime_parser(parser): """Mixing in arguments required by :class:`WorkerRuntime` into the given parser. :par...
# Copyright (c) OpenMMLab. All rights reserved. from .mask2former_track_head import Mask2FormerTrackHead from .quasi_dense_embed_head import QuasiDenseEmbedHead from .quasi_dense_track_head import QuasiDenseTrackHead __all__ = [ 'QuasiDenseEmbedHead', 'QuasiDenseTrackHead', 'Mask2FormerTrackHead' ]
# Copyright (c) OpenMMLab. All rights reserved. from .quasi_dense_embed_head import QuasiDenseEmbedHead from .quasi_dense_track_head import QuasiDenseTrackHead __all__ = ['QuasiDenseEmbedHead', 'QuasiDenseTrackHead']
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp import tempfile import mmcv from mmdet.datasets import CocoPanopticDataset def _create_panoptic_style_json(json_name): image1 = { 'id': 0, 'width': 640, 'height': 640, 'file_name': 'fake_name1.jpg', } ...
import os.path as osp import tempfile import mmcv from mmdet.datasets import CocoPanopticDataset def _create_panoptic_style_json(json_name): image1 = { 'id': 0, 'width': 640, 'height': 640, 'file_name': 'fake_name1.jpg', } image2 = { 'id': 1, 'width': 640...
"""Code to help indexing data into a vectorstore. This package contains helper logic to help deal with indexing data into a vectorstore while avoiding duplicated content and over-writing content if it's unchanged. """ from typing import TYPE_CHECKING from langchain_core._import_utils import import_attr if TYPE_CHEC...
"""Code to help indexing data into a vectorstore. This package contains helper logic to help deal with indexing data into a vectorstore while avoiding duplicated content and over-writing content if it's unchanged. """ from typing import TYPE_CHECKING from langchain_core._import_utils import import_attr if TYPE_CHEC...
from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize("repo_id", ["canonical_dataset_name", "org-name/dataset-name"]) @pytest.mark.parametrize("filename", ["filename.csv", "filename with blanks.csv"]) @pytest.mark.parametrize("revision", [None, "v2"]) def te...
from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize("repo_id", ["canonical_dataset_name", "org-name/dataset-name"]) @pytest.mark.parametrize("path", ["filename.csv", "filename with blanks.csv"]) @pytest.mark.parametrize("revision", [None, "v2"]) def test_h...
import logging from datasets import load_dataset from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseTranslationEvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Load a model, not mutilingual but hope to see some on the hub soon m...
import logging from datasets import load_dataset from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseTranslationEvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Load a model, not mutilingual but hope to see some on the hub soon m...
import logging import os from contextlib import asynccontextmanager from uuid import uuid4 from dotenv import load_dotenv from prisma import Prisma from pydantic import BaseModel, Field, field_validator from backend.util.retry import conn_retry load_dotenv() PRISMA_SCHEMA = os.getenv("PRISMA_SCHEMA", "schema.prisma...
import logging import os from contextlib import asynccontextmanager from uuid import uuid4 from dotenv import load_dotenv from prisma import Prisma from pydantic import BaseModel, Field, field_validator from backend.util.retry import conn_retry load_dotenv() PRISMA_SCHEMA = os.getenv("PRISMA_SCHEMA", "schema.prisma...
from pydantic import AnyUrl as BaseAnyUrl from docarray.document.base_node import BaseNode from docarray.proto import NodeProto class AnyUrl(BaseAnyUrl, BaseNode): def _to_node_protobuf(self) -> NodeProto: """Convert Document into a NodeProto protobuf message. This function should be called when ...
from pydantic import AnyUrl as BaseAnyUrl from docarray.document.base_node import BaseNode from docarray.proto import NodeProto class AnyUrl(BaseAnyUrl, BaseNode): def _to_nested_item_protobuf(self) -> 'NodeProto': """Convert Document into a nested item protobuf message. This function should be c...
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='Text') class Text(BaseDocument): """ Document for handling text. It can contain a T...
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='Text') class Text(BaseDocument): """ Document for handling text. It can contain a T...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.ops.image import affine_transform as affine_transform from keras.src.ops.image import crop_images as crop_images from keras.src.ops.image import elastic_transform as elastic_transform...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.ops.image import affine_transform from keras.src.ops.image import crop_images from keras.src.ops.image import elastic_transform from keras.src.ops.image import extract_patches from ke...
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn import torch.utils.checkpoint as cp from mmcv.cnn import ConvModule from mmcv.cnn.bricks import DropPath from mmcv.runner import BaseModule from .se_layer import SELayer class InvertedResidual(BaseModule): """Inverted Residual Block. Args...
# Copyright (c) OpenMMLab. All rights reserved. import torch.utils.checkpoint as cp from mmcv.cnn import ConvModule from mmcv.runner import BaseModule from .se_layer import SELayer class InvertedResidual(BaseModule): """Inverted Residual Block. Args: in_channels (int): The input channels of this Mod...
import json import aioboto3.session import pytest import aioboto3 from llama_index.embeddings.bedrock import BedrockEmbedding, Models EXP_REQUEST = "foo bar baz" EXP_RESPONSE = { "embedding": [ 0.017410278, 0.040924072, -0.007507324, 0.09429932, 0.015304565, ] } class...
import json import aioboto3.session import pytest import aioboto3 from llama_index.embeddings.bedrock import BedrockEmbedding, Models EXP_REQUEST = "foo bar baz" EXP_RESPONSE = { "embedding": [ 0.017410278, 0.040924072, -0.007507324, 0.09429932, 0.015304565, ] } class...
# Copyright (c) OpenMMLab. All rights reserved. from mmcv.runner.hooks import HOOKS, Hook @HOOKS.register_module() class MemoryProfilerHook(Hook): """Memory profiler hook recording memory information including virtual memory, swap memory, and the memory of the current process. Args: interval (int...
# Copyright (c) OpenMMLab. All rights reserved. from mmcv.runner.hooks import HOOKS, Hook @HOOKS.register_module() class MemoryProfilerHook(Hook): """Memory profiler hook recording memory information: virtual memory, swap memory and memory of current process. Args: interval (int): Checking interv...
_base_ = '../mask_rcnn/mask-rcnn_x101-32x4d_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. / 16), stages=(False, True, True, Tru...
_base_ = '../mask_rcnn/mask_rcnn_x101_32x4d_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. / 16), stages=(False, True, True, Tru...
# pylint: disable=protected-access """Shared typing definition.""" import ctypes import os from typing import ( TYPE_CHECKING, Any, AnyStr, Callable, Dict, List, Optional, Sequence, Tuple, Type, TypeVar, Union, ) # os.PathLike/string/numpy.array/scipy.sparse/pd.DataFrame...
# pylint: disable=protected-access """Shared typing definition.""" import ctypes import os from typing import ( TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence, Tuple, Type, TypeVar, Union, ) # os.PathLike/string/numpy.array/scipy.sparse/pd.DataFrame/dt.Frame/ #...
from keras.src import ops from keras.src.api_export import keras_export from keras.src.layers.layer import Layer @keras_export("keras.layers.UnitNormalization") class UnitNormalization(Layer): """Unit normalization layer. Normalize a batch of inputs so that each input in the batch has a L2 norm equal to ...
from keras.src import ops from keras.src.api_export import keras_export from keras.src.layers.layer import Layer @keras_export("keras.layers.UnitNormalization") class UnitNormalization(Layer): """Unit normalization layer. Normalize a batch of inputs so that each input in the batch has a L2 norm equal to ...
import os import numpy as np import pytest from docarray import BaseDocument, DocumentArray from docarray.documents import ImageDoc from docarray.typing import NdArray class MyDoc(BaseDocument): embedding: NdArray text: str image: ImageDoc @pytest.mark.slow @pytest.mark.parametrize( 'protocol', ['...
import pytest import os import numpy as np from docarray import BaseDocument from docarray.typing import NdArray from docarray.documents import Image from docarray import DocumentArray class MyDoc(BaseDocument): embedding: NdArray text: str image: Image @pytest.mark.slow @pytest.mark.parametrize( '...
import pytest from docarray import DocumentArray @pytest.fixture def docs(): docs = DocumentArray.empty(5) docs[0].text = 'hello' docs[0].tags['name'] = 'hello' docs[1].text = 'world' docs[1].tags['name'] = 'hello' docs[2].tags['x'] = 0.3 docs[2].tags['y'] = 0.6 docs[3].tags['x'] = 0....
import pytest from docarray import DocumentArray @pytest.fixture def docs(): docs = DocumentArray.empty(5) docs[0].text = 'hello' docs[0].tags['name'] = 'hello' docs[1].text = 'world' docs[1].tags['name'] = 'hello' docs[2].tags['x'] = 0.3 docs[2].tags['y'] = 0.6 docs[3].tags['x'] = 0....
from typing import List import numpy as np import pytest import torch from jina import Document, DocumentArray from ...audioclip_text import AudioCLIPTextEncoder _EMBEDDING_DIM = 1024 def test_encoding_cpu(): enc = AudioCLIPTextEncoder(device='cpu') input_data = DocumentArray([Document(text='hello world')])...
from typing import List import numpy as np import pytest import torch from jina import Document, DocumentArray from jinahub.encoder.audioclip_text import AudioCLIPTextEncoder _EMBEDDING_DIM = 1024 def test_encoding_cpu(): enc = AudioCLIPTextEncoder(device='cpu') input_data = DocumentArray([Document(text='he...
import pathlib from typing import Any, Dict, List, Tuple, Union from torchdata.datapipes.iter import IterDataPipe, Mapper from torchvision.prototype.datasets.utils import Dataset, EncodedImage, HttpResource, OnlineResource from torchvision.prototype.datasets.utils._internal import hint_sharding, hint_shuffling from to...
import pathlib from typing import Any, Dict, List, Tuple, Union from torchdata.datapipes.iter import IterDataPipe, Mapper from torchvision.prototype.datasets.utils import Dataset, HttpResource, OnlineResource from torchvision.prototype.datasets.utils._internal import hint_sharding, hint_shuffling from torchvision.prot...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from pathlib import Path from typing import Dict import numpy as np import pytest from image_tf_encoder import ImageTFEncoder from jina import Document, DocumentArray, Executor input_dim = 336 target_output_dim...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from pathlib import Path from typing import Dict import numpy as np import pytest from jina import Document, DocumentArray, Executor from ...image_tf_encoder import ImageTFEncoder input_dim = 336 target_output...
import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast logger = datasets.utils.logging.get_logger(__name__) @dataclass class ParquetConfig(datasets.BuilderConfig): """BuilderCo...
import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast logger = datasets.utils.logging.get_logger(__name__) @dataclass class ParquetConfig(datasets.BuilderConfig): """BuilderCo...
# Copyright (c) OpenMMLab. All rights reserved. from unittest import TestCase import torch from mmengine.structures import InstanceData from mmdet.models.dense_heads import NASFCOSHead class TestNASFCOSHead(TestCase): def test_nasfcos_head_loss(self): """Tests nasfcos head loss when truth is empty and ...
# Copyright (c) OpenMMLab. All rights reserved. from unittest import TestCase import torch from mmengine.data import InstanceData from mmdet.models.dense_heads import NASFCOSHead class TestNASFCOSHead(TestCase): def test_nasfcos_head_loss(self): """Tests nasfcos head loss when truth is empty and non-em...
import os from functools import lru_cache from typing import Union import ffmpeg import numpy as np import torch import torch.nn.functional as F from .utils import exact_div # hard-coded audio hyperparameters SAMPLE_RATE = 16000 N_FFT = 400 N_MELS = 80 HOP_LENGTH = 160 CHUNK_LENGTH = 30 N_SAMPLES = CHUNK_LENGTH * SA...
import os from functools import lru_cache from typing import Union import ffmpeg import numpy as np import torch import torch.nn.functional as F from .utils import exact_div # hard-coded audio hyperparameters SAMPLE_RATE = 16000 N_FFT = 400 N_MELS = 80 HOP_LENGTH = 160 CHUNK_LENGTH = 30 N_SAMPLES = CHUNK_LENGTH * SA...
import io import warnings from abc import ABC import numpy as np from typing_extensions import TYPE_CHECKING from docarray.typing.tensor.abstract_tensor import AbstractTensor from docarray.utils._internal.misc import import_library, is_notebook if TYPE_CHECKING: from docarray.typing.bytes.image_bytes import Imag...
import io import warnings from abc import ABC import numpy as np from docarray.typing.tensor.abstract_tensor import AbstractTensor from docarray.utils._internal.misc import import_library, is_notebook class AbstractImageTensor(AbstractTensor, ABC): def to_bytes(self, format: str = 'PNG') -> bytes: """ ...
import os import shutil import subprocess import numpy as np import PIL.Image as Image import pytest from jina import Document, Flow cur_dir = os.path.dirname(os.path.abspath(__file__)) def data_generator(num_docs): for i in range(num_docs): doc = Document(uri=os.path.join(cur_dir, '..', 'test_data', 't...
import os import shutil import pytest import PIL.Image as Image import numpy as np from jina import Flow, Document cur_dir = os.path.dirname(os.path.abspath(__file__)) from ...big_transfer import BigTransferEncoder def data_generator(num_docs): for i in range(num_docs): doc = Document( uri=...
_base_ = './grid-rcnn_x101-32x4d_fpn_gn-head_2x_coco.py' model = dict( backbone=dict( type='ResNeXt', depth=101, groups=64, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, style='pytorch', init_cfg=dict( type=...
_base_ = './grid_rcnn_x101_32x4d_fpn_gn-head_2x_coco.py' model = dict( backbone=dict( type='ResNeXt', depth=101, groups=64, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, style='pytorch', init_cfg=dict( type=...
"""ReAct output parser.""" import re from typing import Tuple from llama_index.core.agent.react.types import ( ActionReasoningStep, BaseReasoningStep, ResponseReasoningStep, ) from llama_index.core.output_parsers.utils import extract_json_str from llama_index.core.types import BaseOutputParser def extra...
"""ReAct output parser.""" import re from typing import Tuple from llama_index.core.agent.react.types import ( ActionReasoningStep, BaseReasoningStep, ResponseReasoningStep, ) from llama_index.core.output_parsers.utils import extract_json_str from llama_index.core.types import BaseOutputParser def extr...
"""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...
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 langchain_core.outputs import Generation fr...
_base_ = ['faster-rcnn_r50_fpn_32xb2-1x_openimages.py'] model = dict( roi_head=dict(bbox_head=dict(num_classes=500)), test_cfg=dict(rcnn=dict(score_thr=0.01))) # dataset settings dataset_type = 'OpenImagesChallengeDataset' train_dataloader = dict( dataset=dict( type=dataset_type, ann_file=...
_base_ = ['faster_rcnn_r50_fpn_32x2_1x_openimages.py'] model = dict( roi_head=dict(bbox_head=dict(num_classes=500)), test_cfg=dict(rcnn=dict(score_thr=0.01))) # dataset settings dataset_type = 'OpenImagesChallengeDataset' train_dataloader = dict( dataset=dict( type=dataset_type, ann_file='...
import sys from typing import Any, Optional from unittest.mock import MagicMock, patch from langchain_community.embeddings import GPT4AllEmbeddings _GPT4ALL_MODEL_NAME = "all-MiniLM-L6-v2.gguf2.f16.gguf" _GPT4ALL_NTHREADS = 4 _GPT4ALL_DEVICE = "gpu" _GPT4ALL_KWARGS = {"allow_download": False} class MockEmbed4All(Ma...
import sys from typing import Any, Optional from unittest.mock import MagicMock, patch from langchain_community.embeddings import GPT4AllEmbeddings _GPT4ALL_MODEL_NAME = "all-MiniLM-L6-v2.gguf2.f16.gguf" _GPT4ALL_NTHREADS = 4 _GPT4ALL_DEVICE = "gpu" _GPT4ALL_KWARGS = {"allow_download": False} class MockEmbed4All(Ma...
"""Init file of LlamaIndex.""" __version__ = "0.12.32" import logging from logging import NullHandler from typing import Callable, Optional try: # Force pants to install eval_type_backport on 3.9 import eval_type_backport # noqa # type: ignore except ImportError: pass # response from llama_index.core....
"""Init file of LlamaIndex.""" __version__ = "0.12.31" import logging from logging import NullHandler from typing import Callable, Optional try: # Force pants to install eval_type_backport on 3.9 import eval_type_backport # noqa # type: ignore except ImportError: pass # response from llama_index.core....
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.models.utils.misc import get_box_tensor from mmdet.registry import TASK_UTILS from mmdet.structures.bbox import HorizontalBoxes, bbox2distance, distance2bbox from .base_bbox_coder import BaseBBoxCoder @TASK_UTILS.register_module() class DistancePointBBoxCoder...
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.registry import TASK_UTILS from mmdet.structures.bbox import bbox2distance, distance2bbox from .base_bbox_coder import BaseBBoxCoder @TASK_UTILS.register_module() class DistancePointBBoxCoder(BaseBBoxCoder): """Distance Point BBox coder. This coder e...
_base_ = './tood_r50_fpn_ms-2x_coco.py' model = dict( backbone=dict( type='ResNeXt', depth=101, groups=64, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, ...
_base_ = './tood_r50_fpn_mstrain_2x_coco.py' model = dict( backbone=dict( type='ResNeXt', depth=101, groups=64, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True...
from __future__ import annotations import re from typing import TYPE_CHECKING, Any if TYPE_CHECKING: import numpy as np from torch import Tensor from sentence_transformers.SentenceTransformer import SentenceTransformer class SentenceEvaluator: """ Base class for all evaluators. Notably, this cl...
from __future__ import annotations import re from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from sentence_transformers.SentenceTransformer import SentenceTransformer class SentenceEvaluator: """ Base class for all evaluators. Notably, this class introduces the ``greater_is_better`` and ``primar...
import pytest import datasets import datasets.config # Import fixture modules as plugins pytest_plugins = ["tests.fixtures.files", "tests.fixtures.hub", "tests.fixtures.fsspec"] def pytest_collection_modifyitems(config, items): # Mark tests as "unit" by default if not marked as "integration" (or already marked...
import pytest import datasets # Import fixture modules as plugins pytest_plugins = ["tests.fixtures.files", "tests.fixtures.hub", "tests.fixtures.fsspec"] def pytest_collection_modifyitems(config, items): # Mark tests as "unit" by default if not marked as "integration" (or already marked as "unit") for ite...
from typing import Any, Dict, Union from torchvision import tv_tensors from torchvision.transforms.v2 import functional as F, Transform class ConvertBoundingBoxFormat(Transform): """[BETA] Convert bounding box coordinates to the given ``format``, eg from "CXCYWH" to "XYXY". .. v2betastatus:: ConvertBounding...
from typing import Any, Dict, Union from torchvision import datapoints from torchvision.transforms.v2 import functional as F, Transform class ConvertBoundingBoxFormat(Transform): """[BETA] Convert bounding box coordinates to the given ``format``, eg from "CXCYWH" to "XYXY". .. v2betastatus:: ConvertBounding...
from .BinaryClassificationEvaluator import BinaryClassificationEvaluator from .EmbeddingSimilarityEvaluator import EmbeddingSimilarityEvaluator from .InformationRetrievalEvaluator import InformationRetrievalEvaluator from .LabelAccuracyEvaluator import LabelAccuracyEvaluator from .MSEEvaluator import MSEEvaluator from ...
from .SentenceEvaluator import SentenceEvaluator from .SimilarityFunction import SimilarityFunction from .BinaryClassificationEvaluator import BinaryClassificationEvaluator from .EmbeddingSimilarityEvaluator import EmbeddingSimilarityEvaluator from .InformationRetrievalEvaluator import InformationRetrievalEvaluator fro...
from __future__ import annotations from sentence_transformers.sparse_encoder.losses.CSRLoss import CSRLoss from sentence_transformers.sparse_encoder.losses.CSRReconstructionLoss import ( CSRReconstructionLoss, ) from sentence_transformers.sparse_encoder.losses.SparseAnglELoss import SparseAnglELoss from sentence_t...
from __future__ import annotations from sentence_transformers.sparse_encoder.losses.CSRLoss import CSRLoss from sentence_transformers.sparse_encoder.losses.CSRReconstructionLoss import ( CSRReconstructionLoss, ) from sentence_transformers.sparse_encoder.losses.SparseAnglELoss import SparseAnglELoss from sentence_t...
# Copyright (c) OpenMMLab. All rights reserved. import torch from ..builder import BBOX_SAMPLERS from .base_sampler import BaseSampler @BBOX_SAMPLERS.register_module() class RandomSampler(BaseSampler): """Random sampler. Args: num (int): Number of samples pos_fraction (float): Fraction of po...
import torch from ..builder import BBOX_SAMPLERS from .base_sampler import BaseSampler @BBOX_SAMPLERS.register_module() class RandomSampler(BaseSampler): """Random sampler. Args: num (int): Number of samples pos_fraction (float): Fraction of positive samples neg_pos_up (int, optional...
# coding=utf-8 # Copyright 2022 The HuggingFace Inc. team. # # 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...
# coding=utf-8 # Copyright 2022 The HuggingFace Inc. team. # # 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...
from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class TextDatasetReader(AbstractDatasetReader): def __init__( self, path_or_paths: Nest...
from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class TextDatasetReader(AbstractDatasetReader): def __init__( self, path_or_paths: Nest...
from typing import Any, Dict, Optional, Union import numpy as np import PIL.Image import torch from torchvision import datapoints from torchvision.transforms.v2 import functional as F, Transform from torchvision.transforms.v2.utils import is_pure_tensor class PILToTensor(Transform): """[BETA] Convert a PIL Ima...
from typing import Any, Dict, Optional, Union import numpy as np import PIL.Image import torch from torchvision import datapoints from torchvision.transforms.v2 import functional as F, Transform from torchvision.transforms.v2.utils import is_simple_tensor class PILToTensor(Transform): """[BETA] Convert a PIL I...
"""Test self-hosted embeddings.""" from typing import Any from langchain_community.embeddings import ( SelfHostedEmbeddings, SelfHostedHuggingFaceEmbeddings, SelfHostedHuggingFaceInstructEmbeddings, ) def get_remote_instance() -> Any: """Get remote instance for testing.""" import runhouse as rh ...
"""Test self-hosted embeddings.""" from typing import Any from langchain_community.embeddings import ( SelfHostedEmbeddings, SelfHostedHuggingFaceEmbeddings, SelfHostedHuggingFaceInstructEmbeddings, ) def get_remote_instance() -> Any: """Get remote instance for testing.""" import runhouse as rh ...
from typing import TYPE_CHECKING, List from docarray.typing.tensor.abstract_tensor import AbstractTensor if TYPE_CHECKING: from docarray.array import DocArrayStacked from docarray.array.abstract_array import AnyDocArray class DocArraySummary: def __init__(self, da: 'AnyDocArray'): self.da = da ...
from typing import TYPE_CHECKING, List from docarray.typing.tensor.abstract_tensor import AbstractTensor if TYPE_CHECKING: from docarray.array import DocumentArrayStacked from docarray.array.abstract_array import AnyDocumentArray class DocumentArraySummary: def __init__(self, da: 'AnyDocumentArray'): ...
""" This examples trains BERT (or any other transformer model like RoBERTa, DistilBERT etc.) for the STSbenchmark from scratch. It uses MatryoshkaLoss with the powerful CoSENTLoss to train models that perform well at output dimensions [768, 512, 256, 128, 64]. It generates sentence embeddings that can be compared using...
""" This examples trains BERT (or any other transformer model like RoBERTa, DistilBERT etc.) for the STSbenchmark from scratch. It uses MatryoshkaLoss with the powerful CoSENTLoss to train models that perform well at output dimensions [768, 512, 256, 128, 64]. It generates sentence embeddings that can be compared using...
# Copyright 2025 The HuggingFace Team, the AllenNLP library 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 # ...
# Copyright 2024 The HuggingFace Team, the AllenNLP library 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 # ...
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.registry import MODELS from mmdet.utils import ConfigType, OptConfigType, OptMultiConfig from .single_stage import SingleStageDetector @MODELS.register_module() class DDOD(SingleStageDetector): """Implementation of `DDOD <https://arxiv.org/pdf/2107.02963....
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.core import ConfigType, OptConfigType, OptMultiConfig from mmdet.registry import MODELS from .single_stage import SingleStageDetector @MODELS.register_module() class DDOD(SingleStageDetector): """Implementation of `DDOD <https://arxiv.org/pdf/2107.02963.p...
_base_ = [ '../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/openimages_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict(roi_head=dict(bbox_head=dict(num_classes=601))) # Using 32 GPUS while training optim_wrapper = dict( type='OptimWrappe...
_base_ = [ '../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/openimages_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict(roi_head=dict(bbox_head=dict(num_classes=601))) # Using 32 GPUS while training optimizer = dict(type='SGD', lr=0.08, momen...
""" Computes embeddings """ from __future__ import annotations import numpy as np from sentence_transformers import SentenceTransformer def test_encode_token_embeddings(paraphrase_distilroberta_base_v1_model: SentenceTransformer) -> None: """ Test that encode(output_value='token_embeddings') works """ ...
""" Computes embeddings """ import numpy as np from sentence_transformers import SentenceTransformer def test_encode_token_embeddings(paraphrase_distilroberta_base_v1_model: SentenceTransformer) -> None: """ Test that encode(output_value='token_embeddings') works """ model = paraphrase_distilroberta...
import sys from os import path from setuptools import find_packages from setuptools import setup if sys.version_info < (3, 7, 0): raise OSError(f'DocArray requires Python >=3.7, but yours is {sys.version}') try: pkg_name = 'docarray' libinfo_py = path.join(pkg_name, '__init__.py') libinfo_content = o...
import sys from os import path from setuptools import find_packages from setuptools import setup if sys.version_info < (3, 7, 0): raise OSError(f'DocArray requires Python >=3.7, but yours is {sys.version}') try: pkg_name = 'docarray' libinfo_py = path.join(pkg_name, '__init__.py') libinfo_content = o...
# Copyright 2015 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 2015 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...
_base_ = 'ssd300_voc0712.py' input_size = 512 model = dict( neck=dict( out_channels=(512, 1024, 512, 256, 256, 256, 256), level_strides=(2, 2, 2, 2, 1), level_paddings=(1, 1, 1, 1, 1), last_kernel_size=4), bbox_head=dict( in_channels=(512, 1024, 512, 256, 256, 256, 256),...
_base_ = 'ssd300_voc0712.py' input_size = 512 model = dict( neck=dict( out_channels=(512, 1024, 512, 256, 256, 256, 256), level_strides=(2, 2, 2, 2, 1), level_paddings=(1, 1, 1, 1, 1), last_kernel_size=4), bbox_head=dict( in_channels=(512, 1024, 512, 256, 256, 256, 256),...
_base_ = '../cascade_rcnn/cascade_rcnn_r50_fpn_1x_coco.py' norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict( # use ResNeSt img_norm data_preprocessor=dict( mean=[123.68, 116.779, 103.939], std=[58.393, 57.12, 57.375], bgr_to_rgb=True), backbone=dict( type='ResN...
_base_ = '../cascade_rcnn/cascade_rcnn_r50_fpn_1x_coco.py' norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict( backbone=dict( type='ResNeSt', stem_channels=64, depth=50, radix=2, reduction_factor=4, avg_down_stride=True, num_stages=4, out_...
_base_ = 'mask_rcnn_r50_fpn_syncbn-all_rpn-2conv_ssj_32x2_270k_coco.py' # lr steps at [0.9, 0.95, 0.975] of the maximum iterations lr_config = dict( warmup_iters=500, warmup_ratio=0.067, step=[81000, 85500, 87750]) # 90k iterations with batch_size 64 is roughly equivalent to 48 epochs runner = dict(type='IterBased...
_base_ = 'mask_rcnn_r50_fpn_syncbn-all_rpn-2conv_ssj_270k_coco.py' # lr steps at [0.9, 0.95, 0.975] of the maximum iterations lr_config = dict( warmup_iters=500, warmup_ratio=0.067, step=[81000, 85500, 87750]) # 90k iterations with batch_size 64 is roughly equivalent to 48 epochs runner = dict(type='IterBasedRunne...
from __future__ import annotations from typing import Any from langchain_core._api import deprecated from langchain_core.caches import BaseCache as BaseCache # For model_rebuild from langchain_core.callbacks import Callbacks as Callbacks # For model_rebuild from langchain_core.chat_history import BaseChatMessageHis...
from __future__ import annotations from typing import Any from langchain_core._api import deprecated from langchain_core.caches import BaseCache as BaseCache # For model_rebuild from langchain_core.callbacks import Callbacks as Callbacks # For model_rebuild from langchain_core.chat_history import BaseChatMessageHis...
"""Function components.""" from inspect import signature from typing import Any, Callable, Dict, Optional, Set, Tuple from typing_extensions import Annotated from llama_index.core.base.query_pipeline.query import ( InputKeys, OutputKeys, QueryComponent, ) from llama_index.core.bridge.pydantic import ( ...
"""Function components.""" from inspect import signature from typing import Any, Callable, Dict, Optional, Set, Tuple from typing_extensions import Annotated from llama_index.core.base.query_pipeline.query import ( InputKeys, OutputKeys, QueryComponent, ) from llama_index.core.bridge.pydantic import ( ...
import os import asyncio import cognee import pytest from llama_index.core import Document from llama_index.graph_rag.cognee import CogneeGraphRAG @pytest.mark.skipif( os.getenv("OPENAI_API_KEY") is None, reason="OPENAI_API_KEY not available to test Cognee integration", ) @pytest.mark.asyncio() async def tes...
import os import asyncio import cognee import pytest from llama_index.core import Document from llama_index.graph_rag.cognee import CogneeGraphRAG @pytest.mark.skipif( os.getenv("OPENAI_API_KEY") is None, reason="OPENAI_API_KEY not available to test Cognee integration", ) @pytest.mark.asyncio() async def tes...
# Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors. # # 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 # # U...
# Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors. # # 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 # # U...
# Copyright (c) OpenMMLab. All rights reserved. from collections import OrderedDict from mmengine.dist import get_dist_info from mmengine.hooks import Hook from torch import nn from mmdet.registry import HOOKS from ..utils.dist_utils import all_reduce_dict def get_norm_states(module: nn.Module) -> OrderedDict: ...
# Copyright (c) OpenMMLab. All rights reserved. from collections import OrderedDict from mmcv.runner import get_dist_info from mmcv.runner.hooks import Hook from torch import nn from mmdet.registry import HOOKS from ..utils.dist_utils import all_reduce_dict def get_norm_states(module): async_norm_states = Order...
# dataset settings dataset_type = 'OpenImagesDataset' data_root = 'data/OpenImages/' # file_client_args = dict( # backend='petrel', # path_mapping=dict({ # './data/': 's3://openmmlab/datasets/detection/', # 'data/': 's3://openmmlab/datasets/detection/' # })) file_client_args = dict(backend...
# dataset settings dataset_type = 'OpenImagesDataset' data_root = 'data/OpenImages/' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True, denorm_bbox=True), dict(type...
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import torch from mmcv.runner import load_checkpoint from .. import build_detector from ..builder import DETECTORS from .single_stage import SingleStageDetector @DETECTORS.register_module() class KnowledgeDistillationSingleStageDetector(SingleStageDetector)...
import mmcv import torch from mmcv.runner import load_checkpoint from .. import build_detector from ..builder import DETECTORS from .single_stage import SingleStageDetector @DETECTORS.register_module() class KnowledgeDistillationSingleStageDetector(SingleStageDetector): r"""Implementation of `Distilling the Know...
from torchaudio._internal import module_utils as _mod_utils from . import sox_utils from .download import download_asset if _mod_utils.is_sox_available(): sox_utils.set_verbosity(0) __all__ = [ "download_asset", "sox_utils", ]
from torchaudio._internal import module_utils as _mod_utils from . import sox_utils from .download import download_asset if _mod_utils.is_sox_available(): sox_utils.set_verbosity(1) __all__ = [ "download_asset", "sox_utils", ]
import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( "files", [ ["full:README.md", "dataset_infos.json"], ["empty:README.md", "dataset_infos.json"], ["dataset_infos...
import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( "dataset_info", [ DatasetInfo(), DatasetInfo( description="foo", features=Features({"a": Value(...
__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 from jina.excepts import BadDocType import librosa as lr import numpy as np import torch from .audio_clip.model impo...
__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 (c) OpenMMLab. All rights reserved. from .base_det_dataset import BaseDetDataset from .base_video_dataset import BaseVideoDataset from .cityscapes import CityscapesDataset from .coco import CocoDataset from .coco_panoptic import CocoPanopticDataset from .crowdhuman import CrowdHumanDataset from .dataset_wra...
# Copyright (c) OpenMMLab. All rights reserved. from .base_det_dataset import BaseDetDataset from .base_video_dataset import BaseVideoDataset from .cityscapes import CityscapesDataset from .coco import CocoDataset from .coco_panoptic import CocoPanopticDataset from .crowdhuman import CrowdHumanDataset from .dataset_wra...
import types from typing_extensions import TYPE_CHECKING from docarray.typing.tensor.audio import AudioNdArray from docarray.typing.tensor.embedding import AnyEmbedding, NdArrayEmbedding from docarray.typing.tensor.image import ImageNdArray, ImageTensor from docarray.typing.tensor.ndarray import NdArray from docarray...
from docarray.typing.tensor.audio import AudioNdArray from docarray.typing.tensor.embedding import AnyEmbedding, NdArrayEmbedding from docarray.typing.tensor.image import ImageNdArray, ImageTensor from docarray.typing.tensor.ndarray import NdArray from docarray.typing.tensor.tensor import AnyTensor from docarray.typing...
import numpy as np import pytest from docarray import Document, DocumentArray @pytest.mark.parametrize('nrof_docs', [10, 100, 10_000, 10_100, 20_000, 20_100]) @pytest.mark.parametrize('columns', [[('price', 'int')], {'price': 'int'}]) def test_success_get_bulk_data(start_storage, nrof_docs, columns): elastic_doc...
from docarray import Document, DocumentArray import numpy as np import pytest @pytest.mark.parametrize('nrof_docs', [10, 100, 10_000, 10_100, 20_000, 20_100]) def test_success_get_bulk_data(start_storage, nrof_docs): elastic_doc = DocumentArray( storage='elasticsearch', config={ 'n_dim...
from typing import List from llama_index.core.base.embeddings.base import BaseEmbedding from typing import Optional try: import chonkie from chonkie import AutoEmbeddings except ImportError: raise ImportError( "Could not import Autembeddings from chonkie. " "Please install it wi...
from typing import List from llama_index.core.base.embeddings.base import BaseEmbedding from typing import Optional try: import chonkie from chonkie import AutoEmbeddings except ImportError: raise ImportError( "Could not import Autembeddings from chonkie. " "Please install it wi...
from typing import Optional from llama_index.core.storage.index_store.keyval_index_store import KVIndexStore from llama_index.storage.kvstore.firestore import FirestoreKVStore class FirestoreIndexStore(KVIndexStore): """ Firestore Index store. Args: firestore_kvstore (FirestoreKVStore): Firestor...
from typing import Optional from llama_index.core.storage.index_store.keyval_index_store import KVIndexStore from llama_index.storage.kvstore.firestore import FirestoreKVStore class FirestoreIndexStore(KVIndexStore): """Firestore Index store. Args: firestore_kvstore (FirestoreKVStore): Firestore key...
_base_ = './vfnet_r50-mdconv-c3-c5_fpn_ms-2x_coco.py' model = dict( backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_e...
_base_ = './vfnet_r50_fpn_mdconv_c3-c5_mstrain_2x_coco.py' model = dict( backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), n...
from __future__ import annotations import csv import logging import os from typing import TYPE_CHECKING import torch from torch.utils.data import DataLoader from sentence_transformers.evaluation.SentenceEvaluator import SentenceEvaluator from sentence_transformers.util import batch_to_device if TYPE_CHECKING: f...
from __future__ import annotations import csv import logging import os from typing import TYPE_CHECKING import torch from torch.utils.data import DataLoader from sentence_transformers.evaluation.SentenceEvaluator import SentenceEvaluator from sentence_transformers.util import batch_to_device if TYPE_CHECKING: f...
# Copyright (c) OpenMMLab. All rights reserved. import sys from unittest import TestCase import torch.cuda import mmengine from mmengine.utils.dl_utils import collect_env from mmengine.utils.dl_utils.parrots_wrapper import _get_cuda_home class TestCollectEnv(TestCase): def test_get_cuda_home(self): CUD...
# Copyright (c) OpenMMLab. All rights reserved. import sys from unittest import TestCase import torch.cuda import mmengine from mmengine.utils.dl_utils import collect_env from mmengine.utils.dl_utils.parrots_wrapper import _get_cuda_home class TestCollectEnv(TestCase): def test_get_cuda_home(self): CUD...
import os import shutil import pytest import torch import torchaudio class GreedyCTCDecoder(torch.nn.Module): def __init__(self, labels, blank: int = 0): super().__init__() self.blank = blank self.labels = labels def forward(self, logits: torch.Tensor) -> str: """Given a sequ...
import pytest import torch import torchaudio class GreedyCTCDecoder(torch.nn.Module): def __init__(self, labels, blank: int = 0): super().__init__() self.blank = blank self.labels = labels def forward(self, logits: torch.Tensor) -> str: """Given a sequence logits over labels, ...
# Copyright 2020 The HuggingFace Authors. # # 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 agreed to...
import sys from collections.abc import Mapping import numpy as np import pyarrow as pa from .. import config from ..utils.py_utils import map_nested from .formatting import Formatter class NumpyFormatter(Formatter[Mapping, np.ndarray, Mapping]): def __init__(self, features=None, **np_array_kwargs): supe...
""" 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...
# Copyright (c) OpenMMLab. All rights reserved. from mmengine.config import ConfigDict from mmdet.registry import MODELS from mmdet.utils import OptConfigType, OptMultiConfig from .two_stage import TwoStageDetector @MODELS.register_module() class PointRend(TwoStageDetector): """PointRend: Image Segmentation as R...
# Copyright (c) OpenMMLab. All rights reserved. from mmengine.config import ConfigDict from mmdet.core.utils import OptConfigType, OptMultiConfig from mmdet.registry import MODELS from .two_stage import TwoStageDetector @MODELS.register_module() class PointRend(TwoStageDetector): """PointRend: Image Segmentation...
from pathlib import Path from typing import Any, Callable, Optional, Union from .folder import default_loader, ImageFolder from .utils import download_and_extract_archive, verify_str_arg class Country211(ImageFolder): """`The Country211 Data Set <https://github.com/openai/CLIP/blob/main/data/country211.md>`_ fro...
from pathlib import Path from typing import Callable, Optional, Union from .folder import ImageFolder from .utils import download_and_extract_archive, verify_str_arg class Country211(ImageFolder): """`The Country211 Data Set <https://github.com/openai/CLIP/blob/main/data/country211.md>`_ from OpenAI. This d...
from typing import List import torch import torchaudio.prototype.transforms as T from torch.autograd import gradcheck, gradgradcheck from torchaudio_unittest.common_utils import get_spectrogram, get_whitenoise, TestBaseMixin class Autograd(TestBaseMixin): def assert_grad( self, transform: torch.n...
from typing import List import torch import torchaudio.prototype.transforms as T from torch.autograd import gradcheck, gradgradcheck from torchaudio_unittest.common_utils import get_spectrogram, get_whitenoise, nested_params, TestBaseMixin class Autograd(TestBaseMixin): def assert_grad( self, tra...
import os import urllib import numpy as np import PIL import pytest from pydantic.tools import parse_obj_as, schema_json_of from docarray.document.io.json import orjson_dumps from docarray.typing import ImageUrl CUR_DIR = os.path.dirname(os.path.abspath(__file__)) PATH_TO_IMAGE_DATA = os.path.join(CUR_DIR, '..', '.....
import os import urllib import numpy as np import PIL import pytest from pydantic.tools import parse_obj_as from docarray.typing import ImageUrl CUR_DIR = os.path.dirname(os.path.abspath(__file__)) PATH_TO_IMAGE_DATA = os.path.join(CUR_DIR, '..', '..', '..', 'toydata', 'image-data') IMAGE_PATHS = { 'png': os.pat...
from docarray.documents.mesh.mesh_3d import Mesh3D from docarray.documents.mesh.vertices_and_faces import VerticesAndFaces __all__ = ['Mesh3D', 'VerticesAndFaces']
from docarray.documents.mesh.mesh_3d import Mesh3D __all__ = ['Mesh3D']
import json from typing import Any, Type, TypeGuard, TypeVar, overload import jsonschema from fastapi.encoders import jsonable_encoder from pydantic import BaseModel from .type import type_match def to_dict(data) -> dict: if isinstance(data, BaseModel): data = data.model_dump() return jsonable_encod...
import json from typing import Any, Type, TypeGuard, TypeVar, overload import jsonschema from fastapi.encoders import jsonable_encoder from pydantic import BaseModel from .type import type_match def to_dict(data) -> dict: if isinstance(data, BaseModel): data = data.model_dump() return jsonable_encod...
from typing import Any, Optional, Union, cast from langchain_core.messages import AIMessage, ToolCall from langchain_core.messages.tool import tool_call from langchain_core.output_parsers import BaseGenerationOutputParser from langchain_core.outputs import ChatGeneration, Generation from pydantic import BaseModel, Con...
from typing import Any, Optional, Union, cast from langchain_core.messages import AIMessage, ToolCall from langchain_core.messages.tool import tool_call from langchain_core.output_parsers import BaseGenerationOutputParser from langchain_core.outputs import ChatGeneration, Generation from pydantic import BaseModel, Con...
# Copyright 2021 The HuggingFace Authors. # # 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 agreed to...
# Copyright 2021 The HuggingFace Authors. # # 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 agreed to...
# Copyright (c) OpenMMLab. All rights reserved. from functools import partial from typing import Optional import torch TORCH_VERSION = torch.__version__ def is_rocm_pytorch() -> bool: """Check whether the PyTorch is compiled on ROCm.""" is_rocm = False if TORCH_VERSION != 'parrots': try: ...
# Copyright (c) OpenMMLab. All rights reserved. from functools import partial from typing import Optional import torch TORCH_VERSION = torch.__version__ def is_rocm_pytorch() -> bool: """Check whether the PyTorch is compiled on ROCm.""" is_rocm = False if TORCH_VERSION != 'parrots': try: ...
_base_ = [ '../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # please install mmcls>=0.20.0 # import mmcls.models to trigger register_module in mmcls custom_imports = dict(imports=['mmcls.models'], allow_f...
_base_ = [ '../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # please install mmcls>=0.20.0 # import mmcls.models to trigger register_module in mmcls custom_imports = dict(imports=['mmcls.models'], allow_f...
default_scope = 'mmdet' default_hooks = dict( timer=dict(type='IterTimerHook'), logger=dict(type='LoggerHook', interval=50), param_scheduler=dict(type='ParamSchedulerHook'), checkpoint=dict(type='CheckpointHook', interval=1), sampler_seed=dict(type='DistSamplerSeedHook'), visualization=dict(typ...
default_scope = 'mmdet' default_hooks = dict( optimizer=dict(type='OptimizerHook', grad_clip=None), timer=dict(type='IterTimerHook'), logger=dict(type='LoggerHook', interval=50), param_scheduler=dict(type='ParamSchedulerHook'), checkpoint=dict(type='CheckpointHook', interval=1), sampler_seed=di...
"""PlaygroundsSubgraphConnectorToolSpec.""" from typing import Optional, Union import requests from llama_index.tools.graphql.base import GraphQLToolSpec class PlaygroundsSubgraphConnectorToolSpec(GraphQLToolSpec): """ Connects to subgraphs on The Graph's decentralized network via the Playgrounds API. ...
"""PlaygroundsSubgraphConnectorToolSpec.""" from typing import Optional, Union import requests from llama_index.tools.graphql.base import GraphQLToolSpec class PlaygroundsSubgraphConnectorToolSpec(GraphQLToolSpec): """ Connects to subgraphs on The Graph's decentralized network via the Playgrounds API. ...
_base_ = './ga-retinanet_r101-caffe_fpn_1x_coco.py' train_pipeline = [ dict( type='LoadImageFromFile', file_client_args={{_base_.file_client_args}}), dict(type='LoadAnnotations', with_bbox=True), dict( type='RandomResize', scale=[(1333, 480), (1333, 960)], keep_ratio=True), ...
_base_ = './ga_retinanet_r101_caffe_fpn_1x_coco.py' train_pipeline = [ dict( type='LoadImageFromFile', file_client_args={{_base_.file_client_args}}), dict(type='LoadAnnotations', with_bbox=True), dict( type='RandomResize', scale=[(1333, 480), (1333, 960)], keep_ratio=True), ...
# Copyright (c) OpenMMLab. All rights reserved. import unittest from unittest import TestCase import torch from parameterized import parameterized from mmdet import * # noqa from mmdet.structures import DetDataSample from mmdet.testing import demo_mm_inputs, get_detector_cfg from mmdet.utils import register_all_modu...
# Copyright (c) OpenMMLab. All rights reserved. import unittest from unittest import TestCase import torch from parameterized import parameterized from mmdet import * # noqa from mmdet.structures import DetDataSample from mmdet.testing import demo_mm_inputs, get_detector_cfg from mmdet.utils import register_all_modu...
from keras.src.backend.common.name_scope import name_scope from keras.src.backend.jax import core from keras.src.backend.jax import distribution_lib from keras.src.backend.jax import image from keras.src.backend.jax import linalg from keras.src.backend.jax import math from keras.src.backend.jax import nn from keras.src...
from keras.src.backend.jax import core from keras.src.backend.jax import distribution_lib from keras.src.backend.jax import image from keras.src.backend.jax import linalg from keras.src.backend.jax import math from keras.src.backend.jax import nn from keras.src.backend.jax import numpy from keras.src.backend.jax import...
import numpy as np import pytest from keras.src import testing from keras.src.layers.activations import elu class ELUTest(testing.TestCase): def test_config(self): elu_layer = elu.ELU() self.run_class_serialization_test(elu_layer) @pytest.mark.requires_trainable_backend def test_elu(self...
import numpy as np import pytest from keras.src import testing from keras.src.layers.activations import elu class ELUTest(testing.TestCase): def test_config(self): elu_layer = elu.ELU() self.run_class_serialization_test(elu_layer) @pytest.mark.requires_trainable_backend def test_elu(self...
from typing import TYPE_CHECKING, Any, Type, TypeVar, Union, cast import numpy as np if TYPE_CHECKING: from pydantic.fields import ModelField from pydantic import BaseConfig from docarray.document.base_node import BaseNode from docarray.proto import NdArrayProto, NodeProto T = TypeVar('T', bound='Tensor') ...
from typing import Union, TypeVar, Any, TYPE_CHECKING, Type, cast import numpy as np if TYPE_CHECKING: from pydantic.fields import ModelField from pydantic import BaseConfig from docarray.document.base_node import BaseNode from docarray.proto import NdArrayProto, NodeProto T = TypeVar('T', bound='Tensor') ...
import io from typing import TYPE_CHECKING, Any, Tuple, Type, TypeVar import numpy as np from pydantic import parse_obj_as from pydantic.validators import bytes_validator from docarray.typing.abstract_type import AbstractType from docarray.typing.proto_register import _register_proto if TYPE_CHECKING: from pydan...
import io from typing import TYPE_CHECKING, Any, Tuple, Type, TypeVar import numpy as np from pydantic import parse_obj_as from pydantic.validators import bytes_validator from docarray.typing.abstract_type import AbstractType from docarray.typing.proto_register import _register_proto if TYPE_CHECKING: from pydan...
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, Literal from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator if TYPE_CHECKING: import numpy as np from torch import Tensor from sentence_transformers.similarity_functions import SimilarityFuncti...
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, Literal from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator if TYPE_CHECKING: import numpy as np from torch import Tensor from sentence_transformers.similarity_functions import SimilarityFuncti...