input
stringlengths
33
5k
output
stringlengths
32
5k
# Copyright 2024 The HuggingFace Inc. 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 appl...
# Copyright 2024 The HuggingFace Inc. 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 appl...
import warnings from typing import List, Optional import torchaudio from . import utils # TODO: Once legacy global backend is removed, move this to torchaudio.__init__ def _init_backend(): torchaudio.info = utils.get_info_func() torchaudio.load = utils.get_load_func() torchaudio.save = utils.get_save_fu...
from .utils import get_info_func, get_load_func, get_save_func info = get_info_func() load = get_load_func() save = get_save_func()
from typing import Any, Optional, Type, TypeVar, Union import numpy as np from docarray.base_document import BaseDocument from docarray.typing import AnyEmbedding, AnyTensor, PointCloud3DUrl from docarray.typing.tensor.abstract_tensor import AbstractTensor from docarray.utils.misc import is_tf_available, is_torch_ava...
from typing import Any, Optional, Type, TypeVar, Union import numpy as np from docarray.base_document import BaseDocument from docarray.typing import AnyEmbedding, AnyTensor, PointCloud3DUrl from docarray.typing.tensor.abstract_tensor import AbstractTensor from docarray.utils.misc import is_torch_available torch_ava...
""" Using rmm on a single node device ================================= """ import rmm from sklearn.datasets import make_classification import xgboost as xgb # Initialize RMM pool allocator rmm.reinitialize(pool_allocator=True) # Optionally force XGBoost to use RMM for all GPU memory allocation, see ./README.md # xg...
""" Using rmm on a single node device ================================= """ import rmm from sklearn.datasets import make_classification import xgboost as xgb # Initialize RMM pool allocator rmm.reinitialize(pool_allocator=True) # Optionally force XGBoost to use RMM for all GPU memory allocation, see ./README.md # xgb...
import logging from datasets import load_dataset from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseTripletEvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Load a model model = SparseEncoder("naver/splade-cocondenser-ensembledis...
import logging from datasets import load_dataset from sentence_transformers import SparseEncoder from sentence_transformers.sparse_encoder.evaluation import SparseTripletEvaluator logging.basicConfig(format="%(message)s", level=logging.INFO) # Load a model model = SparseEncoder("naver/splade-cocondenser-ensembledis...
from typing import TYPE_CHECKING from .github import GithubWebhooksManager from .slant3d import Slant3DWebhooksManager if TYPE_CHECKING: from ..providers import ProviderName from .base import BaseWebhooksManager # --8<-- [start:WEBHOOK_MANAGERS_BY_NAME] WEBHOOK_MANAGERS_BY_NAME: dict["ProviderName", type["Ba...
from typing import TYPE_CHECKING from .github import GithubWebhooksManager from .slant3d import Slant3DWebhooksManager if TYPE_CHECKING: from .base import BaseWebhooksManager # --8<-- [start:WEBHOOK_MANAGERS_BY_NAME] WEBHOOK_MANAGERS_BY_NAME: dict[str, type["BaseWebhooksManager"]] = { handler.PROVIDER_NAME: ...
from llama_index.vector_stores.redis.base import RedisVectorStore, TokenEscaper __all__ = ["RedisVectorStore", "TokenEscaper"]
from llama_index.vector_stores.redis.base import RedisVectorStore __all__ = ["RedisVectorStore"]
from __future__ import annotations from .MLMTransformer import MLMTransformer from .SparseAutoEncoder import SparseAutoEncoder from .SparseStaticEmbedding import SparseStaticEmbedding from .SpladePooling import SpladePooling __all__ = ["SparseAutoEncoder", "MLMTransformer", "SpladePooling", "SparseStaticEmbedding"]
from __future__ import annotations from .IDF import IDF from .MLMTransformer import MLMTransformer from .SparseAutoEncoder import SparseAutoEncoder from .SpladePooling import SpladePooling __all__ = ["SparseAutoEncoder", "MLMTransformer", "SpladePooling", "IDF"]
from typing import Optional from docarray import Document, DocumentArray from pydantic import BaseModel from uvicorn import Config, Server from jina import Gateway, __default_host__ from jina.clients.request import request_generator class DummyResponseModel(BaseModel): arg1: Optional[str] arg2: Optional[str...
from typing import Optional from docarray import Document, DocumentArray from pydantic import BaseModel from uvicorn import Config, Server from jina import Gateway, __default_host__ from jina.clients.request import request_generator class DummyResponseModel(BaseModel): arg1: Optional[str] arg2: Optional[str...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.tools import E2BDataAnalysisTool from langchain_community.tools.e2b_data_analysis.tool import ( E2BDataAnalysisToolArguments, UploadedFile, ) # Create a way to dynam...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.tools import E2BDataAnalysisTool from langchain_community.tools.e2b_data_analysis.tool import ( E2BDataAnalysisToolArguments, UploadedFile, ) # Create a way to dynam...
import csv import os from pathlib import Path from typing import Dict, List, Tuple, Union import torchaudio from torch import Tensor from torch.utils.data import Dataset def load_commonvoice_item( line: List[str], header: List[str], path: str, folder_audio: str, ext_audio: str ) -> Tuple[Tensor, int, Dict[str, s...
import csv import os from pathlib import Path from typing import Dict, List, Tuple, Union import torchaudio from torch import Tensor from torch.utils.data import Dataset def load_commonvoice_item( line: List[str], header: List[str], path: str, folder_audio: str, ext_audio: str ) -> Tuple[Tensor, int, Dict[str, s...
# 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/' # file_client_args = dict( # backend='petrel', # path_mapping=dict({ # './data/': 's3://openmmlab/datasets/detection/', # 'data/': 's3://openmmlab/datasets/detection/' # })) file_client_args = dict(backend...
# Copyright (c) OpenMMLab. All rights reserved. import math import torch from torch.utils.data import DistributedSampler as _DistributedSampler from mmdet.core.utils import sync_random_seed from mmdet.registry import DATA_SAMPLERS from mmdet.utils import get_device @DATA_SAMPLERS.register_module() class Distributed...
# Copyright (c) OpenMMLab. All rights reserved. import math import torch from torch.utils.data import DistributedSampler as _DistributedSampler from mmdet.core.utils import sync_random_seed from mmdet.utils import get_device class DistributedSampler(_DistributedSampler): def __init__(self, dat...
import pytest from backend.data import db from backend.executor.scheduler import SchedulerClient from backend.server.model import CreateGraph from backend.usecases.sample import create_test_graph, create_test_user from backend.util.service import get_service_client from backend.util.test import SpinTestServer @pytes...
import pytest from backend.data import db from backend.executor.scheduler import SchedulerClient from backend.server.model import CreateGraph from backend.usecases.sample import create_test_graph, create_test_user from backend.util.service import get_service_client from backend.util.test import SpinTestServer @pytes...
import multiprocessing import pytest from jina import Client from jina.parsers import set_gateway_parser from jina.serve.runtimes.asyncio import AsyncNewLoopRuntime from jina.serve.runtimes.gateway import GatewayRuntime from jina.serve.runtimes.worker import WorkerRuntime from tests.helper import _generate_pod_args ...
import multiprocessing import pytest from jina import Client from jina.parsers import set_gateway_parser, set_pod_parser from jina.serve.runtimes.asyncio import AsyncNewLoopRuntime from jina.serve.runtimes.gateway import GatewayRuntime from jina.serve.runtimes.worker import WorkerRuntime def _create_worker_runtime(...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.chat_message_histories import FileChatMessageHistory # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling op...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.chat_message_histories import FileChatMessageHistory # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling op...
# Copyright (c) OpenMMLab. All rights reserved. from .onnx_helper import (add_dummy_nms_for_onnx, dynamic_clip_for_onnx, get_k_for_topk) from .pytorch2onnx import (build_model_from_cfg, generate_inputs_and_wrap_model, preprocess_example_inp...
from .onnx_helper import (add_dummy_nms_for_onnx, dynamic_clip_for_onnx, get_k_for_topk) from .pytorch2onnx import (build_model_from_cfg, generate_inputs_and_wrap_model, preprocess_example_input) __all__ = [ 'build_model_from_cfg', 'ge...
__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...
from keras.src import backend def is_in_jax_tracing_scope(x=None): if backend.backend() == "jax": if x is None: x = backend.numpy.ones(()) for c in x.__class__.__mro__: if c.__name__ == "Tracer" and c.__module__.startswith("jax"): return True return Fals...
from keras.src import backend def is_in_jax_tracing_scope(x=None): if backend.backend() == "jax": if x is None: x = backend.numpy.ones(()) if x.__class__.__name__ == "DynamicJaxprTracer": return True return False
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import os from typing import Dict import pytest import torch import numpy as np from torchvision.models.mobilenetv2 import model_urls from PIL import Image from jina import DocumentArray, Document @pytest.fixture(...
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import os from typing import Dict import pytest import torch import numpy as np from torchvision.models.mobilenetv2 import model_urls from PIL import Image from jina import DocumentArray, Document @pytest.fixture(...
from ._dsp import ( adsr_envelope, exp_sigmoid, extend_pitch, filter_waveform, frequency_impulse_response, oscillator_bank, sinc_impulse_response, ) from ._rir import simulate_rir_ism from .functional import barkscale_fbanks, chroma_filterbank __all__ = [ "adsr_envelope", "exp_sigm...
from ._dsp import ( adsr_envelope, exp_sigmoid, extend_pitch, filter_waveform, frequency_impulse_response, oscillator_bank, sinc_impulse_response, ) from ._rir import simulate_rir_ism from .functional import barkscale_fbanks __all__ = [ "adsr_envelope", "exp_sigmoid", "barkscal...
from typing import ( TYPE_CHECKING, TypeVar, Sequence, List, Dict, Optional, ) import numpy as np from .... import Document, DocumentArray from ....math import ndarray from ....math.helper import EPSILON from ....math.ndarray import to_numpy_array from ....score import NamedScore if TYPE_CHEC...
from typing import ( TYPE_CHECKING, TypeVar, Sequence, List, ) import numpy as np from .... import Document, DocumentArray from ....math import ndarray from ....math.helper import EPSILON from ....math.ndarray import to_numpy_array from ....score import NamedScore if TYPE_CHECKING: import tensorf...
from typing import Optional import numpy as np import pytest import torch from docarray import DocumentArray from docarray.base_document import BaseDocument from docarray.typing import NdArray, TorchTensor @pytest.mark.proto def test_proto_simple(): class CustomDoc(BaseDocument): text: str doc = Cu...
from typing import Optional import numpy as np import torch from docarray import DocumentArray from docarray.base_document import BaseDocument from docarray.typing import NdArray, TorchTensor def test_proto_simple(): class CustomDoc(BaseDocument): text: str doc = CustomDoc(text='hello') Custom...
# Copyright (c) OpenMMLab. All rights reserved. from .augment_wrappers import AutoAugment, RandAugment from .colorspace import (AutoContrast, Brightness, Color, ColorTransform, Contrast, Equalize, Invert, Posterize, Sharpness, Solarize, SolarizeAdd) from .formatting imp...
# Copyright (c) OpenMMLab. All rights reserved. from .augment_wrappers import AutoAugment, RandAugment from .colorspace import (AutoContrast, Brightness, Color, ColorTransform, Contrast, Equalize, Invert, Posterize, Sharpness, Solarize, SolarizeAdd) from .formatting imp...
import multiprocessing import time import grpc import pytest import requests from jina import __version__ from jina.constants import __jina_env__ from jina.proto import jina_pb2, jina_pb2_grpc from jina.serve.runtimes.asyncio import AsyncNewLoopRuntime from jina.serve.runtimes.servers import BaseServer from jina.serv...
import multiprocessing import time import grpc import pytest import requests from jina import __version__ from jina.constants import __jina_env__ from jina.proto import jina_pb2, jina_pb2_grpc from jina.serve.runtimes.asyncio import AsyncNewLoopRuntime from jina.serve.runtimes.worker import WorkerRuntime from tests.h...
# coding=utf-8 # Copyright 2025 The HuggingFace Team Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a clone of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
# coding=utf-8 # Copyright 2024 The HuggingFace Team Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a clone of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.models.utils import ResLayer, SimplifiedBasicBlock from mmdet.registry import MODELS from .fused_semantic_head import FusedSemanticHead @MODELS.register_module() class SCNetSemanticHead(FusedSemanticHead): """Mask head for `SCNet <https://arxiv.org/abs/20...
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.models.utils import ResLayer, SimplifiedBasicBlock from mmdet.registry import MODELS from .fused_semantic_head import FusedSemanticHead @MODELS.register_module() class SCNetSemanticHead(FusedSemanticHead): """Mask head for `SCNet <https://arxiv.org/abs/20...
"""python scripts/update_mypy_ruff.py""" import glob import tomllib from pathlib import Path import toml import subprocess import re ROOT_DIR = Path(__file__).parents[1] def main(): for path in glob.glob(str(ROOT_DIR / "libs/**/pyproject.toml"), recursive=True): if "libs/cli/" in path: cont...
"""python scripts/update_mypy_ruff.py""" import glob import tomllib from pathlib import Path import toml import subprocess import re ROOT_DIR = Path(__file__).parents[1] def main(): for path in glob.glob(str(ROOT_DIR / "libs/**/pyproject.toml"), recursive=True): if "libs/cli/" in path: cont...
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...
from typing import Any, Union from langchain_core.utils.json import parse_json_markdown from langchain.evaluation.schema import StringEvaluator class JsonSchemaEvaluator(StringEvaluator): """An evaluator that validates a JSON prediction against a JSON schema reference. This evaluator checks if a given JSON...
from typing import Any, Union from langchain_core.utils.json import parse_json_markdown from langchain.evaluation.schema import StringEvaluator class JsonSchemaEvaluator(StringEvaluator): """An evaluator that validates a JSON prediction against a JSON schema reference. This evaluator checks if a given JSON...
_base_ = './mask2former_r50_8xb2-lsj-50e_coco-panoptic.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
_base_ = './mask2former_r50_lsj_8x2_50e_coco-panoptic.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
__all__ = ['reduce', 'reduce_all'] from typing import Dict, List, Optional from docarray import DocList def reduce( left: DocList, right: DocList, left_id_map: Optional[Dict] = None ) -> 'DocList': """ Reduces left and right DocList into one DocList in-place. Changes are applied to the left DocList....
__all__ = ['reduce', 'reduce_all'] from typing import Dict, List, Optional from docarray import DocList def reduce( left: DocList, right: DocList, left_id_map: Optional[Dict] = None ) -> 'DocList': """ Reduces left and right DocList into one DocList in-place. Changes are applied to the left DocList....
import pytest from jina import Flow num_calls = 0 @pytest.fixture(scope='function', autouse=True) def patched_path_import(mocker): from jina.importer import _path_import def _wrapped_path_import(absolute_path: str): global num_calls num_calls += 1 assert num_calls < 2 return...
import pytest from jina import Flow num_calls = 0 @pytest.fixture(scope='function', autouse=True) def patched_path_import(mocker): from jina.importer import _path_import def _wrapped_path_import(absolute_path: str): global num_calls num_calls += 1 assert num_calls < 2 return ...
from datasets import Dataset from sentence_transformers.sparse_encoder import SparseEncoder, SparseEncoderTrainer, losses # Initialize the SPLADE model model = SparseEncoder("naver/splade-cocondenser-ensembledistil") guide = SparseEncoder("prithivida/Splade_PP_en_v1") train_dataset = Dataset.from_dict( { ...
from datasets import Dataset from sentence_transformers.sparse_encoder import ( MLMTransformer, SparseEncoder, SparseEncoderTrainer, SparseGISTEmbedLoss, SpladePooling, ) # Initialize the SPLADE model model_name = "naver/splade-cocondenser-ensembledistil" model = SparseEncoder( modules=[ ...
import importlib import pytest from fastapi.testclient import TestClient from ...utils import needs_py39 @pytest.fixture( name="client", params=[ "tutorial008b", "tutorial008b_an", pytest.param("tutorial008b_an_py39", marks=needs_py39), ], ) def get_client(request: pytest.Fixture...
from fastapi.testclient import TestClient from docs_src.dependencies.tutorial008b import app client = TestClient(app) def test_get_no_item(): response = client.get("/items/foo") assert response.status_code == 404, response.text assert response.json() == {"detail": "Item not found"} def test_owner_erro...
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.registry import TASK_UTILS from mmdet.structures.bbox import (HorizontalBoxes, bbox2distance, distance2bbox, get_box_tensor) from .base_bbox_coder import BaseBBoxCoder @TASK_UTILS.register_module() class DistancePointBBoxCod...
# 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...
import os from jina import Executor, requests, DocumentArray import socket class TestExecutor(Executor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) from jina.logging.logger import JinaLogger self.logger = JinaLogger(self.__class__.__name__) self._name ...
import os from jina import Executor, requests, DocumentArray import socket class TestExecutor(Executor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) from jina.logging.logger import JinaLogger self.logger = JinaLogger(self.__class__.__name__) self._name ...
from typing import Union, Iterable, Dict, List import warnings from docarray.array.storage.base.seqlike import BaseSequenceLikeMixin from docarray import Document class SequenceLikeMixin(BaseSequenceLikeMixin): """Implement sequence-like methods for DocumentArray with Elastic as storage""" def __eq__(self, ...
from typing import Union, Iterable, Dict, List import warnings from docarray.array.storage.base.seqlike import BaseSequenceLikeMixin from docarray import Document class SequenceLikeMixin(BaseSequenceLikeMixin): """Implement sequence-like methods for DocumentArray with Elastic as storage""" def __eq__(self, ...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.utils.image_utils import array_to_img as array_to_img from keras.src.utils.image_utils import img_to_array as img_to_array from keras.src.utils.image_utils import load_img as load_img...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.utils.image_utils import array_to_img from keras.src.utils.image_utils import img_to_array from keras.src.utils.image_utils import load_img from keras.src.utils.image_utils import sav...
from typing import Any, Dict, List, Optional, Sequence, Type, Union import PIL.Image import torch from torchvision import datapoints from torchvision.prototype.datapoints import Label, OneHotLabel from torchvision.transforms.v2 import functional as F, Transform from torchvision.transforms.v2._utils import _FillType, ...
from typing import Any, Dict, List, Optional, Sequence, Type, Union import PIL.Image import torch from torchvision import datapoints from torchvision.prototype.datapoints import Label, OneHotLabel from torchvision.transforms.v2 import functional as F, Transform from torchvision.transforms.v2._utils import _FillType, ...
from functools import lru_cache import numpy as np import torch try: import triton import triton.language as tl except ImportError: raise RuntimeError("triton import failed; try `pip install --pre triton`") @triton.jit def dtw_kernel( cost, trace, x, x_stride, cost_stride, trace_stride, N, M, BLOCK_...
import math import numpy as np import torch from functools import lru_cache try: import triton import triton.language as tl except ImportError: raise RuntimeError("triton import failed; try `pip install --pre triton`") @triton.jit def dtw_kernel(cost, trace, x, x_stride, cost_stride, trace_stride, N, M,...
_base_ = '../_base_/default_runtime.py' # dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' image_size = (1024, 1024) file_client_args = dict(backend='disk') # comment out the code below to use different file client # file_client_args = dict( # backend='petrel', # path_mapping=dict({ # ...
_base_ = '../_base_/default_runtime.py' # dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' image_size = (1024, 1024) file_client_args = dict(backend='disk') # comment out the code below to use different file client # file_client_args = dict( # backend='petrel', # path_mapping=dict({ # ...
# Copyright 2025 The HuggingFace Inc. 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 appl...
# Copyright 2025 The HuggingFace Inc. 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 appl...
# Copyright (c) OpenMMLab. All rights reserved. from .collect_env import collect_env from .logger import get_root_logger __all__ = ['get_root_logger', 'collect_env']
from .collect_env import collect_env from .logger import get_root_logger __all__ = ['get_root_logger', 'collect_env']
"""Prompts for comparing the outputs of two models for a given question. This prompt is used to compare two responses and evaluate which one best follows the instructions and answers the question. The prompt is based on the paper from Zheng, et. al. https://arxiv.org/abs/2306.05685 """ # noqa: E501 from langchain_co...
"""Prompts for comparing the outputs of two models for a given question. This prompt is used to compare two responses and evaluate which one best follows the instructions and answers the question. The prompt is based on the paper from Zheng, et. al. https://arxiv.org/abs/2306.05685 """ # flake8: noqa from langchain_c...
from torchaudio import ( # noqa: F401 _extension, compliance, datasets, functional, io, kaldi_io, models, pipelines, sox_effects, transforms, utils, ) from torchaudio.backend import get_audio_backend, list_audio_backends, set_audio_backend try: from .version import __ve...
from torchaudio import _extension # noqa: F401 from torchaudio import ( io, compliance, datasets, functional, models, pipelines, kaldi_io, utils, sox_effects, transforms, ) from torchaudio.backend import ( list_audio_backends, get_audio_backend, set_audio_backend, ) ...
# 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...
# Copyright (c) OpenMMLab. All rights reserved. import warnings from mmdet.registry import TASK_UTILS MATCH_COST = TASK_UTILS def build_match_cost(cfg, default_args=None): """Builder of IoU calculator.""" warnings.warn('``build_match_cost`` would be deprecated soon, please use ' '``mmdet.r...
# Copyright (c) OpenMMLab. All rights reserved. from mmcv.utils import Registry, build_from_cfg MATCH_COST = Registry('Match Cost') def build_match_cost(cfg, default_args=None): """Builder of IoU calculator.""" return build_from_cfg(cfg, MATCH_COST, default_args)
import csv import os from pathlib import Path from typing import Dict, List, Tuple, Union import torchaudio from torch import Tensor from torch.utils.data import Dataset def load_commonvoice_item( line: List[str], header: List[str], path: str, folder_audio: str, ext_audio: str ) -> Tuple[Tensor, int, Dict[str, s...
import csv import os from pathlib import Path from typing import List, Dict, Tuple, Union import torchaudio from torch import Tensor from torch.utils.data import Dataset def load_commonvoice_item( line: List[str], header: List[str], path: str, folder_audio: str, ext_audio: str ) -> Tuple[Tensor, int, Dict[str, s...
# 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...
# Copyright (c) OpenMMLab. All rights reserved. import time import pytest import mmengine def test_timer_init(): timer = mmengine.Timer(start=False) assert not timer.is_running timer.start() assert timer.is_running timer = mmengine.Timer() assert timer.is_running def test_timer_run(): ...
# Copyright (c) OpenMMLab. All rights reserved. import time import pytest import mmengine def test_timer_init(): timer = mmengine.Timer(start=False) assert not timer.is_running timer.start() assert timer.is_running timer = mmengine.Timer() assert timer.is_running def test_timer_run(): ...
import os import pytest import requests from jina import Flow from tests.helper import ( ProcessExecutor, _validate_custom_gateway_process, _validate_dummy_custom_gateway_response, ) from tests.unit.yaml.dummy_gateway import DummyGateway from tests.unit.yaml.dummy_gateway_get_streamer import DummyGatewayG...
import os import pytest import requests from jina import Flow from tests.helper import ( ProcessExecutor, _validate_custom_gateway_process, _validate_dummy_custom_gateway_response, ) from tests.unit.yaml.dummy_gateway import DummyGateway cur_dir = os.path.dirname(os.path.abspath(__file__)) _dummy_gateway...
from typing import Any, Optional, Type, TypeVar, Union import numpy as np from docarray.base_document import BaseDocument from docarray.typing import AnyEmbedding, ImageBytes, ImageUrl from docarray.typing.tensor.abstract_tensor import AbstractTensor from docarray.typing.tensor.image.image_tensor import ImageTensor ...
from typing import Any, Optional, Type, TypeVar, Union import numpy as np from docarray.base_document import BaseDocument from docarray.typing import AnyEmbedding, AnyTensor, ImageUrl from docarray.typing.tensor.abstract_tensor import AbstractTensor T = TypeVar('T', bound='Image') try: import torch torch_a...
"""Dappier Real Time Search tool spec.""" import os from typing import Optional from llama_index.core.tools.tool_spec.base import BaseToolSpec class DappierRealTimeSearchToolSpec(BaseToolSpec): """Dappier Real Time Search tool spec.""" spec_functions = ["search_real_time_data", "search_stock_market_data"] ...
"""Dappier Real Time Search tool spec.""" import os from typing import Optional from llama_index.core.tools.tool_spec.base import BaseToolSpec class DappierRealTimeSearchToolSpec(BaseToolSpec): """Dappier Real Time Search tool spec.""" spec_functions = ["search_real_time_data", "search_stock_market_data"] ...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import subprocess import numpy as np import pytest from jina import Document, DocumentArray, Flow from ...audioclip_image import AudioCLIPImageEncoder @pytest.mark.parametrize("request_size", [1, 10, 50, 100]...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from typing import Callable import numpy as np import pytest from jina import Document, DocumentArray, Flow from ...audioclip_image import AudioCLIPImageEncoder @pytest.mark.parametrize("request_size", [1, 10...
"""Loads word documents.""" import os import tempfile from abc import ABC from pathlib import Path from typing import Any, List, Union from urllib.parse import urlparse import requests from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader from langchain_commun...
"""Loads word documents.""" import os import tempfile from abc import ABC from pathlib import Path from typing import Any, List, Union from urllib.parse import urlparse import requests from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader from langchain_commun...
from keras.src import activations from keras.src.api_export import keras_export from keras.src.layers.layer import Layer @keras_export("keras.layers.ReLU") class ReLU(Layer): """Rectified Linear Unit activation function layer. Formula: ``` python f(x) = max(x,0) f(x) = max_value if x >= max_value...
from keras.src import activations from keras.src.api_export import keras_export from keras.src.layers.layer import Layer @keras_export("keras.layers.ReLU") class ReLU(Layer): """Rectified Linear Unit activation function layer. Formula: ``` python f(x) = max(x,0) f(x) = max_value if x >= max_value...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.tools.ainetwork.base import AINBaseTool, OperationType # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling ...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.tools.ainetwork.base import AINBaseTool, OperationType # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling ...
_base_ = [ '../_base_/models/mask_rcnn_r50_fpn.py', '../common/lsj_100e_coco_instance.py' ] image_size = (1024, 1024) batch_augments = [dict(type='BatchFixedSizePad', size=image_size)] norm_cfg = dict(type='SyncBN', requires_grad=True) # Use MMSyncBN that handles empty tensor in head. It can be changed to # Sy...
_base_ = [ '../_base_/models/mask_rcnn_r50_fpn.py', '../common/lsj_100e_coco_instance.py' ] image_size = (1024, 1024) batch_augments = [dict(type='BatchFixedSizePad', size=image_size)] norm_cfg = dict(type='SyncBN', requires_grad=True) # Use MMSyncBN that handles empty tensor in head. It can be changed to # Sy...
# coding=utf-8 # Copyright 2025 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
# coding=utf-8 # Copyright 2024 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
# Copyright 2025 The HuggingFace Inc. 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 appl...
# Copyright 2024 The HuggingFace Inc. 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 appl...
from langchain_huggingface.chat_models.huggingface import ( # type: ignore[import-not-found] TGI_MESSAGE, TGI_RESPONSE, ChatHuggingFace, _convert_dict_to_message, ) __all__ = ["ChatHuggingFace", "_convert_dict_to_message", "TGI_MESSAGE", "TGI_RESPONSE"]
from langchain_huggingface.chat_models.huggingface import ( # type: ignore[import-not-found] TGI_MESSAGE, TGI_RESPONSE, ChatHuggingFace, _convert_message_to_chat_message, _convert_TGI_message_to_LC_message, ) __all__ = [ "ChatHuggingFace", "_convert_message_to_chat_message", "_convert_...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.ops.nn import average_pool from keras.src.ops.nn import batch_normalization from keras.src.ops.nn import binary_crossentropy from keras.src.ops.nn import categorical_crossentropy from...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.ops.nn import average_pool from keras.src.ops.nn import batch_normalization from keras.src.ops.nn import binary_crossentropy from keras.src.ops.nn import categorical_crossentropy from...
_base_ = './fast-rcnn_r50_fpn_1x_coco.py' train_cfg = dict(max_epochs=24) param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', begin=0, end=24, by_epoch=True, milestones=[16, 22], gamm...
_base_ = './fast-rcnn_r50_fpn_1x_coco.py' # learning policy lr_config = dict(step=[16, 22]) runner = dict(type='EpochBasedRunner', max_epochs=24)
"""Base tool spec class.""" import asyncio from inspect import signature from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple, Type, Union from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.tools.function_tool import FunctionTool from llama_index.core.tools.types import T...
"""Base tool spec class.""" import asyncio from inspect import signature from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple, Type, Union from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.tools.function_tool import FunctionTool from llama_index.core.tools.types import T...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.ops.nn import average_pool from keras.src.ops.nn import batch_normalization from keras.src.ops.nn import binary_crossentropy from keras.src.ops.nn import categorical_crossentropy from...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.ops.nn import average_pool from keras.src.ops.nn import batch_normalization from keras.src.ops.nn import binary_crossentropy from keras.src.ops.nn import categorical_crossentropy from...
import inspect import threading from typing import Awaitable, Callable, ParamSpec, TypeVar, cast, overload P = ParamSpec("P") R = TypeVar("R") @overload def thread_cached(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]: ... @overload def thread_cached(func: Callable[P, R]) -> Callable[P, R]: ... de...
import inspect import threading from typing import Any, Awaitable, Callable, ParamSpec, TypeVar, cast, overload P = ParamSpec("P") R = TypeVar("R") @overload def thread_cached(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]: ... @overload def thread_cached(func: Callable[P, R]) -> Callable[P, R]: ......
import logging from typing import Any from autogpt_libs.utils.cache import thread_cached from backend.data.block import ( Block, BlockCategory, BlockInput, BlockOutput, BlockSchema, BlockType, get_block, ) from backend.data.execution import ExecutionStatus from backend.data.model import Sc...
import logging from typing import Any from autogpt_libs.utils.cache import thread_cached from backend.data.block import ( Block, BlockCategory, BlockInput, BlockOutput, BlockSchema, BlockType, get_block, ) from backend.data.execution import ExecutionStatus from backend.data.model import Sc...
# Copyright 2025 Google Brain and 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 requ...
# Copyright 2024 Google Brain and 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 requ...
# Copyright (c) OpenMMLab. All rights reserved. from .accuracy import Accuracy, accuracy from .ae_loss import AssociativeEmbeddingLoss from .balanced_l1_loss import BalancedL1Loss, balanced_l1_loss from .cross_entropy_loss import (CrossEntropyLoss, binary_cross_entropy, cross_entropy, m...
from .accuracy import Accuracy, accuracy from .ae_loss import AssociativeEmbeddingLoss from .balanced_l1_loss import BalancedL1Loss, balanced_l1_loss from .cross_entropy_loss import (CrossEntropyLoss, binary_cross_entropy, cross_entropy, mask_cross_entropy) from .focal_loss import Focal...
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, Callable from sentence_transformers.evaluation import RerankingEvaluator from sentence_transformers.util import cos_sim if TYPE_CHECKING: import numpy as np from torch import Tensor from sentence_transformers.sparse...
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, Callable from sentence_transformers.evaluation import RerankingEvaluator from sentence_transformers.util import cos_sim if TYPE_CHECKING: import numpy as np from torch import Tensor from sentence_transformers.sparse...
"""DeepMemory Retrieval Pack.""" from typing import Any, Dict, List, Optional from llama_index.core.indices.vector_store import VectorStoreIndex from llama_index.core.llama_pack.base import BaseLlamaPack from llama_index.core.query_engine import RetrieverQueryEngine from llama_index.core.schema import TextNode from l...
"""DeepMemory Retrieval Pack.""" from typing import Any, Dict, List, Optional from llama_index.core.indices.vector_store import VectorStoreIndex from llama_index.core.llama_pack.base import BaseLlamaPack from llama_index.core.query_engine import RetrieverQueryEngine from llama_index.core.schema import TextNode from ...
from fastapi import FastAPI from fastapi.openapi.docs import ( get_redoc_html, get_swagger_ui_html, get_swagger_ui_oauth2_redirect_html, ) app = FastAPI(docs_url=None, redoc_url=None) @app.get("/docs", include_in_schema=False) async def custom_swagger_ui_html(): return get_swagger_ui_html( op...
from fastapi import FastAPI from fastapi.openapi.docs import ( get_redoc_html, get_swagger_ui_html, get_swagger_ui_oauth2_redirect_html, ) app = FastAPI(docs_url=None, redoc_url=None) @app.get("/docs", include_in_schema=False) async def custom_swagger_ui_html(): return get_swagger_ui_html( op...
# Copyright (c) OpenMMLab. All rights reserved. # from mmengine.dist import get_dist_info, all_reduce from collections import OrderedDict from typing import Generator, List from unittest.mock import MagicMock, Mock import torch from torch._utils import (_flatten_dense_tensors, _take_tensors, ...
# Copyright (c) OpenMMLab. All rights reserved. # from mmengine.dist import get_dist_info, all_reduce from collections import OrderedDict from typing import Generator, List from unittest.mock import MagicMock, Mock import torch from torch._utils import (_flatten_dense_tensors, _take_tensors, ...
_base_ = 'ssd300_coco.py' # model settings 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, 2...
_base_ = 'ssd300_coco.py' # model settings 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, 2...
import subprocess import pytest from flair_text import FlairTextEncoder from jina import Document, DocumentArray, Flow _EMBEDDING_DIM = 100 @pytest.mark.parametrize('request_size', [1, 10, 50, 100]) def test_integration(request_size: int): docs = DocumentArray( [Document(text='just some random text here...
import subprocess import pytest from flair_text import FlairTextEncoder from jina import Document, DocumentArray, Flow _EMBEDDING_DIM = 100 @pytest.mark.parametrize('request_size', [1, 10, 50, 100]) def test_integration(request_size: int): docs = DocumentArray( [Document(text='just some random text here...
# Copyright (c) OpenMMLab. All rights reserved. import math from typing import Sequence, Tuple import torch import torch.nn as nn from mmcv.cnn import ConvModule from mmengine.model import BaseModule from mmdet.registry import MODELS from mmdet.utils import OptMultiConfig @MODELS.register_module() class CTResNetNec...
# Copyright (c) OpenMMLab. All rights reserved. import math from typing import Sequence, Tuple import torch import torch.nn as nn from mmcv.cnn import ConvModule from mmengine.model import BaseModule from mmdet.core.utils import OptMultiConfig from mmdet.registry import MODELS @MODELS.register_module() class CTResN...
""" This example uses average word embeddings (for example from GloVe). It adds two fully-connected feed-forward layers (dense layers) to create a Deep Averaging Network (DAN). If 'glove.6B.300d.txt.gz' does not exist, it tries to download it from our server. See https://public.ukp.informatik.tu-darmstadt.de/reimers/...
""" This example uses average word embeddings (for example from GloVe). It adds two fully-connected feed-forward layers (dense layers) to create a Deep Averaging Network (DAN). If 'glove.6B.300d.txt.gz' does not exist, it tries to download it from our server. See https://public.ukp.informatik.tu-darmstadt.de/reimers/...
from docarray.documents.text import Text def test_text_document_operators(): doc = Text(text='text', url='url.com') assert doc == 'text' assert doc != 'url.com' doc2 = Text(id=doc.id, text='text', url='url.com') assert doc == doc2 doc3 = Text(id='other-id', text='text', url='url.com') ...
from docarray.documents.text import Text def test_text_document_operators(): doc = Text(text='text', url='url.com') assert doc == 'text' assert doc != 'url.com' doc2 = Text(id=doc.id, text='text', url='url.com') assert doc == doc2 doc3 = Text(id='other-id', text='text', url='url.com') ...
_base_ = './retinanet_r50-caffe_fpn_ms-3x_coco.py' # learning policy model = dict( backbone=dict( depth=101, init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://detectron2/resnet101_caffe')))
_base_ = './retinanet_r50-caffe_fpn_ms-3x_coco.py' # learning policy model = dict( pretrained='open-mmlab://detectron2/resnet101_caffe', backbone=dict(depth=101))
from llama_index_instrumentation.span import active_span_id from llama_index_instrumentation.span.base import BaseSpan from llama_index_instrumentation.span.simple import SimpleSpan __all__ = ["BaseSpan", "SimpleSpan", "active_span_id"]
from contextvars import ContextVar from typing import Optional from llama_index.core.instrumentation.span.base import BaseSpan from llama_index.core.instrumentation.span.simple import SimpleSpan # ContextVar for managing active spans active_span_id: ContextVar[Optional[str]] = ContextVar("active_span_id", default=Non...
# dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' # Example to use different file client # Method 1: simply set the data root and let the file I/O module # automatically infer from prefix (not support LMDB and Memcache yet) # data_root = 's3://openmmlab/datasets/detection/coco/' # Method 2: Us...
# dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' # file_client_args = dict( # backend='petrel', # path_mapping=dict({ # './data/': 's3://openmmlab/datasets/detection/', # 'data/': 's3://openmmlab/datasets/detection/' # })) file_client_args = dict(backend='disk') tra...
# 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...
__version__ = '0.30.1' import logging from docarray.array import DocList, DocVec from docarray.base_doc.doc import BaseDoc __all__ = ['BaseDoc', 'DocList', 'DocVec'] logger = logging.getLogger('docarray') handler = logging.StreamHandler() formatter = logging.Formatter("%(levelname)s - %(name)s - %(message)s") hand...
__version__ = '0.30.0' import logging from docarray.array import DocList, DocVec from docarray.base_doc.doc import BaseDoc __all__ = ['BaseDoc', 'DocList', 'DocVec'] logger = logging.getLogger('docarray') handler = logging.StreamHandler() formatter = logging.Formatter("%(levelname)s - %(name)s - %(message)s") hand...
# Copyright (c) OpenMMLab. All rights reserved. from .accuracy import Accuracy, accuracy from .ae_loss import AssociativeEmbeddingLoss from .balanced_l1_loss import BalancedL1Loss, balanced_l1_loss from .cross_entropy_loss import (CrossEntropyLoss, binary_cross_entropy, cross_entropy, m...
# Copyright (c) OpenMMLab. All rights reserved. from .accuracy import Accuracy, accuracy from .ae_loss import AssociativeEmbeddingLoss from .balanced_l1_loss import BalancedL1Loss, balanced_l1_loss from .cross_entropy_loss import (CrossEntropyLoss, binary_cross_entropy, cross_entropy, m...
from collections.abc import Sequence from inspect import signature from typing import Optional, Union from langchain_core.callbacks import Callbacks from langchain_core.documents import ( BaseDocumentCompressor, BaseDocumentTransformer, Document, ) from pydantic import ConfigDict class DocumentCompressor...
from collections.abc import Sequence from inspect import signature from typing import Optional, Union from langchain_core.callbacks.manager import Callbacks from langchain_core.documents import ( BaseDocumentCompressor, BaseDocumentTransformer, Document, ) from pydantic import ConfigDict class DocumentCo...
from __future__ import annotations from typing import TYPE_CHECKING, Any, Optional, Tuple, Type from langchain_core.tools import BaseTool from langchain_core.utils import guard_import from pydantic import model_validator if TYPE_CHECKING: from playwright.async_api import Browser as AsyncBrowser from playwrig...
from __future__ import annotations from typing import TYPE_CHECKING, Any, Optional, Tuple, Type from langchain_core.tools import BaseTool from langchain_core.utils import guard_import from pydantic import model_validator if TYPE_CHECKING: from playwright.async_api import Browser as AsyncBrowser from playwrig...
import os from source_separation.utils.dataset import wsj0mix from torchaudio_unittest.common_utils import get_whitenoise, normalize_wav, save_wav, TempDirMixin, TorchaudioTestCase _FILENAMES = [ "012c0207_1.9952_01cc0202_-1.9952.wav", "01co0302_1.63_014c020q_-1.63.wav", "01do0316_0.24011_205a0104_-0.240...
import os from source_separation.utils.dataset import wsj0mix from torchaudio_unittest.common_utils import ( get_whitenoise, normalize_wav, save_wav, TempDirMixin, TorchaudioTestCase, ) _FILENAMES = [ "012c0207_1.9952_01cc0202_-1.9952.wav", "01co0302_1.63_014c020q_-1.63.wav", "01do031...
# Owner(s): ["module: dynamo"] import torch import torch._dynamo import torch._dynamo.test_case @torch._dynamo.config.patch("capture_scalar_outputs", True) class ViewTests(torch._dynamo.test_case.TestCase): def test_view_to_2d(self): @torch.compile(fullgraph=True, backend="eager") def f(t, _u0): ...
# Owner(s): ["module: dynamo"] import torch import torch._dynamo import torch._dynamo.test_case @torch._dynamo.config.patch("capture_scalar_outputs", True) class ViewTests(torch._dynamo.test_case.TestCase): def test_view_to_2d(self): @torch.compile(fullgraph=True, backend="eager") def f(t, _u0): ...
import pathlib from argparse import ArgumentParser import sentencepiece as spm from lightning import ConformerRNNTModule from pytorch_lightning import seed_everything, Trainer from pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint from pytorch_lightning.plugins import DDPPlugin from transforms i...
import pathlib from argparse import ArgumentParser import sentencepiece as spm from lightning import ConformerRNNTModule from pytorch_lightning import seed_everything, Trainer from pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint from pytorch_lightning.plugins import DDPPlugin from transforms i...
from typing import Any, Optional from langchain_core.runnables.base import RunnableBindingBase from langchain_core.runnables.utils import Input, Output class HubRunnable(RunnableBindingBase[Input, Output]): """ An instance of a runnable stored in the LangChain Hub. """ owner_repo_commit: str de...
from typing import Any, Optional from langchain_core.runnables.base import Input, Output, RunnableBindingBase class HubRunnable(RunnableBindingBase[Input, Output]): """ An instance of a runnable stored in the LangChain Hub. """ owner_repo_commit: str def __init__( self, owner_re...
# Copyright (c) OpenMMLab. All rights reserved. from .hook import Hook from .iter_timer_hook import IterTimerHook from .sampler_seed_hook import DistSamplerSeedHook from .param_scheduler_hook import ParamSchedulerHook __all__ = [ 'Hook', 'IterTimerHook', 'DistSamplerSeedHook', 'ParamSchedulerHook' ]
# Copyright (c) OpenMMLab. All rights reserved. from .hook import Hook from .iter_timer_hook import IterTimerHook from .sampler_seed_hook import DistSamplerSeedHook __all__ = ['Hook', 'IterTimerHook', 'DistSamplerSeedHook']
_base_ = './fcos_hrnetv2p-w32-gn-head_ms-640-800-4xb4-2x_coco.py' model = dict( backbone=dict( extra=dict( stage2=dict(num_channels=(18, 36)), stage3=dict(num_channels=(18, 36, 72)), stage4=dict(num_channels=(18, 36, 72, 144))), init_cfg=dict( type='Pr...
_base_ = './fcos_hrnetv2p_w32_gn-head_mstrain_640-800_4x4_2x_coco.py' model = dict( backbone=dict( extra=dict( stage2=dict(num_channels=(18, 36)), stage3=dict(num_channels=(18, 36, 72)), stage4=dict(num_channels=(18, 36, 72, 144))), init_cfg=dict( type...
from typing import Dict, Optional, Tuple import torch import torchaudio from torchaudio.backend.common import AudioMetaData # Note: need to comply TorchScript syntax -- need annotation and no f-string nor global def _info_audio( s: torch.classes.torchaudio.ffmpeg_StreamReader, ): i = s.find_best_audio_stream...
from typing import Dict, Optional, Tuple import torch import torchaudio from torchaudio.backend.common import AudioMetaData # Note: need to comply TorchScript syntax -- need annotation and no f-string nor global def _info_audio( s: torch.classes.torchaudio.ffmpeg_StreamReader, ): i = s.find_best_audio_stream...
from pathlib import Path import pytest from torchaudio.datasets import dr_vctk from torchaudio_unittest.common_utils import get_whitenoise, save_wav, TempDirMixin, TorchaudioTestCase _SUBSETS = ["train", "test"] _CONDITIONS = ["clean", "device-recorded"] _SOURCES = ["DR-VCTK_Office1_ClosedWindow", "DR-VCTK_Office1_O...
from pathlib import Path import pytest from torchaudio.datasets import dr_vctk from torchaudio_unittest.common_utils import ( get_whitenoise, save_wav, TempDirMixin, TorchaudioTestCase, ) _SUBSETS = ["train", "test"] _CONDITIONS = ["clean", "device-recorded"] _SOURCES = ["DR-VCTK_Office1_ClosedWindow...
""" This is a simple application for sentence embeddings: clustering Sentences are mapped to sentence embeddings and then agglomerative clustering with a threshold is applied. """ from sentence_transformers import SentenceTransformer from sklearn.cluster import AgglomerativeClustering embedder = SentenceTransformer(...
""" This is a simple application for sentence embeddings: clustering Sentences are mapped to sentence embeddings and then agglomerative clustering with a threshold is applied. """ from sentence_transformers import SentenceTransformer from sklearn.cluster import AgglomerativeClustering import numpy as np embedder = S...
from typing import Optional from docarray import Document, DocumentArray from pydantic import BaseModel from uvicorn import Config, Server from jina import Gateway, __default_host__ from jina.clients.request import request_generator class DummyResponseModel(BaseModel): arg1: Optional[str] arg2: Optional[str...
from typing import Optional from docarray import Document, DocumentArray from pydantic import BaseModel from uvicorn import Config, Server from jina import Gateway, __default_host__ from jina.clients.request import request_generator class DummyResponseModel(BaseModel): arg1: Optional[str] arg2: Optional[str...
# 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 TOOD(SingleStageDetector): r"""Implementation of `TOOD: Task-aligned One-stage Object Det...
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.registry import MODELS from .single_stage import SingleStageDetector @MODELS.register_module() class TOOD(SingleStageDetector): r"""Implementation of `TOOD: Task-aligned One-stage Object Detection. <https://arxiv.org/abs/2108.07755>`_.""" def __i...
# Copyright (c) OpenMMLab. All rights reserved. __version__ = '2.25.0' short_version = __version__ def parse_version_info(version_str): version_info = [] for x in version_str.split('.'): if x.isdigit(): version_info.append(int(x)) elif x.find('rc') != -1: patch_version...
# Copyright (c) OpenMMLab. All rights reserved. __version__ = '2.24.1' short_version = __version__ def parse_version_info(version_str): version_info = [] for x in version_str.split('.'): if x.isdigit(): version_info.append(int(x)) elif x.find('rc') != -1: patch_version...
from contextlib import contextmanager from threading import Lock from typing import TYPE_CHECKING, Any from expiringdict import ExpiringDict if TYPE_CHECKING: from redis import Redis from redis.lock import Lock as RedisLock class RedisKeyedMutex: """ This class provides a mutex that can be locked an...
from contextlib import contextmanager from threading import Lock from typing import TYPE_CHECKING, Any from expiringdict import ExpiringDict if TYPE_CHECKING: from redis import Redis from redis.lock import Lock as RedisLock class RedisKeyedMutex: """ This class provides a mutex that can be locked an...