python_code
stringlengths
0
992k
repo_name
stringlengths
8
46
file_path
stringlengths
5
162
import pytest from unittest.mock import Mock from swarms.workers.worker_agent_ultra import WorkerUltraNode # import your module here def test_create_agent(): mock_llm = Mock() mock_toolset = { 'test_toolset': Mock() } mock_vectorstore = Mock() worker = WorkerUltraNode(mock_llm, mock_toolset, mock_vect...
swarms-master
tests/agents/workers/worker_agent_ultra.py
import pytest from unittest.mock import Mock, patch from swarms.workers.worker_agent_ultra import WorkerUltraNode, WorkerUltraNodeInitializer @pytest.fixture def llm_mock(): return Mock() @pytest.fixture def toolsets_mock(): return Mock() @pytest.fixture def vectorstore_mock(): return Mock() @pytest.f...
swarms-master
tests/agents/workers/worker_ultra.py
import pytest from unittest.mock import Mock from swarms.workers.multi_modal_worker import MultiModalVisualAgent, MultiModalVisualAgentTool @pytest.fixture def multimodal_agent(): # Mock the MultiModalVisualAgent mock_agent = Mock(spec=MultiModalVisualAgent) mock_agent.run_text.return_value = "Expected o...
swarms-master
tests/agents/workers/multi_model_worker.py
import pytest from swarms.worker.omni_worker import OmniWorkerAgent @pytest.fixture def omni_worker(): api_key = 'test-key' api_endpoint = 'test-endpoint' api_type = 'test-type' return OmniWorkerAgent(api_key, api_endpoint, api_type) @pytest.mark.parametrize("data, expected_response", [ ( ...
swarms-master
tests/agents/workers/omni_worker.py
import pytest from unittest.mock import Mock, patch from swarms.tools.agent_tools import * from swarms.boss.boss_node import BossNodeInitializer, BossNode # For initializing BossNodeInitializer in multiple tests @pytest.fixture def mock_boss_node_initializer(): llm = Mock() vectorstore = Mock() agent_execut...
swarms-master
tests/boss/boss_node.py
from swarms import Model, Agent, WorkerNode, vectorstore, tools, orchestrator #1 model Model(openai) #2 agent level Agent( model, vectorstore, tools ) #3 worker infrastructure level worker_node( Agent, human_input, tools ) #4 swarm level basically handling infrastructure for multiple worker ...
swarms-master
docs/old-docs/design/abstraction.py
swarms-master
api/__init__.py
import logging import os from fastapi import FastAPI, HTTPException, Depends from fastapi_cache.decorator import cache from fastapi_cache.coder import JsonCoder from fastapi_cache import FastAPICache from fastapi_cache.backends.redis import RedisBackend from aioredis import Redis from pydantic import BaseModel from s...
swarms-master
api/app.py
import os from celery import Celery from celery.result import AsyncResult from api.olds.container import agent_manager celery_app = Celery(__name__) celery_app.conf.broker_url = os.environ["CELERY_BROKER_URL"] celery_app.conf.result_backend = os.environ["CELERY_BROKER_URL"] celery_app.conf.update( task_track_st...
swarms-master
api/olds/worker.py
import os from pathlib import Path from typing import Dict, List from fastapi.templating import Jinja2Templates from swarms.agents.utils.agent_creator import AgentManager from swarms.utils.main import BaseHandler, FileHandler, FileType from swarms.tools.main import ExitConversation, RequestsGet, CodeEditor, Terminal ...
swarms-master
api/olds/container.py
import os import re from multiprocessing import Process from tempfile import NamedTemporaryFile from typing import List, TypedDict import uvicorn from fastapi import FastAPI, Request, UploadFile from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles from pydantic import BaseModel from...
swarms-master
api/olds/main.py
#swarms #from swarms.orchestrator.autoscaler import AutoScaler # worker # from swarms.workers.worker_node import WorkerNode #boss from swarms.boss.boss_node import Boss #models from swarms.models.anthropic import Anthropic from swarms.models.huggingface import HFLLM # from swarms.models.palm import GooglePalm from ...
swarms-master
swarms/__init__.py
swarms-master
swarms/artifacts/__init__.py
from __future__ import annotations from attr import define, field from swarms.artifacts.base import BaseArtifact @define(frozen=True) class ErrorArtifact(BaseArtifact): value: str = field(converter=str) def __add__(self, other: ErrorArtifact) -> ErrorArtifact: return ErrorArtifact(self.value + other....
swarms-master
swarms/artifacts/error_artifact.py
from __future__ import annotations import pprint import json from typing import Optional from pydantic import BaseModel, Field, StrictStr class Artifact(BaseModel): """ Artifact that has the task has been produced """ artifact_id: StrictStr = Field( ..., description="ID of the artifa...
swarms-master
swarms/artifacts/main.py
from __future__ import annotations import json import uuid from abc import ABC, abstractmethod from attr import define, field, Factory from marshmallow import class_registry from marshmallow.exceptions import RegistryError @define class BaseArtifact(ABC): id: str = field(default=Factory(lambda: uuid.uuid4().hex),...
swarms-master
swarms/artifacts/base.py
#props to shroominic from swarms.tools.base import Tool, ToolException from typing import Callable, Any, List from codeinterpreterapi import CodeInterpreterSession, File, ToolException class CodeInterpreter(Tool): def __init__(self, name: str, description: str): super().__init__(name, description, self.run...
swarms-master
swarms/tools/code_intepretor.py
# from swarms.tools.base import BaseTool, Tool, StructuredTool, ToolWrapper, BaseToolSet, ToolCreator, GlobalToolsCreator, SessionToolsCreator, ToolsFactory # from swarms.tools.autogpt import pushd, process_csv, async_load_playwright, run_async, browse_web_page, WebpageQATool, web_search, query_website_tool # from swar...
swarms-master
swarms/tools/__init__.py
import asyncio import os # Tools from contextlib import contextmanager from typing import Optional import pandas as pd from langchain.agents import tool from langchain.agents.agent_toolkits.pandas.base import create_pandas_dataframe_agent from langchain.chains.qa_with_sources.loading import load_qa_with_sources_chain...
swarms-master
swarms/tools/autogpt.py
import os import uuid import numpy as np import torch from diffusers import ( EulerAncestralDiscreteScheduler, StableDiffusionInpaintPipeline, StableDiffusionInstructPix2PixPipeline, StableDiffusionPipeline, ) from PIL import Image from transformers import ( BlipForConditionalGeneration, BlipFo...
swarms-master
swarms/tools/mm_models.py
import requests from bs4 import BeautifulSoup from swarms.tools.base import BaseToolSet, tool from swarms.utils.logger import logger class RequestsGet(BaseToolSet): @tool( name="Requests Get", description="A portal to the internet. " "Use this when you need to get specific content from a...
swarms-master
swarms/tools/requests.py
import os import re import signal import subprocess import time from datetime import datetime from pathlib import Path from typing import Callable, Dict, List, Literal, Optional, Tuple, Union from ptrace.debugger import ( NewProcessEvent, ProcessExecution, ProcessExit, ProcessSignal, PtraceDebugge...
swarms-master
swarms/tools/developer.py
from langchain.tools import tool from swarms.tools.base import BaseToolSet, SessionGetter, ToolScope from swarms.utils.logger import logger class ExitConversation(BaseToolSet): @tool( name="Exit Conversation", description="A tool to exit the conversation. " "Use this when you want to exit...
swarms-master
swarms/tools/exit_conversation.py
from __future__ import annotations from enum import Enum from abc import ABC, abstractmethod from typing import Any, Callable, Optional, Type, Tuple from pydantic import BaseModel from langchain.llms.base import BaseLLM from langchain.agents.agent import AgentExecutor from langchain.agents import load_tools class T...
swarms-master
swarms/tools/base.py
from langchain.agents.agent_toolkits import FileManagementToolkit from tempfile import TemporaryDirectory # We'll make a temporary directory to avoid clutter working_directory = TemporaryDirectory() toolkit = FileManagementToolkit( root_dir=str(working_directory.name) ) # If you don't provide a root_dir, operati...
swarms-master
swarms/tools/file_mangagement.py
swarms-master
swarms/embeddings/__init__.py
import logging from typing import Union from pegasus import Pegasus # import oceandb # from oceandb.utils.embedding_functions import MultiModalEmbeddingfunction class PegasusEmbedding: def __init__( self, modality: str, multi_process: bool = False, n_processes: ...
swarms-master
swarms/embeddings/pegasus.py
from __future__ import annotations import logging import warnings from typing import ( Any, Callable, Dict, List, Literal, Optional, Sequence, Set, Tuple, Union, ) import numpy as np from pydantic import BaseModel, Extra, Field, root_validator from tenacity import ( AsyncRe...
swarms-master
swarms/embeddings/openai.py
"""Interface for embedding models.""" from abc import ABC, abstractmethod from typing import List class Embeddings(ABC): """Interface for embedding models.""" @abstractmethod def embed_documents(self, texts: List[str]) -> List[List[float]]: """Embed search docs.""" @abstractmethod def em...
swarms-master
swarms/embeddings/base.py
import uuid from abc import ABC from typing import Any, Dict, List, Optional from swarms.memory.schemas import Artifact, Status from swarms.memory.schemas import Step as APIStep from swarms.memory.schemas import Task as APITask class Step(APIStep): additional_properties: Optional[Dict[str, str]] = None class Ta...
swarms-master
swarms/memory/db.py
swarms-master
swarms/memory/__init__.py
from __future__ import annotations from enum import Enum from typing import Any, List, Optional from pydantic import BaseModel, Field class TaskInput(BaseModel): __root__: Any = Field( ..., description="The input parameters for the task. Any value is allowed.", example='{\n"debug": false...
swarms-master
swarms/memory/schemas.py
#init ocean # TODO upload ocean to pip and config it to the abstract class import logging from typing import Union, List import oceandb from oceandb.utils.embedding_function import MultiModalEmbeddingFunction class OceanDB: def __init__(self): try: self.client = oceandb.Client() p...
swarms-master
swarms/memory/ocean.py
"""Wrapper around ChromaDB embeddings platform.""" from __future__ import annotations import logging import uuid from typing import ( TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Tuple, Type, ) import numpy as np from langchain.docstore.document import Document fr...
swarms-master
swarms/memory/chroma.py
from typing import Any, Dict, List from swarms.memory.base_memory import BaseChatMemory, get_prompt_input_key from swarms.memory.base import VectorStoreRetriever class AgentMemory(BaseChatMemory): retriever: VectorStoreRetriever """VectorStoreRetriever object to connect to.""" @property def memory_va...
swarms-master
swarms/agents/memory.py
"""Agent Infrastructure, models, memory, utils, tools""" ########### # #tools # from swarms.tools.base import BaseTool, Tool, StructuredTool, ToolWrapper, BaseToolSet, ToolCreator, GlobalToolsCreator, SessionToolsCreator, ToolsFactory # from swarms.tools.autogpt import pushd, process_csv, async_load_playwright, run_a...
swarms-master
swarms/agents/__init__.py
import logging import os import time import openai logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) class OpenAI: def __init__( self, api_key, strategy="cot", evaluation_strategy="va...
swarms-master
swarms/agents/aot.py
from __future__ import annotations from typing import List, Optional from langchain.chains.llm import LLMChain from swarms.agents.utils.Agent import AgentOutputParser from swarms.agents.utils.human_input import HumanInputRun from swarms.memory.base import VectorStoreRetriever from swarms.memory.base_memory import Ba...
swarms-master
swarms/agents/agent.py
from abc import ABC, abstractmethod from agent_protocol import Agent, Step, Task class AbstractAgent: @staticmethod async def plan(step: Step) -> Step: task = await Agent.db.get_task(step.task_id) steps = generate_steps(task.input) last_step = steps[-1] for step in steps[:-1]:...
swarms-master
swarms/agents/base.py
import logging import os from typing import Optional import faiss from langchain import LLMChain, OpenAI, PromptTemplate from langchain.agents import AgentExecutor, Tool, ZeroShotAgent from langchain.docstore import InMemoryDocstore from langchain.embeddings import OpenAIEmbeddings from langchain.vectorstores import F...
swarms-master
swarms/boss/boss_node.py
swarms-master
swarms/boss/__init__.py
from abc import ABC from typing import Any, Dict, List, Literal, TypedDict, Union, cast from pydantic import BaseModel, PrivateAttr class BaseSerialized(TypedDict): """Base class for serialized objects.""" lc: int id: List[str] class SerializedConstructor(BaseSerialized): """Serialized constructor...
swarms-master
swarms/utils/serializable.py
# from swarms.utils.ansi import Code, Color, Style, ANSI, dim_multiline # from swarms.utils.logger import logger # from swarms.utils.utils import FileType, AbstractUploader, StaticUploader, BaseHandler, FileHandler, CsvToDataframe """Swarms utils"""
swarms-master
swarms/utils/__init__.py
import logging logger = logging.getLogger() formatter = logging.Formatter("%(message)s") ch = logging.StreamHandler() ch.setFormatter(formatter) logger.addHandler(ch) logger.setLevel(logging.DEBUG)
swarms-master
swarms/utils/logger.py
import os import shutil from pathlib import Path # from env import DotEnv from swarms.utils.main import AbstractUploader class StaticUploader(AbstractUploader): def __init__(self, server: str, path: Path, endpoint: str): self.server = server self.path = path self.endpoint = endpoint ...
swarms-master
swarms/utils/static.py
import os import random import uuid import numpy as np def seed_everything(seed): random.seed(seed) np.random.seed(seed) try: import torch torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) except: pass return seed def cut_dialogue_history(history_memory, ...
swarms-master
swarms/utils/main.py
import time import logging import threading import functools import warnings def log_decorator(func): def wrapper(*args, **kwargs): logging.info(f'Entering {func.__name__}') result = func(*args, **kwargs) logging.info(f'Exiting {func.__name__}') return result return wrapper d...
swarms-master
swarms/utils/decorators.py
# from __future__ import annotations # import logging # from swarms.utils.logger import logger # from typing import Any, Callable, Dict, List, Optional # from pydantic import BaseModel, model_validator # from tenacity import ( # before_sleep_log, # retry, # retry_if_exception_type, # stop_after_attemp...
swarms-master
swarms/models/palm.py
from transformers import AutoTokenizer, AutoModelForCausalLM class Petals: """Petals Bloom models.""" def __init__( self, model_name="bigscience/bloom-petals", temperature=0.7, max_new_tokens=256, top_p=0.9, top_k=None, ...
swarms-master
swarms/models/petals.py
from swarms.models.anthropic import Anthropic from swarms.models.huggingface import HFLLM # from swarms.models.palm import GooglePalm from swarms.models.petals import Petals #from swarms.models.openai import OpenAIChat
swarms-master
swarms/models/__init__.py
# from __future__ import annotations # import logging # import sys # import warnings # from typing import ( # AbstractSet, # Any, # AsyncIterator, # Collection, # Dict, # Iterator, # List, # Literal, # Mapping, # Optional, # Tuple, # Union, # ) # from langchain.callback...
swarms-master
swarms/models/openai.py
import logging import torch from torch.multiprocessing import set_start_method from torch.nn.parallel import DistributedDataParallel as DDP from transformers import ( AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, GPTQConfig, ) #set up logging logging.basicConfig(level=logging.INFO) logger =...
swarms-master
swarms/models/huggingface.py
import requests import os class Anthropic: """Anthropic large language models.""" def __init__( self, model="claude-2", max_tokens_to_sample=256, temperature=None, top_k=None, top_p=None, streaming=False, de...
swarms-master
swarms/models/anthropic.py
from abc import ABC, abstractmethod class AbstractModel(ABC): #abstract base class for language models @abstractmethod def generate(self, prompt): #generate text using language model pass def chat(self, prompt, history): pass
swarms-master
swarms/models/base.py
import json import re from abc import abstractmethod from typing import Dict, NamedTuple class AgentAction(NamedTuple): """Action returned by AgentOutputParser.""" name: str args: Dict class BaseAgentOutputParser: """Base Output parser for Agent.""" @abstractmethod def parse(self, text: str) ...
swarms-master
swarms/models/prompts/agent_output_parser.py
def generate_agent_role_prompt(agent): """ Generates the agent role prompt. Args: agent (str): The type of the agent. Returns: str: The agent role prompt. """ prompts = { "Finance Agent": "You are a seasoned finance analyst AI assistant. Your primary goal is to compose comprehensive, astute,...
swarms-master
swarms/models/prompts/agent_prompts.py
import time from typing import Any, Callable, List from swarms.models.prompts.agent_prompt_generator import get_prompt class TokenUtils: @staticmethod def count_tokens(text: str) -> int: return len(text.split()) class PromptConstructor: def __init__(self, ai_name: str, ai_role: str, tools): ...
swarms-master
swarms/models/prompts/agent_prompt_auto.py
# """PROMPTS MULTI MODAL"""
swarms-master
swarms/models/prompts/__init__.py
import json from typing import List class PromptGenerator: """A class for generating custom prompt strings.""" def __init__(self) -> None: """Initialize the PromptGenerator object.""" self.constraints: List[str] = [] self.commands: List[str] = [] self.resources: List[str] = [] ...
swarms-master
swarms/models/prompts/agent_prompt.py
import json from typing import List from langchain.tools.base import BaseTool FINISH_NAME = "finish" class PromptGenerator: """A class for generating custom prompt strings. Does this based on constraints, commands, resources, and performance evaluations. """ def __init__(self) -> None: """...
swarms-master
swarms/models/prompts/agent_prompt_generator.py
from __future__ import annotations from abc import abstractmethod from typing import Any, Dict, List, Sequence from pydantic import Field class Message: """ The base abstract Message class. Messages are the inputs and outputs of ChatModels. """ def __init__(self, content: str, role: str, additio...
swarms-master
swarms/models/prompts/chat_prompt.py
from __future__ import annotations from abc import abstractmethod from typing import TYPE_CHECKING, Any, Dict, List, Sequence from pydantic import Field from swarms.utils.serializable import Serializable if TYPE_CHECKING: from langchain.prompts.chat import ChatPromptTemplate def get_buffer_string( messages...
swarms-master
swarms/models/prompts/base.py
SALES_ASSISTANT_PROMPT = """You are a sales assistant helping your sales agent to determine which stage of a sales conversation should the agent move to, or stay at. Following '===' is the conversation history. Use this conversation history to make your decision. Only use the text between first and second '===' to ...
swarms-master
swarms/models/prompts/prebuild/sales_prompts.py
SUMMARIZE_PROMPT = """ Your output should use the following template: ### Summary ### Facts - [Emoji] Bulletpoint Your task is to summarize the text I give you in up to seven concise bullet points and start with a short, high-quality summary. Pick a suitable emoji for every bullet point. Your response should be in {...
swarms-master
swarms/models/prompts/prebuild/summaries_prompts.py
swarms-master
swarms/models/prompts/prebuild/__init__.py
PROJECT_MANAGR_PROMPT_TEMPLATE = ''' # Context {context} ## Format example {format_example} ----- Role: You are a project manager; the goal is to break down tasks according to PRD/technical design, give a task list, and analyze task dependencies to start with the prerequisite modules Requirements: Based on the context...
swarms-master
swarms/models/prompts/prebuild/project_manager.py
ERROR_PROMPT = "An error has occurred for the following text: \n{promptedQuery} Please explain this error.\n {e}" IMAGE_PROMPT = """ provide a figure named {filename}. The description is: {description}. Please understand and answer the image based on this information. The image understanding is complete, so don't try...
swarms-master
swarms/models/prompts/prebuild/multi_modal_prompts.py
swarms-master
swarms/hivemind/__init__.py
# workers in unison #kye gomez jul 13 4:01pm, can scale up the number of swarms working on a probkem with `hivemind(swarms=4, or swarms=auto which will scale the agents depending on the complexity)` #this needs to change, we need to specify exactly what needs to be imported # add typechecking, documentation, and deepe...
swarms-master
swarms/hivemind/hivemind.py
from __future__ import annotations import json import pprint import uuid from abc import ABC, abstractmethod from enum import Enum from typing import Any, Optional from swarms.artifacts.main import Artifact from pydantic import BaseModel, Field, StrictStr, conlist from swarms.artifacts.error_artifact import ErrorArt...
swarms-master
swarms/structs/task.py
swarms-master
swarms/structs/__init__.py
from __future__ import annotations from typing import Any, Dict, List, Optional, Union from swarms.artifacts.error_artifacts import ErrorArtifact from swarms.structs.task import BaseTask import concurrent.futures class StringTask(BaseTask): def __init__( self, task ): super().__init__...
swarms-master
swarms/structs/workflow.py
# from swarms.workers.multi_modal_workers.multi_modal_agent import MultiModalVisualAgent from swarms.workers.multi_modal_workers.multi_modal_agent import MultiModalVisualAgent from langchain.tools import BaseTool class MultiModalVisualAgentTool(BaseTool): name = "multi_visual_agent" description = "Multi-Modal ...
swarms-master
swarms/workers/multi_modal_worker.py
import faiss from langchain.chat_models import ChatOpenAI from langchain.docstore import InMemoryDocstore from langchain.embeddings import OpenAIEmbeddings from langchain.tools.human.tool import HumanInputRun from langchain.vectorstores import FAISS from langchain_experimental.autonomous_agents import AutoGPT from swa...
swarms-master
swarms/workers/worker.py
from swarms.agents.aot import AoTAgent task = "Create GPT-2" system = f""" You are Quoc V. Le, a computer scientist and artificial intelligence researcher who is widely regarded as one of the leading experts in deep learning and neural network architecture search. Your work in this area has focused on developin...
swarms-master
swarms/workers/neural_architecture_search_worker.py
swarms-master
swarms/workers/__init__.py
import os import re import logging from pathlib import Path from typing import Dict, List from swarms.agents.utils.agent_creator import AgentCreator from swarms.utils.main import BaseHandler, FileHandler, FileType from swarms.tools.main import ExitConversation, RequestsGet, CodeEditor, Terminal from swarms.utils.main ...
swarms-master
swarms/workers/worker_ultra_node.py
import enum import os from pathlib import Path import sys import time import shutil import argparse import asyncio import re from typing import List, Optional, Callable, Any import openai from openai_function_call import openai_function from tenacity import retry, stop_after_attempt, wait_random_exponential import log...
swarms-master
swarms/workers/developer_agent.py
from langchain.tools import tool from swarms.workers.multi_modal_workers.omni_agent.omni_chat import chat_huggingface class OmniWorkerAgent: def __init__( self, api_key, api_endpoint, api_type ): self.api_key = api_key self.api_endpoint = api_endpoint ...
swarms-master
swarms/workers/omni_worker.py
# coding: utf-8 import argparse import inspect import math import os import random import re import uuid import cv2 import gradio as gr import matplotlib.pyplot as plt import numpy as np import torch import wget from controlnet_aux import HEDdetector, MLSDdetector, OpenposeDetector from diffusers import ( ControlN...
swarms-master
swarms/workers/multi_modal_workers/multi_modal_agent.py
swarms-master
swarms/workers/multi_modal_workers/__init__.py
import argparse import logging import random import uuid import numpy as np from transformers import pipeline from diffusers import DiffusionPipeline, StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler from diffusers.utils import load_image from diffusers import DiffusionPipeline, DPMSolverMult...
swarms-master
swarms/workers/multi_modal_workers/omni_agent/model_server.py
swarms-master
swarms/workers/multi_modal_workers/omni_agent/__init__.py
import tiktoken encodings = { "gpt-4": tiktoken.get_encoding("cl100k_base"), "gpt-4-32k": tiktoken.get_encoding("cl100k_base"), "gpt-3.5-turbo": tiktoken.get_encoding("cl100k_base"), "gpt-3.5-turbo-0301": tiktoken.get_encoding("cl100k_base"), "text-davinci-003": tiktoken.get_encoding("p50k_base"), ...
swarms-master
swarms/workers/multi_modal_workers/omni_agent/get_token_ids.py
import base64 import copy from io import BytesIO import io import os import random import time import traceback import uuid import requests import re import json import logging import argparse import yaml from PIL import Image, ImageDraw from diffusers.utils import load_image from pydub import AudioSegment import threa...
swarms-master
swarms/workers/multi_modal_workers/omni_agent/omni_chat.py
# from .GroundingDINO.groundingdino.datasets.transforms import T # from .GroundingDINO.groundingdino.models import build_model # from .GroundingDINO.groundingdino.util import box_ops, SLConfig # from .GroundingDINO.groundingdino.util.utils import clean_state_dict, get_phrases_from_posmap # from .segment_anything.segmen...
swarms-master
swarms/workers/models/__init__.py
swarms-master
swarms/workers/models/segment_anything/__init__.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from setuptools import find_packages, setup setup( name="segment_anything", version="1.0", install_requires=[...
swarms-master
swarms/workers/models/segment_anything/setup.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch from segment_anything.modeling import Sam from typing import Optional, Tuple from .util...
swarms-master
swarms/workers/models/segment_anything/segment_anything/predictor.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from functools import partial from .modeling import ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWa...
swarms-master
swarms/workers/models/segment_anything/segment_anything/build_sam.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch from torchvision.ops.boxes import batched_nms, box_area # type: ignore from typing impor...
swarms-master
swarms/workers/models/segment_anything/segment_anything/automatic_mask_generator.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree.
swarms-master
swarms/workers/models/segment_anything/segment_anything/__init__.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch import math from copy import deepcopy from itertools import product from typing import An...
swarms-master
swarms/workers/models/segment_anything/segment_anything/utils/amg.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch from torch.nn import functional as F from torchvision.transforms.functional import resize,...
swarms-master
swarms/workers/models/segment_anything/segment_anything/utils/transforms.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn from torch.nn import functional as F from typing import Tuple from ..modeling import ...
swarms-master
swarms/workers/models/segment_anything/segment_anything/utils/onnx.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree.
swarms-master
swarms/workers/models/segment_anything/segment_anything/utils/__init__.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree.
swarms-master
swarms/workers/models/segment_anything/segment_anything/modeling/__init__.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn from typing import Type class MLPBlock(nn.Module): def __init__( self, ...
swarms-master
swarms/workers/models/segment_anything/segment_anything/modeling/common.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch import Tensor, nn import math from typing import Tuple, Type from .common import MLPBlock clas...
swarms-master
swarms/workers/models/segment_anything/segment_anything/modeling/transformer.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common...
swarms-master
swarms/workers/models/segment_anything/segment_anything/modeling/image_encoder.py