input
stringlengths
33
5k
output
stringlengths
32
5k
import numpy as np import pytest from fastapi import FastAPI from httpx import AsyncClient from docarray import BaseDocument, Image, Text from docarray.typing import NdArray @pytest.mark.asyncio async def test_fast_api(): class Mmdoc(BaseDocument): img: Image text: Text title: str in...
import numpy as np import pytest from fastapi import FastAPI from httpx import AsyncClient from docarray import Document, Image, Text from docarray.typing import NdArray @pytest.mark.asyncio async def test_fast_api(): class Mmdoc(Document): img: Image text: Text title: str input_doc ...
# 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...
import os from llama_index.core.tools.function_tool import FunctionTool import pytest from llama_index.core.base.llms.base import BaseLLM from llama_index.core.base.llms.types import ChatMessage, ImageBlock, MessageRole from llama_index.llms.gemini import Gemini from llama_index.llms.gemini.utils import chat_message_t...
import os from llama_index.core.tools.function_tool import FunctionTool import pytest from llama_index.core.base.llms.base import BaseLLM from llama_index.core.base.llms.types import ChatMessage, ImageBlock, MessageRole from llama_index.llms.gemini import Gemini from llama_index.llms.gemini.utils import chat_message_t...
from llama_index_instrumentation.span.base import BaseSpan # noqa
from typing import Any, Dict, Optional from uuid import uuid4 from llama_index.core.bridge.pydantic import BaseModel, Field, ConfigDict class BaseSpan(BaseModel): """Base data class representing a span.""" model_config = ConfigDict(arbitrary_types_allowed=True) id_: str = Field(default_factory=lambda: st...
import torch from docarray.computation.torch_backend import TorchCompBackend def test_to_device(): t = torch.rand(10, 3) assert t.device == torch.device('cpu') t = TorchCompBackend.to_device(t, 'meta') assert t.device == torch.device('meta') def test_empty(): tensor = TorchCompBackend.empty((10...
import torch from docarray.computation.torch_backend import TorchCompBackend def test_to_device(): t = torch.rand(10, 3) assert t.device == torch.device('cpu') t = TorchCompBackend.to_device(t, 'meta') assert t.device == torch.device('meta')
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.quantizers import deserialize from keras.src.quantizers import get from keras.src.quantizers import serialize from keras.src.quantizers.quantizers import AbsMaxQuantizer from keras.sr...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.quantizers import deserialize from keras.src.quantizers import get from keras.src.quantizers import serialize from keras.src.quantizers.quantizers import AbsMaxQuantizer from keras.sr...
"""Mock prompt utils.""" from llama_index.core.prompts.base import PromptTemplate from llama_index.core.prompts.prompt_type import PromptType MOCK_SUMMARY_PROMPT_TMPL = "{context_str}\n" MOCK_SUMMARY_PROMPT = PromptTemplate( MOCK_SUMMARY_PROMPT_TMPL, prompt_type=PromptType.SUMMARY ) MOCK_INSERT_PROMPT_TMPL = "{n...
"""Mock prompt utils.""" from llama_index.core.prompts.base import PromptTemplate from llama_index.core.prompts.prompt_type import PromptType MOCK_SUMMARY_PROMPT_TMPL = "{context_str}\n" MOCK_SUMMARY_PROMPT = PromptTemplate( MOCK_SUMMARY_PROMPT_TMPL, prompt_type=PromptType.SUMMARY ) MOCK_INSERT_PROMPT_TMPL = "{n...
from __future__ import annotations import random import pytest import torch from torch.utils.data import ConcatDataset from sentence_transformers.sampler import NoDuplicatesBatchSampler, ProportionalBatchSampler from sentence_transformers.util import is_datasets_available if is_datasets_available(): from datase...
from __future__ import annotations import random import pytest import torch from datasets import Dataset from torch.utils.data import ConcatDataset from sentence_transformers.sampler import NoDuplicatesBatchSampler, ProportionalBatchSampler @pytest.fixture def dummy_dataset() -> Dataset: """ Dummy dataset ...
""" Tests the correct computation of evaluation scores from BinaryClassificationEvaluator """ from __future__ import annotations import csv import gzip import os from pathlib import Path import pytest from torch.utils.data import DataLoader from sentence_transformers import ( InputExample, SentenceTransform...
""" Tests the correct computation of evaluation scores from BinaryClassificationEvaluator """ from __future__ import annotations import csv import gzip import os from pathlib import Path from torch.utils.data import DataLoader from sentence_transformers import ( InputExample, SentenceTransformer, evalua...
from typing import Any, Dict, List, Sequence, Union from deprecated import deprecated from llama_index.core.base.llms.types import ( CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, MessageRole, ) from llama_index.core.base.llms.generic_utils import ( chat_response_to_completi...
from typing import Any, Dict, List, Sequence from llama_index.core.base.llms.types import ( CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, MessageRole, ) from llama_index.core.base.llms.generic_utils import ( chat_response_to_completion_response, stream_chat_response_to_...
"""Simple reader that reads weather data from OpenWeatherMap API.""" from typing import List from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document class WeatherReader(BaseReader): """ Weather Reader. Reads the forecast & current weather of any location using ...
"""Simple reader that reads weather data from OpenWeatherMap API.""" from typing import List from llama_index.core.readers.base import BaseReader from llama_index.core.schema import Document class WeatherReader(BaseReader): """ Weather Reader. Reads the forecast & current weather of any location using O...
# Copyright (c) OpenMMLab. All rights reserved. from .dist_utils import (DistOptimizerHook, all_reduce_dict, allreduce_grads, reduce_mean, sync_random_seed) from .misc import (center_of_mass, filter_scores_and_topk, flip_tensor, generate_coordinate, mask2ndarray, multi_apply,...
# Copyright (c) OpenMMLab. All rights reserved. from .dist_utils import (DistOptimizerHook, all_reduce_dict, allreduce_grads, reduce_mean) from .misc import (center_of_mass, filter_scores_and_topk, flip_tensor, generate_coordinate, mask2ndarray, multi_apply, ...
from langchain_core._api import warn_deprecated from pydantic.v1.dataclasses import * # noqa: F403 warn_deprecated( "0.3.0", removal="1.0.0", alternative="pydantic.v1 or pydantic", message=( "As of langchain-core 0.3.0, LangChain uses pydantic v2 internally. " "The langchain.pydantic_v...
from langchain_core._api import warn_deprecated try: from pydantic.v1.dataclasses import * # noqa: F403 except ImportError: from pydantic.dataclasses import * # type: ignore # noqa: F403 warn_deprecated( "0.3.0", removal="1.0.0", alternative="pydantic.v1 or pydantic", message=( "As o...
from __future__ import annotations from typing import Any, Dict, Optional from docarray import BaseDoc, DocList from docarray.typing import AnyEmbedding, AnyTensor class LegacyDocument(BaseDoc): """ This Document is the LegacyDocument. It follows the same schema as in DocArray <=0.21. It can be useful t...
from __future__ import annotations from typing import Any, Dict, Optional from docarray import BaseDoc, DocList from docarray.typing import AnyEmbedding, AnyTensor class LegacyDocument(BaseDoc): """ This Document is the LegacyDocument. It follows the same schema as in DocArray <=0.21. It can be useful t...
# Copyright (c) OpenMMLab. All rights reserved. from .vis_backend import (BaseVisBackend, LocalVisBackend, MLflowVisBackend, TensorboardVisBackend, WandbVisBackend) from .visualizer import Visualizer __all__ = [ 'Visualizer', 'BaseVisBackend', 'LocalVisBackend', 'WandbVisBackend', 'Te...
# Copyright (c) OpenMMLab. All rights reserved. from .vis_backend import (BaseVisBackend, LocalVisBackend, TensorboardVisBackend, WandbVisBackend) from .visualizer import Visualizer __all__ = [ 'Visualizer', 'BaseVisBackend', 'LocalVisBackend', 'WandbVisBackend', 'TensorboardVisBacken...
from docarray.documents.text import TextDoc def test_text_document_operators(): doc = TextDoc(text='text', url='http://url.com') assert doc == 'text' assert doc != 'http://url.com' doc2 = TextDoc(id=doc.id, text='text', url='http://url.com') assert doc == doc2 doc3 = TextDoc(id='other-id', ...
from docarray.documents.text import TextDoc def test_text_document_operators(): doc = TextDoc(text='text', url='url.com') assert doc == 'text' assert doc != 'url.com' doc2 = TextDoc(id=doc.id, text='text', url='url.com') assert doc == doc2 doc3 = TextDoc(id='other-id', text='text', url='ur...
#!/usr/bin/env python3 # coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unles...
#!/usr/bin/env python3 # coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unles...
"""Test ChatDeepSeek chat model.""" from typing import Optional, Type import pytest from langchain_core.language_models import BaseChatModel from langchain_core.messages import AIMessageChunk, BaseMessageChunk from langchain_core.tools import BaseTool from langchain_tests.integration_tests import ChatModelIntegration...
"""Test ChatDeepSeek chat model.""" from typing import Optional, Type import pytest from langchain_core.language_models import BaseChatModel from langchain_core.messages import AIMessageChunk, BaseMessageChunk from langchain_core.tools import BaseTool from langchain_tests.integration_tests import ChatModelIntegration...
from __future__ import annotations from sentence_transformers.losses.MSELoss import MSELoss from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder class SparseMSELoss(MSELoss): def __init__(self, model: SparseEncoder) -> None: """ Computes the MSE loss between the computed s...
from __future__ import annotations from sentence_transformers.losses.MSELoss import MSELoss from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder class SparseMSELoss(MSELoss): def __init__(self, model: SparseEncoder) -> None: """ # TODO: Update as it's mentionned trainings ...
from pathlib import Path import numpy as np import pytest as pytest from jina import Document, DocumentArray, Executor compose_yml = Path(__file__).parent / 'docker-compose.yml' def test_config(): ex = Executor.load_config(str(Path(__file__).parents[1] / 'config.yml')) assert ex.port == 6379 @pytest.mark....
import os import numpy as np import pytest as pytest from jina import Document, DocumentArray cur_dir = os.path.dirname(os.path.abspath(__file__)) compose_yml = os.path.abspath(os.path.join(cur_dir, 'docker-compose.yml')) @pytest.mark.parametrize('docker_compose', [compose_yml], indirect=['docker_compose']) def tes...
from __future__ import annotations from sentence_transformers import SentenceTransformer, losses, util class AnglELoss(losses.CoSENTLoss): def __init__(self, model: SentenceTransformer, scale: float = 20.0) -> None: """ This class implements AnglE (Angle Optimized) loss. This is a modific...
from __future__ import annotations from sentence_transformers import SentenceTransformer, losses, util class AnglELoss(losses.CoSENTLoss): def __init__(self, model: SentenceTransformer, scale: float = 20.0) -> None: """ This class implements AnglE (Angle Optimized) loss. This is a modific...
# Copyright (c) OpenMMLab. All rights reserved. from typing import Optional import torch.nn as nn import torch.nn.functional as F from torch import Tensor from mmdet.registry import MODELS from .utils import weighted_loss @weighted_loss def knowledge_distillation_kl_div_loss(pred: Tensor, ...
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn import torch.nn.functional as F from mmdet.registry import MODELS from .utils import weighted_loss @weighted_loss def knowledge_distillation_kl_div_loss(pred, soft_label, ...
import asyncio import time import pytest from jina import Client, Deployment, Executor, requests from jina._docarray import Document, DocumentArray from jina.excepts import BadServer from jina.helper import random_port class MyExecutor(Executor): @requests(on='/hello') async def task(self, doc: Document, **...
import asyncio import time import pytest from jina import Client, Deployment, Executor, requests from jina._docarray import Document, DocumentArray from jina.excepts import BadServer from jina.helper import random_port class MyExecutor(Executor): @requests(on='/hello') async def task(self, doc: Document, **...
from ._source_separation_pipeline import ( CONVTASNET_BASE_LIBRI2MIX, HDEMUCS_HIGH_MUSDB, HDEMUCS_HIGH_MUSDB_PLUS, SourceSeparationBundle, ) from ._squim_pipeline import SQUIM_OBJECTIVE, SQUIM_SUBJECTIVE, SquimObjectiveBundle, SquimSubjectiveBundle from ._tts import ( TACOTRON2_GRIFFINLIM_CHAR_LJSPE...
from ._source_separation_pipeline import ( CONVTASNET_BASE_LIBRI2MIX, HDEMUCS_HIGH_MUSDB, HDEMUCS_HIGH_MUSDB_PLUS, SourceSeparationBundle, ) from ._tts import ( TACOTRON2_GRIFFINLIM_CHAR_LJSPEECH, TACOTRON2_GRIFFINLIM_PHONE_LJSPEECH, TACOTRON2_WAVERNN_CHAR_LJSPEECH, TACOTRON2_WAVERNN_PHO...
"""Tool for the Wikidata API.""" from typing import Optional from langchain_core.callbacks import CallbackManagerForToolRun from langchain_core.tools import BaseTool from langchain_community.utilities.wikidata import WikidataAPIWrapper class WikidataQueryRun(BaseTool): """Tool that searches the Wikidata API.""...
"""Tool for the Wikidata API.""" from typing import Optional from langchain_core.callbacks import CallbackManagerForToolRun from langchain_core.tools import BaseTool from langchain_community.utilities.wikidata import WikidataAPIWrapper class WikidataQueryRun(BaseTool): # type: ignore[override] """Tool that se...
import os import time import pytest from jina.excepts import RuntimeFailToStart from jina.orchestrate.pods import Pod from jina.parsers import set_gateway_parser from jina.serve.runtimes import asyncio as runtime_asyncio from jina.serve.executors import BaseExecutor from tests.helper import _generate_pod_args @pyte...
import os import time import pytest from jina.excepts import RuntimeFailToStart from jina.orchestrate.pods import Pod from jina.parsers import set_gateway_parser from jina.serve.runtimes import asyncio as runtime_asyncio from jina.serve.executors import BaseExecutor from tests.helper import _generate_pod_args @pyte...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.models.cloning import clone_model as clone_model from keras.src.models.model import Model as Model from keras.src.models.model import model_from_json as model_from_json from keras.src...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.src.models.cloning import clone_model from keras.src.models.model import Model from keras.src.models.model import model_from_json from keras.src.models.sequential import Sequential from k...
# Copyright (c) OpenMMLab. All rights reserved. from .interpolation import InterpolateTracklets from .kalman_filter import KalmanFilter from .similarity import embed_similarity __all__ = ['KalmanFilter', 'InterpolateTracklets', 'embed_similarity']
# Copyright (c) OpenMMLab. All rights reserved. from .interpolation import InterpolateTracklets from .kalman_filter import KalmanFilter __all__ = ['KalmanFilter', 'InterpolateTracklets']
from typing import TYPE_CHECKING, Any, Generic, Type, TypeVar, Union import numpy as np from docarray.typing.tensor.abstract_tensor import AbstractTensor from docarray.typing.tensor.ndarray import NdArray from docarray.utils._internal.misc import is_tf_available, is_torch_available # noqa torch_available = is_torch...
from typing import Union from docarray.typing.tensor.ndarray import NdArray from docarray.utils._internal.misc import is_tf_available, is_torch_available torch_available = is_torch_available() if torch_available: from docarray.typing.tensor.torch_tensor import TorchTensor # noqa: F401 tf_available = is_tf_avai...
# Copyright 2024 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
# Copyright 2024 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
import os from pathlib import Path from typing import Any, Callable, Optional, Tuple, Union from PIL import Image from .utils import check_integrity, download_and_extract_archive, download_url from .vision import VisionDataset class SBU(VisionDataset): """`SBU Captioned Photo <http://www.cs.virginia.edu/~vicent...
import os from typing import Any, Callable, Optional, Tuple from PIL import Image from .utils import check_integrity, download_and_extract_archive, download_url from .vision import VisionDataset class SBU(VisionDataset): """`SBU Captioned Photo <http://www.cs.virginia.edu/~vicente/sbucaptions/>`_ Dataset. ...
from typing import TYPE_CHECKING, Optional, Type from langchain_core.callbacks import ( CallbackManagerForToolRun, ) from langchain_core.tools import BaseTool from pydantic import BaseModel, Field if TYPE_CHECKING: # This is for linting and IDE typehints import multion else: try: # We do this ...
from typing import TYPE_CHECKING, Optional, Type from langchain_core.callbacks import ( CallbackManagerForToolRun, ) from langchain_core.tools import BaseTool from pydantic import BaseModel, Field if TYPE_CHECKING: # This is for linting and IDE typehints import multion else: try: # We do this ...
from typing import Any from langchain_core.memory import BaseMemory class SimpleMemory(BaseMemory): """Simple memory for storing context or other information that shouldn't ever change between prompts. """ memories: dict[str, Any] = dict() @property def memory_variables(self) -> list[str]: ...
from typing import Any from langchain_core.memory import BaseMemory class SimpleMemory(BaseMemory): """Simple memory for storing context or other information that shouldn't ever change between prompts. """ memories: dict[str, Any] = dict() @property def memory_variables(self) -> list[str]: ...
_base_ = './cascade-mask-rcnn_r50_fpn_20e_coco.py' model = dict( backbone=dict( type='ResNeXt', depth=101, groups=64, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), style='py...
_base_ = './cascade_mask_rcnn_r50_fpn_20e_coco.py' model = dict( backbone=dict( type='ResNeXt', depth=101, groups=64, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), style='py...
_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...
""" This script contains an example how to perform semantic search with Elasticsearch. You need Elasticsearch up and running locally: https://www.elastic.co/guide/en/elasticsearch/reference/current/run-elasticsearch-locally.html Further, you need the Python Elasticsearch Client installed: https://elasticsearch-py.rea...
""" This script contains an example how to perform semantic search with Elasticsearch. You need Elasticsearch up and running locally: https://www.elastic.co/guide/en/elasticsearch/reference/current/run-elasticsearch-locally.html Further, you need the Python Elasticsearch Client installed: https://elasticsearch-py.rea...
import numpy as np import torch from docarray import Document from docarray.document import AnyDocument from docarray.typing import AnyUrl, Embedding, ImageUrl, NdArray, TextUrl, TorchTensor def test_proto_all_types(): class Mymmdoc(Document): tensor: NdArray torch_tensor: TorchTensor emb...
import numpy as np import torch from docarray import Document from docarray.document import AnyDocument from docarray.typing import AnyUrl, Embedding, ImageUrl, NdArray, TextUrl, TorchTensor def test_proto_all_types(): class Mymmdoc(Document): tensor: NdArray torch_tensor: TorchTensor emb...
""" This file is part of the private API. Please do not use directly these classes as they will be modified on future versions without warning. The classes should be accessed only via the transforms argument of Weights. """ from typing import Optional, Union import PIL.Image import torch from torch import Tensor fr...
""" This file is part of the private API. Please do not use directly these classes as they will be modified on future versions without warning. The classes should be accessed only via the transforms argument of Weights. """ from typing import List, Optional, Tuple, Union import PIL.Image import torch from torch impor...
from typing import Any, Dict, Optional, Type from jina.jaml.parsers.base import BaseLegacyParser from jina.serve.gateway import BaseGateway class GatewayLegacyParser(BaseLegacyParser): """Legacy parser for gateway.""" def parse( self, cls: Type['BaseGateway'], data: Dict, run...
from typing import Any, Dict, Optional, Type from jina.jaml.parsers.base import BaseLegacyParser from jina.serve.gateway import BaseGateway class GatewayLegacyParser(BaseLegacyParser): """Legacy parser for gateway.""" def parse( self, cls: Type['BaseGateway'], data: Dict, run...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from jina import Flow, Document from ...laser_encoder import LaserEncoder def data_generator(num_docs): for i in range(num_docs): doc = Document( text='it is a good day! the dog sits on ...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from jina import Flow, Document from jinahub.encoder.laser_encoder import LaserEncoder def data_generator(num_docs): for i in range(num_docs): doc = Document( text='it is a good day! the...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.llms.loading import load_llm, load_llm_from_config # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling opti...
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.llms.loading import load_llm, load_llm_from_config # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling opti...
# 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...
"""Schema for Blobs and Blob Loaders. The goal is to facilitate decoupling of content loading from content parsing code. In addition, content loading code should provide a lazy loading interface by default. """ from __future__ import annotations from abc import ABC, abstractmethod from typing import TYPE_CHECKING ...
"""Schema for Blobs and Blob Loaders. The goal is to facilitate decoupling of content loading from content parsing code. In addition, content loading code should provide a lazy loading interface by default. """ from __future__ import annotations from abc import ABC, abstractmethod from typing import TYPE_CHECKING ...
from langchain_core.runnables.configurable import ( DynamicRunnable, RunnableConfigurableAlternatives, RunnableConfigurableFields, StrEnum, make_options_spec, ) __all__ = [ "DynamicRunnable", "RunnableConfigurableAlternatives", "RunnableConfigurableFields", "StrEnum", "make_opti...
from langchain_core.runnables.configurable import ( DynamicRunnable, RunnableConfigurableAlternatives, RunnableConfigurableFields, StrEnum, make_options_spec, ) __all__ = [ "DynamicRunnable", "RunnableConfigurableFields", "StrEnum", "RunnableConfigurableAlternatives", "make_opti...
# Copyright (c) OpenMMLab. All rights reserved. from typing import Tuple from torch import Tensor from mmdet.registry import MODELS from .standard_roi_head import StandardRoIHead @MODELS.register_module() class DoubleHeadRoIHead(StandardRoIHead): """RoI head for `Double Head RCNN <https://arxiv.org/abs/1904.064...
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.registry import MODELS from .standard_roi_head import StandardRoIHead @MODELS.register_module() class DoubleHeadRoIHead(StandardRoIHead): """RoI head for Double Head RCNN. https://arxiv.org/abs/1904.06493 """ def __init__(self, reg_roi_scale...
from __future__ import annotations from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Any from langchain_core.runnables.config import run_in_executor if TYPE_CHECKING: from collections.abc import Sequence from langchain_core.documents import Document class BaseDocumentTransformer(ABC): ...
from __future__ import annotations from abc import ABC, abstractmethod from collections.abc import Sequence from typing import TYPE_CHECKING, Any from langchain_core.runnables.config import run_in_executor if TYPE_CHECKING: from langchain_core.documents import Document class BaseDocumentTransformer(ABC): "...
"""``langchain-core`` defines the base abstractions for the LangChain ecosystem. The interfaces for core components like chat models, LLMs, vector stores, retrievers, and more are defined here. The universal invocation protocol (Runnables) along with a syntax for combining components (LangChain Expression Language) ar...
"""``langchain-core`` defines the base abstractions for the LangChain ecosystem. The interfaces for core components like chat models, LLMs, vector stores, retrievers, and more are defined here. The universal invocation protocol (Runnables) along with a syntax for combining components (LangChain Expression Language) ar...
from typing import ( TYPE_CHECKING, Iterable, ) from docarray.array.memory import DocumentArrayInMemory if TYPE_CHECKING: from docarray.document import Document class MatchArray(DocumentArrayInMemory): """ :class:`MatchArray` inherits from :class:`DocumentArray`. It's a subset of Documents t...
from typing import ( TYPE_CHECKING, Iterable, ) from .memory import DocumentArrayInMemory if TYPE_CHECKING: from ..document import Document class MatchArray(DocumentArrayInMemory): """ :class:`MatchArray` inherits from :class:`DocumentArray`. It's a subset of Documents that represents the ma...
# Copyright (c) OpenMMLab. All rights reserved. from .data_preprocessor import (BatchFixedSizePad, BatchResize, BatchSyncRandomResize, BoxInstDataPreprocessor, DetDataPreprocessor, MultiBranchDataPreprocessor) from .track_da...
# Copyright (c) OpenMMLab. All rights reserved. from .data_preprocessor import (BatchFixedSizePad, BatchResize, BatchSyncRandomResize, BoxInstDataPreprocessor, DetDataPreprocessor, MultiBranchDataPreprocessor) __all__ = [ ...
import os from pathlib import Path from torchaudio.datasets import gtzan from torchaudio_unittest.common_utils import ( get_whitenoise, normalize_wav, save_wav, TempDirMixin, TorchaudioTestCase, ) def get_mock_dataset(root_dir): """ root_dir: directory to the mocked dataset """ mo...
import os from pathlib import Path from torchaudio.datasets import gtzan from torchaudio_unittest.common_utils import ( TempDirMixin, TorchaudioTestCase, get_whitenoise, save_wav, normalize_wav, ) def get_mock_dataset(root_dir): """ root_dir: directory to the mocked dataset """ mo...
# Copyright (c) OpenMMLab. All rights reserved. from .anchor_free_head import AnchorFreeHead from .anchor_head import AnchorHead from .atss_head import ATSSHead from .autoassign_head import AutoAssignHead from .cascade_rpn_head import CascadeRPNHead, StageCascadeRPNHead from .centernet_head import CenterNetHead from .c...
# Copyright (c) OpenMMLab. All rights reserved. from .anchor_free_head import AnchorFreeHead from .anchor_head import AnchorHead from .atss_head import ATSSHead from .autoassign_head import AutoAssignHead from .cascade_rpn_head import CascadeRPNHead, StageCascadeRPNHead from .centernet_head import CenterNetHead from .c...
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any from sentence_transformers.evaluation import TranslationEvaluator if TYPE_CHECKING: import numpy as np from torch import Tensor from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder logger = ...
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any from sentence_transformers.evaluation import TranslationEvaluator if TYPE_CHECKING: import numpy as np from torch import Tensor from sentence_transformers.sparse_encoder.SparseEncoder import SparseEncoder logger = ...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from typing import Dict, Optional, Tuple import numpy as np import paddlehub as hub from jina import DocumentArray, Executor, requests from jina_commons.batching import get_docs_batch_generator class TextPaddl...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from typing import Optional, List, Any, Dict, Tuple import numpy as np import paddlehub as hub from jina import Executor, DocumentArray, requests from jina_commons.batching import get_docs_batch_generator clas...
import os from abc import abstractmethod from typing import Union from unittest import mock import pytest from langchain_core.tools import BaseTool from pydantic import SecretStr from langchain_tests.base import BaseStandardTests class ToolsTests(BaseStandardTests): """ :private: Base class for testing ...
import os from abc import abstractmethod from typing import Tuple, Type, Union from unittest import mock import pytest from langchain_core.tools import BaseTool from pydantic import SecretStr from langchain_tests.base import BaseStandardTests class ToolsTests(BaseStandardTests): """ :private: Base class...
""" Borrowed from Langchain's Neo4j graph utility functions. https://github.com/langchain-ai/langchain/blob/95c3e5f85f8ed8026a11e351b57bfae488d654c4/libs/community/langchain_community/graphs/neo4j_graph.py """ from typing import Any LIST_LIMIT = 128 def clean_string_values(text: str) -> str: return text.replac...
"""Borrowed from Langchain's Neo4j graph utility functions. https://github.com/langchain-ai/langchain/blob/95c3e5f85f8ed8026a11e351b57bfae488d654c4/libs/community/langchain_community/graphs/neo4j_graph.py """ from typing import Any LIST_LIMIT = 128 def clean_string_values(text: str) -> str: return text.replace...
# Copyright (c) OpenMMLab. All rights reserved. import pickle from .base import BaseFileHandler class PickleHandler(BaseFileHandler): str_like = False def load_from_fileobj(self, file, **kwargs): return pickle.load(file, **kwargs) def load_from_path(self, filepath, **kwargs): return su...
# Copyright (c) OpenMMLab. All rights reserved. import pickle from .base import BaseFileHandler class PickleHandler(BaseFileHandler): str_like = False def load_from_fileobj(self, file, **kwargs): return pickle.load(file, **kwargs) def load_from_path(self, filepath, **kwargs): return su...
# dataset settings dataset_type = 'Objects365V2Dataset' data_root = 'data/Objects365/Obj365_v2/' # 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/detectio...
# dataset settings dataset_type = 'Objects365V2Dataset' data_root = 'data/Objects365/Obj365_v2/' # file_client_args = dict( # backend='petrel', # path_mapping=dict({ # './data/': 's3://openmmlab/datasets/detection/', # 'data/': 's3://openmmlab/datasets/detection/' # })) file_client_args = d...
_base_ = '../retinanet/retinanet_r50_fpn_1x_coco.py' # model settings model = dict( type='FSAF', bbox_head=dict( type='FSAFHead', num_classes=80, in_channels=256, stacked_convs=4, feat_channels=256, reg_decoded_bbox=True, # Only anchor-free branch is imple...
_base_ = '../retinanet/retinanet_r50_fpn_1x_coco.py' # model settings model = dict( type='FSAF', bbox_head=dict( type='FSAFHead', num_classes=80, in_channels=256, stacked_convs=4, feat_channels=256, reg_decoded_bbox=True, # Only anchor-free branch is imple...
import torch from docarray import BaseDocument from docarray.typing import TorchEmbedding, TorchTensor def test_set_torch_tensor(): class MyDocument(BaseDocument): tensor: TorchTensor d = MyDocument(tensor=torch.zeros((3, 224, 224))) assert isinstance(d.tensor, TorchTensor) assert isinstanc...
import torch from docarray import Document from docarray.typing import TorchEmbedding, TorchTensor def test_set_torch_tensor(): class MyDocument(Document): tensor: TorchTensor d = MyDocument(tensor=torch.zeros((3, 224, 224))) assert isinstance(d.tensor, TorchTensor) assert isinstance(d.tens...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import subprocess import pytest from jina import Document, Flow from ...torch_object_detection_segmenter import TorchObjectDetectionSegmenter def test_exec(): f = Flow().add(uses=TorchObjectDetectionSegme...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from jina import Document, Flow from ...torch_object_detection_segmenter import TorchObjectDetectionSegmenter def test_exec(): f = Flow().add(uses=TorchObjectDetectionSegmenter) with f: resp = ...
import os import tempfile import httpx import pytest from PIL import Image from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.embeddings.cohere import CohereEmbedding from llama_index.embeddings.cohere.base import VALID_MODEL_INPUT_TYPES def test_embedding_class(): emb = CohereEmbed...
import os import httpx import pytest from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.embeddings.cohere import CohereEmbedding def test_embedding_class(): emb = CohereEmbedding(api_key="token") assert isinstance(emb, BaseEmbedding) @pytest.mark.skipif( os.environ.get("C...
import json import multiprocessing import os import time import pytest from jina.helper import random_port from jina.parsers import set_gateway_parser, set_pod_parser from jina.serve.runtimes.gateway import GatewayRuntime from jina.serve.runtimes.worker import WorkerRuntime from tests.helper import ( _validate_cu...
import json import multiprocessing import os import time import pytest from jina.helper import random_port from jina.parsers import set_gateway_parser, set_pod_parser from jina.serve.runtimes.gateway import GatewayRuntime from jina.serve.runtimes.worker import WorkerRuntime from tests.helper import ( _validate_cu...
_base_ = './vfnet_r50_fpn_1x_coco.py' train_pipeline = [ dict(type='LoadImageFromFile', backend_args={{_base_.backend_args}}), dict(type='LoadAnnotations', with_bbox=True), dict( type='RandomResize', scale=[(1333, 480), (1333, 960)], keep_ratio=True), dict(type='RandomFlip', prob=0.5), ...
_base_ = './vfnet_r50_fpn_1x_coco.py' train_pipeline = [ dict( type='LoadImageFromFile', file_client_args={{_base_.file_client_args}}), dict(type='LoadAnnotations', with_bbox=True), dict( type='RandomResize', scale=[(1333, 480), (1333, 960)], keep_ratio=True), dict(type='...
# Copyright (c) OpenMMLab. All rights reserved. import torch def mask_matrix_nms(masks, labels, scores, filter_thr=-1, nms_pre=-1, max_num=-1, kernel='gaussian', sigma=2.0, ...
# Copyright (c) OpenMMLab. All rights reserved. import torch def mask_matrix_nms(masks, labels, scores, filter_thr=-1, nms_pre=-1, max_num=-1, kernel='gaussian', sigma=2.0, ...
# Copyright (c) OpenMMLab. All rights reserved. from ..builder import BBOX_CODERS from ..transforms import bbox2distance, distance2bbox from .base_bbox_coder import BaseBBoxCoder @BBOX_CODERS.register_module() class DistancePointBBoxCoder(BaseBBoxCoder): """Distance Point BBox coder. This coder encodes gt bb...
from ..builder import BBOX_CODERS from ..transforms import bbox2distance, distance2bbox from .base_bbox_coder import BaseBBoxCoder @BBOX_CODERS.register_module() class DistancePointBBoxCoder(BaseBBoxCoder): """Distance Point BBox coder. This coder encodes gt bboxes (x1, y1, x2, y2) into (top, bottom, left, ...
_base_ = './retinanet_r50-caffe_fpn_ms-1x_coco.py' # training schedule for 2x train_cfg = dict(max_epochs=36) # learning rate policy param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', begin=0, end=36, ...
_base_ = './retinanet_r50_caffe_fpn_mstrain_1x_coco.py' # training schedule for 2x train_cfg = dict(max_epochs=36) # learning rate policy param_scheduler = [ dict( type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), dict( type='MultiStepLR', begin=0, end=36,...
from .cmuarctic import CMUARCTIC from .cmudict import CMUDict from .commonvoice import COMMONVOICE from .dr_vctk import DR_VCTK from .gtzan import GTZAN from .librimix import LibriMix from .librispeech import LIBRISPEECH from .libritts import LIBRITTS from .ljspeech import LJSPEECH from .quesst14 import QUESST14 from ....
from .cmuarctic import CMUARCTIC from .cmudict import CMUDict from .commonvoice import COMMONVOICE from .dr_vctk import DR_VCTK from .gtzan import GTZAN from .librimix import LibriMix from .librispeech import LIBRISPEECH from .libritts import LIBRITTS from .ljspeech import LJSPEECH from .speechcommands import SPEECHCOM...
from torchvision.transforms import InterpolationMode # usort: skip from ._utils import is_pure_tensor, register_kernel # usort: skip from ._meta import ( clamp_bounding_boxes, convert_bounding_box_format, get_dimensions_image, get_dimensions_video, get_dimensions, get_num_frames_video, g...
from torchvision.transforms import InterpolationMode # usort: skip from ._utils import is_pure_tensor, register_kernel # usort: skip from ._meta import ( clamp_bounding_boxes, convert_bounding_box_format, get_dimensions_image, _get_dimensions_image_pil, get_dimensions_video, get_dimensions, ...
from jina import DocumentArray, Executor, Flow, requests def test_gateway_metric_labels(monkeypatch_metric_exporter): collect_metrics, read_metrics = monkeypatch_metric_exporter class FirstExec(Executor): @requests() def meow(self, docs, **kwargs): return DocumentArray.empty(3) ...
from jina import DocumentArray, Executor, Flow, requests def test_gateway_metric_labels(monkeypatch_metric_exporter): collect_metrics, read_metrics = monkeypatch_metric_exporter class FirstExec(Executor): @requests() def meow(self, docs, **kwargs): return DocumentArray.empty(3) ...
import os import warnings from modulefinder import Module import torch from torchvision import datasets, io, models, ops, transforms, utils from .extension import _HAS_OPS try: from .version import __version__ # noqa: F401 except ImportError: pass # Check if torchvision is being imported within the root f...
import os import warnings from modulefinder import Module import torch from torchvision import datasets, io, models, ops, transforms, utils from .extension import _HAS_OPS try: from .version import __version__ # noqa: F401 except ImportError: pass # Check if torchvision is being imported within the root f...
# Copyright (c) OpenMMLab. All rights reserved. from .fileio import (FileClient, dict_from_file, dump, list_from_file, load, register_handler) from .misc import (check_prerequisites, concat_list, deprecated_api_warning, has_method, import_modules_from_strings, is_list_of, ...
# Copyright (c) OpenMMLab. All rights reserved. # type: ignore from .fileio import (FileClient, dict_from_file, dump, list_from_file, load, register_handler) from .misc import (check_prerequisites, concat_list, deprecated_api_warning, has_method, import_modules_from_strings, is_l...
import numpy as np import pytest from keras.src import backend from keras.src import initializers from keras.src import layers from keras.src import models from keras.src import testing class SpectralNormalizationTest(testing.TestCase): @pytest.mark.requires_trainable_backend def test_basic_spectralnorm(self...
import numpy as np import pytest from keras.src import backend from keras.src import initializers from keras.src import layers from keras.src import models from keras.src import testing class SpectralNormalizationTest(testing.TestCase): @pytest.mark.requires_trainable_backend def test_basic_spectralnorm(self...
import os from unittest import TestCase import cv2 import numpy as np import torch from mmengine.data import InstanceData, PixelData from mmdet.evaluation import INSTANCE_OFFSET from mmdet.structures import DetDataSample from mmdet.visualization import DetLocalVisualizer def _rand_bboxes(num_boxes, h, w): cx, c...
import os from unittest import TestCase import cv2 import numpy as np import torch from mmengine.data import InstanceData, PixelData from mmdet.evaluation import INSTANCE_OFFSET from mmdet.structures import DetDataSample from mmdet.visualization import DetLocalVisualizer def _rand_bboxes(num_boxes, h, w): cx, c...
from typing import TypeVar from docarray.typing.proto_register import _register_proto from docarray.typing.tensor.image.abstract_image_tensor import AbstractImageTensor from docarray.typing.tensor.torch_tensor import TorchTensor, metaTorchAndNode T = TypeVar('T', bound='ImageTorchTensor') @_register_proto(proto_typ...
from typing import TypeVar from docarray.typing.proto_register import _register_proto from docarray.typing.tensor.image.abstract_image_tensor import AbstractImageTensor from docarray.typing.tensor.torch_tensor import TorchTensor, metaTorchAndNode T = TypeVar('T', bound='ImageTorchTensor') @_register_proto(proto_typ...
from __future__ import annotations from sentence_transformers.sparse_encoder.evaluation.SparseBinaryClassificationEvaluator import ( SparseBinaryClassificationEvaluator, ) from sentence_transformers.sparse_encoder.evaluation.SparseEmbeddingSimilarityEvaluator import ( SparseEmbeddingSimilarityEvaluator, ) from...
from __future__ import annotations from sentence_transformers.sparse_encoder.evaluation.SparseEmbeddingSimilarityEvaluator import ( SparseEmbeddingSimilarityEvaluator, ) from sentence_transformers.sparse_encoder.evaluation.SparseInformationRetrievalEvaluator import ( SparseInformationRetrievalEvaluator, ) __a...
_base_ = './cascade-mask-rcnn_r50_fpn_ms-3x_coco.py' model = dict( # ResNeXt-101-32x8d model trained with Caffe2 at FB, # so the mean and std need to be changed. data_preprocessor=dict( type='DetDataPreprocessor', mean=[103.530, 116.280, 123.675], std=[57.375, 57.120, 58.395], ...
_base_ = './cascade-mask-rcnn_r50_fpn_ms-3x_coco.py' model = dict( # ResNeXt-101-32x8d model trained with Caffe2 at FB, # so the mean and std need to be changed. data_preprocessor=dict( type='DetDataPreprocessor', mean=[103.530, 116.280, 123.675], std=[57.375, 57.120, 58.395], ...
from keras.src.backend.config import backend if backend() == "torch": # When using the torch backend, # torch needs to be imported first, otherwise it will segfault # upon import. import torch from keras.src.api_export import keras_export from keras.src.backend.common.dtypes import result_type from ke...
from keras.src.backend.config import backend if backend() == "torch": # When using the torch backend, # torch needs to be imported first, otherwise it will segfault # upon import. import torch from keras.src.api_export import keras_export from keras.src.backend.common.dtypes import result_type from ke...
# Copyright (c) OpenMMLab. All rights reserved. import warnings import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import ConvModule from mmcv.runner import BaseModule, auto_fp16, force_fp32 from mmdet.models.builder import HEADS, build_loss @HEADS.register_module() class FusedSemanticHead(BaseModu...
# Copyright (c) OpenMMLab. All rights reserved. import warnings import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import ConvModule from mmcv.runner import BaseModule, auto_fp16, force_fp32 from mmdet.models.builder import HEADS, build_loss @HEADS.register_module() class FusedSemanticHead(BaseModu...
_base_ = './fcos_r50_fpn_gn-head-center-normbbox-centeronreg-giou_8xb8-amp-lsj-200e_coco.py' # noqa model = dict( backbone=dict( depth=18, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet18')), neck=dict(in_channels=[64, 128, 256, 512]))
_base_ = './fcos_center-normbbox-centeronreg-giou_r50_fpn_gn-head_lsj_200e_8x8_fp16_coco.py' # noqa model = dict( backbone=dict( depth=18, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet18')), neck=dict(in_channels=[64, 128, 256, 512]))
# Licensed to the LF AI & Data foundation under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the "License"); # you may not use this fil...
from typing import Any, Dict, List, Optional, Union from docarray.utils._internal.query_language.lookup import ( LookupLeaf, LookupNode, LookupTreeElem, Q, ) LOGICAL_OPERATORS: Dict[str, Union[str, bool]] = { '$and': 'and', '$or': 'or', '$not': True, } COMPARISON_OPERATORS = { '$lt': ...
from __future__ import annotations try: from typing import Self except ImportError: from typing_extensions import Self import torch from torch import nn from sentence_transformers.models.Module import Module class CNN(Module): """CNN-layer with multiple kernel-sizes over the word embeddings""" con...
from __future__ import annotations import json import os import torch from safetensors.torch import load_model as load_safetensors_model from safetensors.torch import save_model as save_safetensors_model from torch import nn class CNN(nn.Module): """CNN-layer with multiple kernel-sizes over the word embeddings"...
# mypy: allow-untyped-defs import sys from contextlib import contextmanager from typing import TYPE_CHECKING import torch from torch.backends import ( __allow_nonbracketed_mutation, _FP32Precision, _get_fp32_precision_getter, _set_fp32_precision_setter, ContextProp, PropModule, ) def is_avail...
# mypy: allow-untyped-defs import sys from contextlib import contextmanager from typing import TYPE_CHECKING import torch from torch.backends import __allow_nonbracketed_mutation, ContextProp, PropModule def is_available(): r"""Return whether PyTorch is built with MKL-DNN support.""" return torch._C._has_mkl...
from llama_index.core.schema import NodeRelationship, RelatedNodeInfo, TextNode from llama_index.vector_stores.lancedb import LanceDBVectorStore from llama_index.core import VectorStoreIndex import lance # noqa: F401 import pytest import pytest_asyncio try: from llama_index.embeddings.huggingface import HuggingF...
from llama_index.core.schema import NodeRelationship, RelatedNodeInfo, TextNode from llama_index.vector_stores.lancedb import LanceDBVectorStore from llama_index.core import VectorStoreIndex import pytest import pytest_asyncio try: from llama_index.embeddings.huggingface import HuggingFaceEmbedding from lanced...
""" Train XGBoost with cat_in_the_dat dataset ========================================= A simple demo for categorical data support using dataset from Kaggle categorical data tutorial. The excellent tutorial is at: https://www.kaggle.com/shahules/an-overview-of-encoding-techniques And the data can be found at: https:...
""" Train XGBoost with cat_in_the_dat dataset ========================================= A simple demo for categorical data support using dataset from Kaggle categorical data tutorial. The excellent tutorial is at: https://www.kaggle.com/shahules/an-overview-of-encoding-techniques And the data can be found at: https:...
_base_ = [ '../_base_/models/mask_rcnn_r50_fpn.py', '../_base_/datasets/coco_instance.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] pretrained = 'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_tiny_patch4_window7_224.pth' # noqa model = dict( type...
_base_ = [ '../_base_/models/mask_rcnn_r50_fpn.py', '../_base_/datasets/coco_instance.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] pretrained = 'https://download.openmmlab.com/mmclassification/v0/swin-transformer/swin_tiny_224_b16x64_300e_imagenet_20210616_090925-66df6be6.pth'...
from typing import TYPE_CHECKING, Any, Type, TypeVar, Union from docarray.base_doc import BaseDoc from docarray.typing.tensor.tensor import AnyTensor from docarray.utils._internal.misc import import_library T = TypeVar('T', bound='VerticesAndFaces') class VerticesAndFaces(BaseDoc): """ Document for handling...
from typing import TYPE_CHECKING, Any, Type, TypeVar, Union from docarray.base_doc import BaseDoc from docarray.typing.tensor.tensor import AnyTensor from docarray.utils._internal.misc import import_library T = TypeVar('T', bound='VerticesAndFaces') class VerticesAndFaces(BaseDoc): """ Document for handling...
"""Determination of parameter bounds""" # Authors: The scikit-learn developers # SPDX-License-Identifier: BSD-3-Clause from numbers import Real import numpy as np from ..preprocessing import LabelBinarizer from ..utils._param_validation import Interval, StrOptions, validate_params from ..utils.extmath import safe_s...
"""Determination of parameter bounds""" # Authors: The scikit-learn developers # SPDX-License-Identifier: BSD-3-Clause from numbers import Real import numpy as np from ..preprocessing import LabelBinarizer from ..utils._param_validation import Interval, StrOptions, validate_params from ..utils.extmath import safe_s...
from typing import Dict MISTRALAI_MODELS: Dict[str, int] = { "mistral-tiny": 32000, "mistral-small": 32000, "mistral-medium": 32000, "mistral-large": 131000, "mistral-saba-latest": 32000, "open-mixtral-8x7b": 32000, "open-mistral-7b": 32000, "open-mixtral-8x22b": 64000, "mistral-sma...
from typing import Dict MISTRALAI_MODELS: Dict[str, int] = { "mistral-tiny": 32000, "mistral-small": 32000, "mistral-medium": 32000, "mistral-large": 32000, "open-mixtral-8x7b": 32000, "open-mistral-7b": 32000, "open-mixtral-8x22b": 64000, "mistral-small-latest": 32000, "mistral-med...
"""Argparser module for WorkerRuntime""" from jina.parsers.helper import KVAppendAction def mixin_base_runtime_parser(arg_group): """Mixing in arguments required by any class that extends :class:`AsynNewLoopRuntime` into the given parser. :param arg_group: the parser instance to which we add arguments ""...
"""Argparser module for WorkerRuntime""" from jina.parsers.helper import KVAppendAction def mixin_base_runtime_parser(arg_group): """Mixing in arguments required by any class that extends :class:`AsynNewLoopRuntime` into the given parser. :param arg_group: the parser instance to which we add arguments ""...
# coding=utf-8 # Copyright 2024 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # """ Utility that checks that mo...
# coding=utf-8 # Copyright 2024 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # """ Utility that checks that mo...
from typing import Any, Iterator, List, Optional from urllib.parse import urljoin, urlparse from langchain_core.documents import Document from langchain_community.document_loaders.web_base import WebBaseLoader class GitbookLoader(WebBaseLoader): """Load `GitBook` data. 1. load from either a single page, or...
from typing import Any, Iterator, List, Optional from urllib.parse import urljoin, urlparse from langchain_core.documents import Document from langchain_community.document_loaders.web_base import WebBaseLoader class GitbookLoader(WebBaseLoader): """Load `GitBook` data. 1. load from either a single page, or...
"""Test Fireworks LLM.""" from typing import cast from pydantic import SecretStr from pytest import CaptureFixture, MonkeyPatch from langchain_fireworks import Fireworks def test_fireworks_api_key_is_secret_string() -> None: """Test that the API key is stored as a SecretStr.""" llm = Fireworks( # type: ig...
"""Test Fireworks LLM""" from typing import cast from pydantic import SecretStr from pytest import CaptureFixture, MonkeyPatch from langchain_fireworks import Fireworks def test_fireworks_api_key_is_secret_string() -> None: """Test that the API key is stored as a SecretStr.""" llm = Fireworks( # type: ign...
__version__ = '0.12.2' import os from .document import Document from .array import DocumentArray from .dataclasses import dataclass, field if 'DA_NO_RICH_HANDLER' not in os.environ: from rich.traceback import install install()
__version__ = '0.12.1' import os from .document import Document from .array import DocumentArray from .dataclasses import dataclass, field if 'DA_NO_RICH_HANDLER' not in os.environ: from rich.traceback import install install()
"""Standard LangChain interface tests""" import pytest from langchain_core.language_models import BaseChatModel from langchain_core.rate_limiters import InMemoryRateLimiter from langchain_core.tools import BaseTool from langchain_tests.integration_tests import ( ChatModelIntegrationTests, ) from langchain_groq im...
"""Standard LangChain interface tests""" from typing import Type import pytest from langchain_core.language_models import BaseChatModel from langchain_core.rate_limiters import InMemoryRateLimiter from langchain_core.tools import BaseTool from langchain_tests.integration_tests import ( ChatModelIntegrationTests, ...
from typing import Any, Dict, Optional, Union import PIL.Image import torch from torchvision.prototype import features from torchvision.prototype.transforms import functional as F, Transform class ConvertBoundingBoxFormat(Transform): _transformed_types = (features.BoundingBox,) def __init__(self, format: U...
from typing import Any, Dict, Optional, Union import PIL.Image import torch from torchvision.prototype import features from torchvision.prototype.transforms import functional as F, Transform class ConvertBoundingBoxFormat(Transform): _transformed_types = (features.BoundingBox,) def __init__(self, format: U...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.api.utils import legacy from keras.src.backend.common.global_state import clear_session from keras.src.backend.common.keras_tensor import is_keras_tensor from keras.src.backend.common.var...
"""DO NOT EDIT. This file was autogenerated. Do not edit it by hand, since your modifications would be overwritten. """ from keras.api.utils import legacy from keras.src.backend.common.global_state import clear_session from keras.src.backend.common.keras_tensor import is_keras_tensor from keras.src.backend.common.var...
from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.embeddings.huggingface import ( HuggingFaceEmbedding, HuggingFaceInferenceAPIEmbedding, ) def test_huggingfaceembedding_class(): names_of_base_classes = [b.__name__ for b in HuggingFaceEmbedding.__mro__] assert BaseEmbedd...
from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.embeddings.huggingface import ( HuggingFaceEmbedding, HuggingFaceInferenceAPIEmbedding, ) import pytest def test_huggingfaceembedding_class(): names_of_base_classes = [b.__name__ for b in HuggingFaceEmbedding.__mro__] ass...
# Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed according to the terms of the GNU General Public License version 3. from typing import Tuple import os import sys import torch import fire import time import json from pathlib import Path from fairscale.nn.model_parallel...
# Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed according to the terms of the GNU General Public License version 3. from typing import Tuple import os import sys import torch import fire import time import json from pathlib import Path from fairscale.nn.model_parallel...
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
# Copyright (c) OpenMMLab. All rights reserved. from .ade20k import (ADE20KInstanceDataset, ADE20KPanopticDataset, ADE20KSegDataset) from .base_det_dataset import BaseDetDataset from .base_semseg_dataset import BaseSegDataset from .base_video_dataset import BaseVideoDataset from .cityscapes import ...
# Copyright (c) OpenMMLab. All rights reserved. from .base_det_dataset import BaseDetDataset from .cityscapes import CityscapesDataset from .coco import CocoDataset from .coco_panoptic import CocoPanopticDataset from .crowdhuman import CrowdHumanDataset from .dataset_wrappers import MultiImageMixDataset from .deepfashi...