input
stringlengths
33
5k
output
stringlengths
32
5k
from typing import Optional, TYPE_CHECKING import numpy as np from docarray.document.mixins.helper import _uri_to_blob, _to_datauri, _is_datauri if TYPE_CHECKING: from docarray.typing import T class ConvertMixin: """Provide helper functions for :class:`Document` to support conversion between :attr:`.tensor...
from typing import Optional, TYPE_CHECKING import numpy as np from .helper import _uri_to_blob, _to_datauri, _is_datauri if TYPE_CHECKING: from ...typing import T class ConvertMixin: """Provide helper functions for :class:`Document` to support conversion between :attr:`.tensor`, :attr:`.text` and :attr...
from torch import * # noqa: F403 # Several names are not included in the above import * import torch for n in dir(torch): if (n.startswith('_') or n.endswith('_') or 'cuda' in n or 'cpu' in n or 'backward' in n): continue exec(f"{n} = torch.{n}") del n # These imports m...
from torch import * # noqa: F403 # Several names are not included in the above import * import torch for n in dir(torch): if (n.startswith('_') or n.endswith('_') or 'cuda' in n or 'cpu' in n or 'backward' in n): continue exec(n + ' = torch.' + n) # These imports may ov...
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from typing import Optional, List, Union, Dict import numpy as np from annoy import AnnoyIndex from jina import Executor, requests, DocumentArray, Document from jina_commons import get_logger from jina_commons.index...
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from typing import Optional, List, Union, Dict import numpy as np from annoy import AnnoyIndex from jina import Executor, requests, DocumentArray, Document from jina_commons import get_logger from jina_commons.index...
import torch from torchaudio_unittest.common_utils import PytorchTestCase from .functional_test_impl import Functional64OnlyTestImpl, FunctionalCPUOnlyTestImpl, FunctionalTestImpl class FunctionalFloat32CPUTest(FunctionalTestImpl, PytorchTestCase): dtype = torch.float32 device = torch.device("cpu") class F...
import torch from torchaudio_unittest.common_utils import PytorchTestCase from .functional_test_impl import Functional64OnlyTestImpl, FunctionalTestImpl class FunctionalFloat32CPUTest(FunctionalTestImpl, PytorchTestCase): dtype = torch.float32 device = torch.device("cpu") class FunctionalFloat64CPUTest(Fun...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.ops.nn import average_pool from keras.src.ops.nn import batch_normalization from keras.src.ops.nn import binary_crossentropy from keras.src.ops.nn import categorical_crossentropy from...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.ops.nn import average_pool from keras.src.ops.nn import batch_normalization from keras.src.ops.nn import binary_crossentropy from keras.src.ops.nn import categorical_crossentropy from...
from langchain_xai import ChatXAI MODEL_NAME = "grok-4" def test_chat_xai_secrets() -> None: o = ChatXAI(model=MODEL_NAME, xai_api_key="foo") # type: ignore[call-arg] s = str(o) assert "foo" not in s
from langchain_xai import ChatXAI def test_chat_xai_secrets() -> None: o = ChatXAI(model="grok-beta", xai_api_key="foo") # type: ignore[call-arg] s = str(o) assert "foo" not in s
from keras.src import ops from keras.src.api_export import keras_export from keras.src.optimizers import optimizer @keras_export(["keras.optimizers.Lion"]) class Lion(optimizer.Optimizer): """Optimizer that implements the Lion algorithm. The Lion optimizer is a stochastic-gradient-descent method that uses th...
from keras.src import ops from keras.src.api_export import keras_export from keras.src.optimizers import optimizer @keras_export(["keras.optimizers.Lion"]) class Lion(optimizer.Optimizer): """Optimizer that implements the Lion algorithm. The Lion optimizer is a stochastic-gradient-descent method that uses th...
# dataset settings dataset_type = 'VOCDataset' data_root = 'data/VOCdevkit/' # file_client_args = dict( # backend='petrel', # path_mapping=dict({ # './data/': 's3://openmmlab/datasets/detection/', # 'data/': 's3://openmmlab/datasets/detection/' # })) file_client_args = dict(backend='disk') ...
# dataset settings dataset_type = 'VOCDataset' data_root = 'data/VOCdevkit/' 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), dict(type='Resize', img_scale=(1000...
from typing import TYPE_CHECKING from .backend import BackendMixin, QdrantConfig from .find import FindMixin from .getsetdel import GetSetDelMixin from .helper import DISTANCES from .seqlike import SequenceLikeMixin __all__ = ['StorageMixins', 'QdrantConfig'] if TYPE_CHECKING: from qdrant_client import QdrantCli...
from typing import TYPE_CHECKING from .backend import BackendMixin, QdrantConfig from .find import FindMixin from .getsetdel import GetSetDelMixin from .helper import DISTANCES from .seqlike import SequenceLikeMixin __all__ = ['StorageMixins', 'QdrantConfig'] if TYPE_CHECKING: from qdrant_client import QdrantCli...
from backend.blocks.hubspot._auth import ( HubSpotCredentials, HubSpotCredentialsField, HubSpotCredentialsInput, ) from backend.data.block import Block, BlockCategory, BlockOutput, BlockSchema from backend.data.model import SchemaField from backend.util.request import Requests class HubSpotContactBlock(Bl...
from backend.blocks.hubspot._auth import ( HubSpotCredentials, HubSpotCredentialsField, HubSpotCredentialsInput, ) from backend.data.block import Block, BlockCategory, BlockOutput, BlockSchema from backend.data.model import SchemaField from backend.util.request import Requests class HubSpotContactBlock(Bl...
# model settings preprocess_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True, pad_size_divisor=32) model = dict( type='RetinaNet', preprocess_cfg=preprocess_cfg, backbone=dict( type='ResNet', depth=50, num_stages=4, out_ind...
# model settings img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) model = dict( type='RetinaNet', img_norm_cfg=img_norm_cfg, backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stage...
import csv import gzip import logging import os from datetime import datetime from torch.utils.data import DataLoader from sentence_transformers import InputExample, LoggingHandler, SentenceTransformer, datasets, losses, models, util from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator #### Just...
from torch.utils.data import DataLoader from sentence_transformers import models, losses, datasets from sentence_transformers import LoggingHandler, SentenceTransformer, util, InputExample from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator import logging from datetime import datetime import os im...
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...
""" 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...
# dataset settings dataset_type = 'MOTChallengeDataset' data_root = 'data/MOT17/' img_scale = (1088, 1088) # data pipeline train_pipeline = [ dict( type='UniformRefFrameSample', num_ref_imgs=1, frame_range=10, filter_key_img=True), dict( type='TransformBroadcaster', ...
# dataset settings dataset_type = 'MOTChallengeDataset' data_root = 'data/MOT17/' resized_shape = (1088, 1088) # data pipeline train_pipeline = [ dict( type='UniformRefFrameSample', num_ref_imgs=1, frame_range=10, filter_key_img=True), dict( type='TransformBroadcaster', ...
from pathlib import Path from typing import Dict, Tuple, Union import torchaudio from torch import Tensor from torch.hub import download_url_to_file from torch.utils.data import Dataset from torchaudio.datasets.utils import _extract_zip _URL = "https://datashare.ed.ac.uk/bitstream/handle/10283/3038/DR-VCTK.zip" _CHE...
from pathlib import Path from typing import Dict, Tuple, Union import torchaudio from torch import Tensor from torch.hub import download_url_to_file from torch.utils.data import Dataset from torchaudio.datasets.utils import extract_archive _URL = "https://datashare.ed.ac.uk/bitstream/handle/10283/3038/DR-VCTK.zip" _...
import json import math from collections import namedtuple from typing import List, Tuple import sentencepiece as spm import torch import torchaudio from torchaudio.models import Hypothesis MODEL_TYPE_LIBRISPEECH = "librispeech" MODEL_TYPE_TEDLIUM3 = "tedlium3" MODEL_TYPE_MUSTC = "mustc" DECIBEL = 2 * 20 * math.lo...
import json import math from collections import namedtuple from typing import List, Tuple import sentencepiece as spm import torch import torchaudio from torchaudio.models import Hypothesis MODEL_TYPE_LIBRISPEECH = "librispeech" MODEL_TYPE_TEDLIUM3 = "tedlium3" MODEL_TYPE_MUSTC = "mustc" DECIBEL = 2 * 20 * math.lo...
# training schedule for 1x train_cfg = dict(by_epoch=True, max_epochs=24) val_cfg = dict(interval=1) test_cfg = dict() # learning rate param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', begin=0, end=24, ...
# optimizer optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.001, step=[16, 22]) runner = dict(type='EpochBasedRunner', max_epochs=24)
import os from pathlib import Path from torchaudio.datasets import librispeech from torchaudio_unittest.common_utils import ( get_whitenoise, normalize_wav, save_wav, TempDirMixin, TorchaudioTestCase, ) # Used to generate a unique transcript for each dummy audio file _NUMBERS = ["ZERO", "ONE", "TW...
import os from pathlib import Path from torchaudio.datasets import librispeech from torchaudio_unittest.common_utils import ( TempDirMixin, TorchaudioTestCase, get_whitenoise, save_wav, normalize_wav, ) # Used to generate a unique transcript for each dummy audio file _NUMBERS = ["ZERO", "ONE", "TW...
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn import torch.nn.functional as F from mmdet.registry import MODELS eps = 1e-6 @MODELS.register_module() class DropBlock(nn.Module): """Randomly drop some regions of feature maps. Please refer to the method proposed in `DropB...
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import PLUGIN_LAYERS eps = 1e-6 @PLUGIN_LAYERS.register_module() class DropBlock(nn.Module): """Randomly drop some regions of feature maps. Please refer to the method proposed in...
from typing import Optional import pandas as pd import pytest from docarray import BaseDocument, DocumentArray from docarray.documents import ImageDoc @pytest.fixture() def nested_doc_cls(): class MyDoc(BaseDocument): count: Optional[int] text: str class MyDocNested(MyDoc): image: I...
from typing import Optional import pandas as pd import pytest from docarray import BaseDocument, DocumentArray from docarray.documents import ImageDoc @pytest.fixture() def nested_doc_cls(): class MyDoc(BaseDocument): count: Optional[int] text: str class MyDocNested(MyDoc): image: I...
from llama_index.llms.azure_openai import AzureOpenAI from llama_index.multi_modal_llms.azure_openai import AzureOpenAIMultiModal def test_embedding_class(): names_of_base_classes = [b.__name__ for b in AzureOpenAIMultiModal.__mro__] assert AzureOpenAI.__name__ in names_of_base_classes def test_init(): ...
from llama_index.core.multi_modal_llms.base import MultiModalLLM from llama_index.multi_modal_llms.azure_openai import AzureOpenAIMultiModal def test_embedding_class(): names_of_base_classes = [b.__name__ for b in AzureOpenAIMultiModal.__mro__] assert MultiModalLLM.__name__ in names_of_base_classes def test...
# Copyright (c) OpenMMLab. All rights reserved. import warnings import mmcv from mmdet.registry import TRANSFORMS from .compose import Compose @TRANSFORMS.register_module() class MultiScaleFlipAug: """Test-time augmentation with multiple scales and flipping. An example configuration is as followed: .....
# Copyright (c) OpenMMLab. All rights reserved. import warnings import mmcv from ..builder import PIPELINES from .compose import Compose @PIPELINES.register_module() class MultiScaleFlipAug: """Test-time augmentation with multiple scales and flipping. An example configuration is as followed: .. code-b...
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # model settings preprocess_cfg = dict( mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False, pad_size_divisor=32) model = dict( type='NASFCOS', prepr...
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # model settings preprocess_cfg = dict( mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False, pad_size_divisor=32) model = dict( type='NASFCOS', prepr...
""" this test check the docstring of all of our public API. It does it by checking the `__all__` of each of our namespace. to add a new namespace you need to * import it * add it to the `SUB_MODULE_TO_CHECK` list """ import pytest from mktestdocs import check_docstring, get_codeblock_members import docarray.data imp...
""" this test check the docstring of all of our public API. It does it by checking the `__all__` of each of our namespace. to add a new namespace you need to * import it * add it to the `SUB_MODULE_TO_CHECK` list """ import pytest from mktestdocs import check_docstring, get_codeblock_members import docarray.data imp...
# TODO: enable ruff qa on this file when we figure out why it thinks weaviate_client is # redefined at each test that fixture # ruff: noqa import numpy as np import pytest import torch from pydantic import Field from docarray import BaseDoc from docarray.index.backends.weaviate import WeaviateDocumentIndex from ...
# TODO: enable ruff qa on this file when we figure out why it thinks weaviate_client is # redefined at each test that fixture # ruff: noqa import numpy as np import pytest import torch from pydantic import Field from docarray import BaseDoc from docarray.index.backends.weaviate import WeaviateDocumentIndex from ...
import os import numpy as np import pytest import xgboost as xgb from xgboost import testing as tm from xgboost.core import DataSplitMode pytestmark = pytest.mark.skipif( tm.no_arrow()["condition"] or tm.no_pandas()["condition"], reason=tm.no_arrow()["reason"] + " or " + tm.no_pandas()["reason"], ) import p...
import os import sys import numpy as np import pytest import xgboost as xgb from xgboost import testing as tm from xgboost.core import DataSplitMode pytestmark = pytest.mark.skipif( tm.no_arrow()["condition"] or tm.no_pandas()["condition"], reason=tm.no_arrow()["reason"] + " or " + tm.no_pandas()["reason"], ...
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.registry import MODELS from .two_stage import TwoStageDetector @MODELS.register_module() class FasterRCNN(TwoStageDetector): """Implementation of `Faster R-CNN <https://arxiv.org/abs/1506.01497>`_""" def __init__(self, backbone, ...
# Copyright (c) OpenMMLab. All rights reserved. from ..builder import DETECTORS from .two_stage import TwoStageDetector @DETECTORS.register_module() class FasterRCNN(TwoStageDetector): """Implementation of `Faster R-CNN <https://arxiv.org/abs/1506.01497>`_""" def __init__(self, backbone, ...
""" This file loads sentences from a provided text file. It is expected, that the there is one sentence per line in that text file. CT will be training using these sentences. Checkpoints are stored every 500 steps to the output folder. Usage: python train_ct_from_file.py path/to/sentences.txt """ import math from s...
""" This file loads sentences from a provided text file. It is expected, that the there is one sentence per line in that text file. CT will be training using these sentences. Checkpoints are stored every 500 steps to the output folder. Usage: python train_ct_from_file.py path/to/sentences.txt """ import math from se...
import numpy as np from keras.src.api_export import keras_export @keras_export( [ "keras.utils.pad_sequences", "keras.preprocessing.sequence.pad_sequences", ] ) def pad_sequences( sequences, maxlen=None, dtype="int32", padding="pre", truncating="pre", value=0.0, ): ...
import numpy as np from keras.src.api_export import keras_export @keras_export( [ "keras.utils.pad_sequences", "keras.preprocessing.sequence.pad_sequences", ] ) def pad_sequences( sequences, maxlen=None, dtype="int32", padding="pre", truncating="pre", value=0.0, ): ...
# Licensed to the LF AI & Data foundation under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the "License"); # you may not use this fil...
from abc import ABC from typing import Any, Optional, Tuple, Type from docarray.typing.tensor.abstract_tensor import AbstractTensor class EmbeddingMixin(AbstractTensor, ABC): alternative_type: Optional[Type] = None @classmethod def __docarray_validate_getitem__(cls, item: Any) -> Tuple[int]: sha...
from datasets import Dataset from sentence_transformers.sparse_encoder import SparseEncoder, SparseEncoderTrainer, losses # Initialize the SPLADE model model = SparseEncoder("naver/splade-cocondenser-ensembledistil") train_dataset = Dataset.from_dict( { "anchor": ["It's nice weather outside today.", "He d...
from datasets import Dataset from sentence_transformers.sparse_encoder import ( MLMTransformer, SparseCachedMultipleNegativesRankingLoss, SparseEncoder, SparseEncoderTrainer, SpladePooling, ) # Initialize the SPLADE model model_name = "naver/splade-cocondenser-ensembledistil" model = SparseEncoder...
# Copyright (c) OpenMMLab. All rights reserved. from unittest import TestCase import torch from mmengine.structures import InstanceData from mmdet.models import build_detector from mmdet.structures import DetDataSample from mmdet.testing import get_detector_cfg from mmdet.utils import register_all_modules class Tes...
# Copyright (c) OpenMMLab. All rights reserved. from unittest import TestCase import torch from mmengine.structures import InstanceData from mmdet.models import build_detector from mmdet.structures import DetDataSample from mmdet.testing import get_detector_cfg from mmdet.utils import register_all_modules class Tes...
""" This file loads sentences from a provided text file. It is expected, that the there is one sentence per line in that text file. CT will be training using these sentences. Checkpoints are stored every 500 steps to the output folder. Usage: python train_ct_from_file.py path/to/sentences.txt """ import gzip import...
""" This file loads sentences from a provided text file. It is expected, that the there is one sentence per line in that text file. CT will be training using these sentences. Checkpoints are stored every 500 steps to the output folder. Usage: python train_ct_from_file.py path/to/sentences.txt """ import gzip import...
"""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...
""" ========================================== Feature importances with a forest of trees ========================================== This example shows the use of a forest of trees to evaluate the importance of features on an artificial classification task. The blue bars are the feature importances of the forest, alon...
""" ========================================== Feature importances with a forest of trees ========================================== This example shows the use of a forest of trees to evaluate the importance of features on an artificial classification task. The blue bars are the feature importances of the forest, alon...
import os import pytest import torch import whisper from whisper.tokenizer import get_tokenizer @pytest.mark.parametrize("model_name", whisper.available_models()) def test_transcribe(model_name: str): device = "cuda" if torch.cuda.is_available() else "cpu" model = whisper.load_model(model_name).to(device) ...
import os import pytest import torch import whisper @pytest.mark.parametrize("model_name", whisper.available_models()) def test_transcribe(model_name: str): device = "cuda" if torch.cuda.is_available() else "cpu" model = whisper.load_model(model_name).to(device) audio_path = os.path.join(os.path.dirname...
import argparse from jina.enums import GatewayProtocolType from jina.helper import parse_host_scheme from jina.logging.predefined import default_logger class NetworkChecker: """Check if a BaseDeployment is running or not.""" def __init__(self, args: 'argparse.Namespace'): """ Create a new :c...
import argparse from jina.enums import GatewayProtocolType from jina.helper import parse_host_scheme from jina.logging.predefined import default_logger class NetworkChecker: """Check if a BaseDeployment is running or not.""" def __init__(self, args: 'argparse.Namespace'): """ Create a new :c...
from enum import Enum # --8<-- [start:ProviderName] class ProviderName(str, Enum): ANTHROPIC = "anthropic" COMPASS = "compass" DISCORD = "discord" D_ID = "d_id" E2B = "e2b" EXA = "exa" FAL = "fal" GITHUB = "github" GOOGLE = "google" GOOGLE_MAPS = "google_maps" GROQ = "groq"...
from enum import Enum # --8<-- [start:ProviderName] class ProviderName(str, Enum): ANTHROPIC = "anthropic" COMPASS = "compass" DISCORD = "discord" D_ID = "d_id" E2B = "e2b" EXA = "exa" FAL = "fal" GITHUB = "github" GOOGLE = "google" GOOGLE_MAPS = "google_maps" GROQ = "groq"...
import pytest from langchain_core.agents import AgentAction, AgentFinish from langchain_core.exceptions import OutputParserException from langchain.agents.output_parsers.react_single_input import ( ReActSingleInputOutputParser, ) def test_action() -> None: """Test standard parsing of action/action input.""" ...
import pytest from langchain_core.agents import AgentAction, AgentFinish from langchain_core.exceptions import OutputParserException from langchain.agents.output_parsers.react_single_input import ( ReActSingleInputOutputParser, ) def test_action() -> None: """Test standard parsing of action/action input.""" ...
from typing import TYPE_CHECKING, Type, TypeVar from pydantic import AnyUrl as BaseAnyUrl from pydantic import errors, parse_obj_as from docarray.proto import NodeProto from docarray.typing.abstract_type import AbstractType if TYPE_CHECKING: from pydantic.networks import Parts T = TypeVar('T', bound='AnyUrl') ...
from typing import TYPE_CHECKING, Type, TypeVar from pydantic import AnyUrl as BaseAnyUrl from pydantic import errors, parse_obj_as from docarray.document.base_node import BaseNode from docarray.proto import NodeProto if TYPE_CHECKING: from pydantic.networks import Parts T = TypeVar('T', bound='AnyUrl') class...
import logging from typing import Annotated from autogpt_libs.auth.middleware import APIKeyValidator from fastapi import APIRouter, Body, Depends, HTTPException, Query from fastapi.responses import JSONResponse from backend.data.user import ( get_user_by_email, set_user_email_verification, unsubscribe_use...
import logging from typing import Annotated from autogpt_libs.auth.middleware import APIKeyValidator from fastapi import APIRouter, Body, Depends, Query from fastapi.responses import JSONResponse from backend.data.user import ( get_user_by_email, set_user_email_verification, unsubscribe_user_by_token, ) f...
from __future__ import annotations from dataclasses import dataclass from sentence_transformers.training_args import SentenceTransformerTrainingArguments @dataclass class SparseEncoderTrainingArguments(SentenceTransformerTrainingArguments): r""" SparseEncoderTrainingArguments extends :class:`~SentenceTransf...
from __future__ import annotations from dataclasses import dataclass from sentence_transformers.training_args import SentenceTransformerTrainingArguments @dataclass class SparseEncoderTrainingArguments(SentenceTransformerTrainingArguments): r""" SparseEncoderTrainingArguments extends :class:`~SentenceTransf...
# Copyright (c) OpenMMLab. All rights reserved. from pathlib import Path from typing import List import mmengine from mmengine.dataset import BaseDataset from mmengine.fileio import get_file_backend from mmdet.registry import DATASETS @DATASETS.register_module() class CocoCaptionDataset(BaseDataset): """COCO201...
# Copyright (c) OpenMMLab. All rights reserved. from pathlib import Path from typing import List import mmengine from mmengine.dataset import BaseDataset from mmengine.fileio import get_file_backend from mmdet.registry import DATASETS @DATASETS.register_module() class COCOCaptionDataset(BaseDataset): """COCO Ca...
# Copyright (c) OpenMMLab. All rights reserved. import asyncio from argparse import ArgumentParser import mmcv from mmdet.apis import (async_inference_detector, inference_detector, init_detector) from mmdet.registry import VISUALIZERS from mmdet.utils import register_all_modules def parse_ar...
# Copyright (c) OpenMMLab. All rights reserved. import asyncio from argparse import ArgumentParser import mmcv from mmdet.apis import (async_inference_detector, inference_detector, init_detector) from mmdet.registry import VISUALIZERS from mmdet.utils import register_all_modules def parse_ar...
from __future__ import annotations import logging import os from datasets import load_dataset from sentence_transformers.sparse_encoder import ( SparseEncoder, ) from sentence_transformers.sparse_encoder.evaluation.SparseNanoBEIREvaluator import SparseNanoBEIREvaluator from sentence_transformers.sparse_encoder.l...
from __future__ import annotations import logging import os from datasets import load_dataset from sentence_transformers.sparse_encoder import ( SparseEncoder, ) from sentence_transformers.sparse_encoder.evaluation.SparseNanoBEIREvaluator import SparseNanoBEIREvaluator from sentence_transformers.sparse_encoder.l...
from __future__ import annotations from typing import Any from langchain_text_splitters.base import TextSplitter class KonlpyTextSplitter(TextSplitter): """Splitting text using Konlpy package. It is good for splitting Korean text. """ def __init__( self, separator: str = "\n\n", ...
from __future__ import annotations from typing import Any, List from langchain_text_splitters.base import TextSplitter class KonlpyTextSplitter(TextSplitter): """Splitting text using Konlpy package. It is good for splitting Korean text. """ def __init__( self, separator: str = "\n\...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from pathlib import Path import pytest from jina import Document, DocumentArray, Executor from ...laser_encoder import LaserEncoder @pytest.fixture() def docs_generator(): return DocumentArray((Document(t...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import pytest from jina import Document, DocumentArray from ...laser_encoder import LaserEncoder @pytest.fixture() def docs_generator(): return DocumentArray((Document(text='random text') for _ in range(30)...
"""**Messages** are objects used in prompts and chat conversations. **Class hierarchy:** .. code-block:: BaseMessage --> SystemMessage, AIMessage, HumanMessage, ChatMessage, FunctionMessage, ToolMessage --> BaseMessageChunk --> SystemMessageChunk, AIMessageChunk, HumanMessageChunk, ChatMessageChu...
"""**Messages** are objects used in prompts and chat conversations. **Class hierarchy:** .. code-block:: BaseMessage --> SystemMessage, AIMessage, HumanMessage, ChatMessage, FunctionMessage, ToolMessage --> BaseMessageChunk --> SystemMessageChunk, AIMessageChunk, HumanMessageChunk, ChatMessageChu...
# Copyright (c) OpenMMLab. All rights reserved. import unittest import torch import torch.nn as nn import mmengine from mmengine.device import get_device, is_mlu_available from mmengine.runner import autocast from mmengine.utils import digit_version from mmengine.utils.dl_utils import TORCH_VERSION class TestAmp(un...
# Copyright (c) OpenMMLab. All rights reserved. import unittest import torch import torch.nn as nn import mmengine from mmengine.device import get_device from mmengine.runner import autocast from mmengine.utils import digit_version from mmengine.utils.dl_utils import TORCH_VERSION class TestAmp(unittest.TestCase): ...
"""Callback Handler that prints to std out.""" from __future__ import annotations from typing import TYPE_CHECKING, Any, Optional from typing_extensions import override from langchain_core.callbacks.base import BaseCallbackHandler from langchain_core.utils import print_text if TYPE_CHECKING: from langchain_cor...
"""Callback Handler that prints to std out.""" from __future__ import annotations from typing import TYPE_CHECKING, Any, Optional from typing_extensions import override from langchain_core.callbacks.base import BaseCallbackHandler from langchain_core.utils import print_text if TYPE_CHECKING: from langchain_cor...
# Copyright (c) OpenMMLab. All rights reserved. from typing import Optional, Sequence, Union import torch from mmengine.data import BaseDataElement from mmengine.hooks import Hook from mmengine.runner import Runner from mmdet.registry import HOOKS @HOOKS.register_module() class CheckInvalidLossHook(Hook): """Ch...
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmcv.runner.hooks import Hook from mmdet.registry import HOOKS @HOOKS.register_module() class CheckInvalidLossHook(Hook): """Check invalid loss hook. This hook will regularly check whether the loss is valid during training. Args: ...
# 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 agreed to in writ...
# 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 agreed to in writ...
import multiprocessing import pytest from jina import DocumentArray, Executor, requests from jina.serve.runtimes.asyncio import AsyncNewLoopRuntime from jina.serve.runtimes.worker import WorkerRuntime from jina.serve.streamer import GatewayStreamer from jina.types.request.data import DataRequest from tests.helper imp...
import multiprocessing import pytest from jina import DocumentArray, Executor, requests from jina.parsers import set_pod_parser from jina.serve.runtimes.asyncio import AsyncNewLoopRuntime from jina.serve.runtimes.worker import WorkerRuntime from jina.serve.streamer import GatewayStreamer from jina.types.request.data ...
import numpy as np import pytest import torch from pydantic import parse_obj_as from docarray import BaseDocument from docarray.documents import Video from docarray.typing import AudioNdArray, NdArray, VideoNdArray from tests import TOYDATA_DIR LOCAL_VIDEO_FILE = str(TOYDATA_DIR / 'mov_bbb.mp4') REMOTE_VIDEO_FILE = '...
import pytest from docarray.documents import Video from docarray.typing import AudioNdArray, NdArray, VideoNdArray from tests import TOYDATA_DIR LOCAL_VIDEO_FILE = str(TOYDATA_DIR / 'mov_bbb.mp4') REMOTE_VIDEO_FILE = 'https://github.com/docarray/docarray/blob/feat-rewrite-v2/tests/toydata/mov_bbb.mp4?raw=true' # noq...
import os.path from pathlib import Path from typing import Any, Callable, Optional, Tuple, Union import numpy as np from PIL import Image from .utils import check_integrity, download_url, verify_str_arg from .vision import VisionDataset class SVHN(VisionDataset): """`SVHN <http://ufldl.stanford.edu/housenumbers...
import os.path from typing import Any, Callable, Optional, Tuple import numpy as np from PIL import Image from .utils import check_integrity, download_url, verify_str_arg from .vision import VisionDataset class SVHN(VisionDataset): """`SVHN <http://ufldl.stanford.edu/housenumbers/>`_ Dataset. Note: The SVHN...
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.grpc import GRPCGatewayRuntime from jina.serve.runtimes.gateway.http import HTTPGatewayRuntime from jina...
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.grpc import GRPCGatewayRuntime from jina.serve.runtimes.gateway.http import HTTPGatewayRuntime from jina...
"""langchain-core version information and utilities.""" VERSION = "0.3.61"
"""langchain-core version information and utilities.""" VERSION = "0.3.60"
""" This example runs a BiLSTM after the word embedding lookup. The output of the BiLSTM is than pooled, for example with max-pooling (which gives a system like InferSent) or with mean-pooling. Note, you can also pass BERT embeddings to the BiLSTM. """ import traceback from datasets import load_dataset from sentence_...
""" This example runs a BiLSTM after the word embedding lookup. The output of the BiLSTM is than pooled, for example with max-pooling (which gives a system like InferSent) or with mean-pooling. Note, you can also pass BERT embeddings to the BiLSTM. """ from torch.utils.data import DataLoader import math from sentence...
# Copyright 2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
# Copyright 2024 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
import json import pytest import types from typing import Optional, Type from unittest import mock from requests import Response from llama_index.core.base.llms.base import BaseLLM from llama_index.core.base.llms.types import CompletionResponse from llama_index.llms.siliconflow import SiliconFlow RESPONSE_JSON = { ...
import json import pytest import types from typing import Optional, Type from unittest import mock from requests import Response from llama_index.core.base.llms.base import BaseLLM from llama_index.core.base.llms.types import CompletionResponse from llama_index.llms.siliconflow import SiliconFlow RESPONSE_JSON = { ...
from ._hdemucs import HDemucs, hdemucs_high, hdemucs_low, hdemucs_medium from .conformer import Conformer from .conv_tasnet import conv_tasnet_base, ConvTasNet from .deepspeech import DeepSpeech from .emformer import Emformer from .rnnt import emformer_rnnt_base, emformer_rnnt_model, RNNT from .rnnt_decoder import Hypo...
from ._hdemucs import HDemucs, hdemucs_high, hdemucs_low, hdemucs_medium from .conformer import Conformer from .conv_tasnet import conv_tasnet_base, ConvTasNet from .deepspeech import DeepSpeech from .emformer import Emformer from .rnnt import emformer_rnnt_base, emformer_rnnt_model, RNNT from .rnnt_decoder import Hypo...
from typing import Optional import pytest import torch from docarray import BaseDoc, DocArray from docarray.array.abstract_array import AnyDocArray from docarray.documents import TextDoc from docarray.typing import TorchTensor num_docs = 5 num_sub_docs = 2 num_sub_sub_docs = 3 @pytest.fixture def multi_model_docs(...
from typing import Optional import pytest import torch from docarray import BaseDocument, DocumentArray from docarray.array.abstract_array import AnyDocumentArray from docarray.documents import TextDoc from docarray.typing import TorchTensor num_docs = 5 num_sub_docs = 2 num_sub_sub_docs = 3 @pytest.fixture def mu...
__version__ = '0.32.2' import logging from docarray.array import DocList, DocVec from docarray.base_doc.doc import BaseDoc from docarray.utils._internal.misc import _get_path_from_docarray_root_level __all__ = ['BaseDoc', 'DocList', 'DocVec'] logger = logging.getLogger('docarray') handler = logging.StreamHandler()...
__version__ = '0.32.1' import logging from docarray.array import DocList, DocVec from docarray.base_doc.doc import BaseDoc from docarray.utils._internal.misc import _get_path_from_docarray_root_level __all__ = ['BaseDoc', 'DocList', 'DocVec'] logger = logging.getLogger('docarray') handler = logging.StreamHandler()...
import os from typing import Optional import pytest from docarray import BaseDocument, DocumentArray from docarray.documents import Image from tests import TOYDATA_DIR @pytest.fixture() def nested_doc_cls(): class MyDoc(BaseDocument): count: Optional[int] text: str class MyDocNested(MyDoc):...
import os from typing import Optional import pytest from docarray import BaseDocument, DocumentArray from docarray.documents import Image from tests import TOYDATA_DIR @pytest.fixture() def nested_doc_cls(): class MyDoc(BaseDocument): count: Optional[int] text: str class MyDocNested(MyDoc):...
"""Human message.""" from typing import Any, Literal, Union from langchain_core.messages.base import BaseMessage, BaseMessageChunk class HumanMessage(BaseMessage): """Message from a human. HumanMessages are messages that are passed in from a human to the model. Example: .. code-block:: python...
from typing import Any, Literal, Union from langchain_core.messages.base import BaseMessage, BaseMessageChunk class HumanMessage(BaseMessage): """Message from a human. HumanMessages are messages that are passed in from a human to the model. Example: .. code-block:: python from lan...
""" This script contains an example how to perform semantic search with OpenSearch. You need OpenSearch up and running locally: https://docs.opensearch.org/docs/latest/getting-started/quickstart/ Further, you need the Python OpenSearch Client installed: https://docs.opensearch.org/docs/latest/clients/python-low-level...
""" This script contains an example how to perform semantic search with OpenSearch. You need OpenSearch up and running locally: https://docs.opensearch.org/docs/latest/getting-started/quickstart/ Further, you need the Python OpenSearch Client installed: https://docs.opensearch.org/docs/latest/clients/python-low-level...
from typing import TYPE_CHECKING from docarray.dataclasses.enums import DocumentMetadata, ImageType if TYPE_CHECKING: # pragma: no cover from docarray import Document def image_getter(doc: 'Document'): if doc._metadata[DocumentMetadata.IMAGE_TYPE] == ImageType.URI: return doc.uri elif doc._metad...
from typing import TYPE_CHECKING if TYPE_CHECKING: # pragma: no cover from docarray import Document def image_getter(doc: 'Document'): if doc._metadata['image_type'] == 'uri': return doc.uri elif doc._metadata['image_type'] == 'PIL': from PIL import Image return Image.fromarray(...
import numpy as np from absl.testing import parameterized from keras.src import backend from keras.src import ops from keras.src import testing from keras.src.optimizers.loss_scale_optimizer import LossScaleOptimizer from keras.src.optimizers.sgd import SGD class LossScaleOptimizerTest(testing.TestCase): def _sk...
import numpy as np from absl.testing import parameterized from keras.src import backend from keras.src import ops from keras.src import testing from keras.src.optimizers.loss_scale_optimizer import LossScaleOptimizer from keras.src.optimizers.sgd import SGD class LossScaleOptimizerTest(testing.TestCase, parameterize...
from google.protobuf import __version__ as __pb__version__ from jina._docarray import docarray_v2 as is_docarray_v2 if __pb__version__.startswith('4'): if is_docarray_v2: from jina.proto.docarray_v2.pb.jina_pb2_grpc import * else: from jina.proto.docarray_v1.pb.jina_pb2_grpc import * else: ...
from google.protobuf import __version__ as __pb__version__ from jina._docarray import docarray_v2 as is_docarray_v2 if __pb__version__.startswith('4'): if is_docarray_v2: from .docarray_v2.pb.jina_pb2_grpc import * else: from .docarray_v1.pb.jina_pb2_grpc import * else: if is_docarray_v2:...
from abc import abstractmethod from typing import Iterable, Union from qdrant_client import QdrantClient from docarray.array.storage.base.seqlike import BaseSequenceLikeMixin from docarray import Document class SequenceLikeMixin(BaseSequenceLikeMixin): @property @abstractmethod def client(self) -> Qdran...
from abc import abstractmethod from typing import Iterable, Union from qdrant_client import QdrantClient from docarray.array.storage.base.seqlike import BaseSequenceLikeMixin from docarray import Document class SequenceLikeMixin(BaseSequenceLikeMixin): @property @abstractmethod def client(self) -> Qdran...
_base_ = [ '../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # model settings norm_cfg = dict(type='GN', num_groups=32, requires_grad=True) model = dict( bbox_head=dict( _delete_=True, t...
_base_ = [ '../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # model settings norm_cfg = dict(type='GN', num_groups=32, requires_grad=True) model = dict( bbox_head=dict( _delete_=True, t...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.backend.config import backend from keras.src.backend.config import disable_flash_attention from keras.src.backend.config import enable_flash_attention from keras.src.backend.config im...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.backend.config import backend from keras.src.backend.config import epsilon from keras.src.backend.config import floatx from keras.src.backend.config import image_data_format from kera...
_base_ = [ '../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/openimages_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict(bbox_head=dict(num_classes=601)) # learning rate param_scheduler = [ dict( type='LinearLR', start_factor...
_base_ = [ '../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/openimages_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict(bbox_head=dict(num_classes=601)) optimizer = dict(type='SGD', lr=0.08, momentum=0.9, weight_decay=0.0001) optimizer_config =...
import os import platform import tempfile import pytest from sentence_transformers import SentenceTransformer, CrossEncoder from sentence_transformers.models import Transformer, Pooling from datasets import load_dataset, DatasetDict @pytest.fixture() def stsb_bert_tiny_model() -> SentenceTransformer: return Sent...
import os import platform import tempfile import pytest from sentence_transformers import SentenceTransformer, CrossEncoder from sentence_transformers.models import Transformer, Pooling @pytest.fixture() def stsb_bert_tiny_model() -> SentenceTransformer: return SentenceTransformer("sentence-transformers-testing/...
from dataclasses import dataclass, field from typing import Union from transformers import TrainingArguments as TransformersTrainingArguments from transformers.utils import ExplicitEnum class BatchSamplers(ExplicitEnum): """ Stores the acceptable string identifiers for batch samplers. """ BATCH_SAMPL...
from dataclasses import dataclass, field from typing import Union from transformers import TrainingArguments as TransformersTrainingArguments from transformers.utils import ExplicitEnum class BatchSamplers(ExplicitEnum): """ Stores the acceptable string identifiers for batch samplers. """ BATCH_SAMPL...
from langchain_core.tracers.evaluation import ( EvaluatorCallbackHandler, wait_for_all_evaluators, ) __all__ = ["EvaluatorCallbackHandler", "wait_for_all_evaluators"]
from langchain_core.tracers.evaluation import ( EvaluatorCallbackHandler, wait_for_all_evaluators, ) __all__ = ["wait_for_all_evaluators", "EvaluatorCallbackHandler"]
import sys from dataclasses import dataclass from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast if TYPE_CHECKING: im...
import sys from dataclasses import dataclass from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast if TYPE_CHECKING: im...
"""Pydantic v1 compatibility shim.""" from importlib import metadata from langchain_core._api.deprecation import warn_deprecated # Create namespaces for pydantic v1 and v2. # This code must stay at the top of the file before other modules may # attempt to import pydantic since it adds pydantic_v1 and pydantic_v2 to ...
"""Pydantic v1 compatibility shim.""" from importlib import metadata from langchain_core._api.deprecation import warn_deprecated # Create namespaces for pydantic v1 and v2. # This code must stay at the top of the file before other modules may # attempt to import pydantic since it adds pydantic_v1 and pydantic_v2 to ...
from typing import TYPE_CHECKING, Any, List, Tuple, Type, TypeVar, Union import numpy as np from docarray.typing.proto_register import _register_proto from docarray.typing.tensor.tensorflow_tensor import TensorFlowTensor, metaTensorFlow from docarray.typing.tensor.video.video_tensor_mixin import VideoTensorMixin T =...
from typing import TYPE_CHECKING, Any, List, Tuple, Type, TypeVar, Union import numpy as np from docarray.typing.proto_register import _register_proto from docarray.typing.tensor.tensorflow_tensor import TensorFlowTensor, metaTensorFlow from docarray.typing.tensor.video.video_tensor_mixin import VideoTensorMixin T =...
import pathlib from typing import Any, Dict, List, Tuple, Union import torch from torchdata.datapipes.iter import CSVParser, IterDataPipe, Mapper from torchvision.datapoints import Image from torchvision.prototype.datapoints import OneHotLabel from torchvision.prototype.datasets.utils import Dataset, HttpResource, Onl...
import pathlib from typing import Any, Dict, List, Tuple, Union import torch from torchdata.datapipes.iter import CSVParser, IterDataPipe, Mapper from torchvision.prototype.datapoints import Image, OneHotLabel from torchvision.prototype.datasets.utils import Dataset, HttpResource, OnlineResource from torchvision.proto...
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production""" __version__ = "0.116.0" from starlette import status as status from .applications import FastAPI as FastAPI from .background import BackgroundTasks as BackgroundTasks from .datastructures import UploadFile as UploadFile from...
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production""" __version__ = "0.115.14" from starlette import status as status from .applications import FastAPI as FastAPI from .background import BackgroundTasks as BackgroundTasks from .datastructures import UploadFile as UploadFile fro...
_base_ = './cascade-rcnn_r50_fpn_20e_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
_base_ = './cascade_rcnn_r50_fpn_20e_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
# Copyright (c) OpenMMLab. All rights reserved. from contextlib import contextmanager import torch import torch.nn as nn from torch.cuda.amp import GradScaler from mmengine.registry import OPTIM_WRAPPERS from mmengine.utils import digit_version from mmengine.utils.dl_utils import TORCH_VERSION from .optimizer_wrapper...
# Copyright (c) OpenMMLab. All rights reserved. from contextlib import contextmanager import torch import torch.nn as nn from torch.cuda.amp import GradScaler from mmengine.registry import OPTIM_WRAPPERS from mmengine.utils import TORCH_VERSION, digit_version from .optimizer_wrapper import OptimWrapper @OPTIM_WRAPP...
import pathlib from typing import Any, Dict, List, Tuple, Union from torchdata.datapipes.iter import Filter, IterDataPipe, Mapper from torchvision.prototype.datapoints import Label from torchvision.prototype.datasets.utils import Dataset, EncodedImage, HttpResource, OnlineResource from torchvision.prototype.datasets.u...
import pathlib from typing import Any, Dict, List, Tuple, Union from torchdata.datapipes.iter import Filter, IterDataPipe, Mapper from torchvision.prototype.datasets.utils import Dataset, EncodedImage, HttpResource, OnlineResource from torchvision.prototype.datasets.utils._internal import ( hint_sharding, hint...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.agent_toolkits.openapi.toolkit import ( OpenAPIToolkit, RequestsToolkit, ) # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for rais...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.agent_toolkits.openapi.toolkit import ( OpenAPIToolkit, RequestsToolkit, ) # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for rais...
""" This examples trains a CrossEncoder for the NLI task. A CrossEncoder takes a sentence pair as input and outputs a label. Here, it learns to predict the labels: "contradiction": 0, "entailment": 1, "neutral": 2. It does NOT produce a sentence embedding and does NOT work for individual sentences. Usage: python trai...
""" This examples trains a CrossEncoder for the NLI task. A CrossEncoder takes a sentence pair as input and outputs a label. Here, it learns to predict the labels: "contradiction": 0, "entailment": 1, "neutral": 2. It does NOT produce a sentence embedding and does NOT work for individual sentences. Usage: python trai...
import os from nvflare.apis.executor import Executor from nvflare.apis.fl_constant import FLContextKey, ReturnCode from nvflare.apis.fl_context import FLContext from nvflare.apis.shareable import Shareable, make_reply from nvflare.apis.signal import Signal import xgboost as xgb from xgboost import callback class Su...
import os from nvflare.apis.executor import Executor from nvflare.apis.fl_constant import FLContextKey, ReturnCode from nvflare.apis.fl_context import FLContext from nvflare.apis.shareable import Shareable, make_reply from nvflare.apis.signal import Signal import xgboost as xgb from xgboost import callback class Su...
"""Standard LangChain interface tests.""" import pytest from langchain_core.language_models import BaseChatModel from langchain_core.tools import BaseTool from langchain_tests.integration_tests import ChatModelIntegrationTests from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint class TestHuggingF...
"""Standard LangChain interface tests""" import pytest from langchain_core.language_models import BaseChatModel from langchain_core.tools import BaseTool from langchain_tests.integration_tests import ChatModelIntegrationTests from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint class TestHuggingFa...
import unittest import torch import torchaudio.prototype.functional as F from torchaudio_unittest.common_utils import TestBaseMixin, torch_script class TorchScriptConsistencyTestImpl(TestBaseMixin): def _assert_consistency(self, func, inputs, shape_only=False): inputs_ = [] for i in inputs: ...
import unittest import torch import torchaudio.prototype.functional as F from torchaudio_unittest.common_utils import nested_params, TestBaseMixin, torch_script class TorchScriptConsistencyTestImpl(TestBaseMixin): def _assert_consistency(self, func, inputs, shape_only=False): inputs_ = [] for i i...
from typing import Optional from langchain_core.callbacks.manager import CallbackManagerForRetrieverRun from langchain_core.documents import Document from langchain_core.retrievers import BaseRetriever from langchain.retrievers.ensemble import EnsembleRetriever class MockRetriever(BaseRetriever): docs: list[Doc...
from typing import Optional from langchain_core.callbacks.manager import CallbackManagerForRetrieverRun from langchain_core.documents import Document from langchain_core.retrievers import BaseRetriever from langchain.retrievers.ensemble import EnsembleRetriever class MockRetriever(BaseRetriever): docs: list[Doc...
# Copyright (c) OpenMMLab. All rights reserved. import datetime import os.path as osp from typing import Optional from mmengine.fileio import dump from mmengine.logging import print_log from . import root from .registry import Registry def traverse_registry_tree(registry: Registry, verbose: bool = True) -> list: ...
# Copyright (c) OpenMMLab. All rights reserved. import datetime import os.path as osp from typing import Optional from mmengine.fileio import dump from . import root from .registry import Registry def traverse_registry_tree(registry: Registry, verbose: bool = True) -> list: """Traverse the whole registry tree fr...
_base_ = './cornernet_hourglass104_mstest_8x6_210e_coco.py' train_dataloader = dict(batch_size=3) # NOTE: `auto_scale_lr` is for automatically scaling LR, # USER SHOULD NOT CHANGE ITS VALUES. # base_batch_size = (32 GPUs) x (3 samples per GPU) auto_scale_lr = dict(base_batch_size=96)
_base_ = [ '../_base_/default_runtime.py', '../_base_/datasets/coco_detection.py' ] # model settings model = dict( type='CornerNet', backbone=dict( type='HourglassNet', downsample_times=5, num_stacks=2, stage_channels=[256, 256, 384, 384, 384, 512], stage_blocks=[2, ...
from .transformer_tf_text_encode import TransformerTFTextEncoder
from .transformer_tf_text_encode import TransformerTFTextEncoder
_base_ = [ '../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] checkpoint = 'https://download.openmmlab.com/mmclassification/v0/resnet/resnet50_8xb256-rsb-a1-600e_in1k_20211228-20e21305.pth' # noqa model = ...
_base_ = [ '../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] checkpoint = 'https://download.openmmlab.com/mmclassification/v0/resnet/resnet50_8xb256-rsb-a1-600e_in1k_20211228-20e21305.pth' # noqa model = ...
import os from jina import Executor, requests class DummyExecutor(Executor): def __init__(self, arg='hello', **kwargs): super().__init__(**kwargs) self.arg = arg @requests def foo(self, docs, **kwargs): for doc in docs: doc.text = self.arg
import os from jina import Executor, requests class DummyExecutor(Executor): @requests def foo(self, **kwargs): pass
import sqlite3 import warnings from dataclasses import dataclass, field from tempfile import NamedTemporaryFile from typing import ( Iterable, Dict, Optional, TYPE_CHECKING, Union, List, Tuple, ) from docarray.array.storage.sqlite.helper import initialize_table from docarray.array.storage.b...
import sqlite3 import warnings from dataclasses import dataclass, field from tempfile import NamedTemporaryFile from typing import ( Iterable, Dict, Optional, TYPE_CHECKING, Union, List, Tuple, ) from .helper import initialize_table from ..base.backend import BaseBackendMixin from ....helpe...
from jina.serve.runtimes.servers import BaseServer from aiohttp import web class LoadBalancingServer(BaseServer): """Base FastAPI server. Implement this abstract class in-case you want to build a fastapi-based server by implementing the `app` property. This property should return a fastapi app. The base Gatew...
from jina.serve.runtimes.servers import BaseServer from aiohttp import web class LoadBalancingServer(BaseServer): """Base FastAPI server. Implement this abstract class in-case you want to build a fastapi-based server by implementing the `app` property. This property should return a fastapi app. The base Gatew...
# dataset settings dataset_type = 'WIDERFaceDataset' data_root = 'data/WIDERFace/' # 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/cityscapes/' ...
# dataset settings dataset_type = 'WIDERFaceDataset' data_root = 'data/WIDERFace/' img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[1, 1, 1], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile', to_float32=True), dict(type='LoadAnnotations', with_bbox=True), dict( type='PhotoMetric...
from langchain_core.utils.iter import NoLock, Tee, batch_iterate, tee_peer __all__ = ["NoLock", "Tee", "batch_iterate", "tee_peer"]
from langchain_core.utils.iter import NoLock, Tee, batch_iterate, tee_peer __all__ = ["NoLock", "tee_peer", "Tee", "batch_iterate"]