python_code stringlengths 0 992k | repo_name stringlengths 8 46 | file_path stringlengths 5 162 |
|---|---|---|
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# flake8: noqa
import models
import tasks
import criterions
from fairseq_cli.train import cli_main
if __name__ == "__main__":
cli_main()
| torchscale-flash-master | examples/fairseq/train.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
import json
import logging
import os
from argparse import Namespace
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of t... | torchscale-flash-master | examples/fairseq/tasks/pretraining.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
import argparse
import importlib
import os
# register dataclass
TASK_DATACLASS_REGISTRY = {}
TASK_REGISTRY = {}
TASK_CLASS_NAMES = set()
# automatically import any Python files in the tasks/ directory
tasks_dir = os.path.dirnam... | torchscale-flash-master | examples/fairseq/tasks/__init__.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
import torch
from infinibatch.iterators import CheckpointableIterator
from . import utils
class BaseBatchGen(CheckpointableIterator):
"""
This is a base class for batch generators that use infinibatch
"""
def ... | torchscale-flash-master | examples/fairseq/tasks/data/basic_loader.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
| torchscale-flash-master | examples/fairseq/tasks/data/__init__.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
import collections
from random import Random
from typing import Dict, Iterable, Optional
import numpy as np
from infinibatch import iterators
def apply_to_sample(f, sample):
if hasattr(sample, "__len__") and len(sample) ==... | torchscale-flash-master | examples/fairseq/tasks/data/utils.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
import copy
import itertools
import os
import numpy as np
from infinibatch import iterators
from .basic_loader import BaseBatchGen
from .utils import NativeCheckpointableIterator, WeightIterator
class MLMLoader(BaseBatchGen):... | torchscale-flash-master | examples/fairseq/tasks/data/mlm_loader.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
import math
import warnings
import torch
import torch.distributed as dist
from fairseq.utils import multi_tensor_l2norm_available, multi_tensor_total_norm
@torch.no_grad()
def clip_grad_norm_(
params, max_norm, moe_expert_... | torchscale-flash-master | examples/fairseq/utils/sparse_clip.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
| torchscale-flash-master | examples/fairseq/utils/__init__.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from dataclasses import dataclass, f... | torchscale-flash-master | examples/fairseq/models/language_modeling.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
import argparse
import importlib
import os
MODEL_REGISTRY = {}
MODEL_DATACLASS_REGISTRY = {}
ARCH_MODEL_REGISTRY = {}
ARCH_MODEL_NAME_REGISTRY = {}
ARCH_MODEL_INV_REGISTRY = {}
ARCH_CONFIG_REGISTRY = {}
# automatically import a... | torchscale-flash-master | examples/fairseq/models/__init__.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from typing import Dict, List, Optio... | torchscale-flash-master | examples/fairseq/models/machine_translation.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
import logging
from dataclasses import dataclass, field
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import utils
from fairseq.dataclass import ChoiceEnum, FairseqDa... | torchscale-flash-master | examples/fairseq/models/bert.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
import torch
import torch.nn.functional as F
from fairseq import metrics, utils
from fairseq.criterions import MoECriterion, regis... | torchscale-flash-master | examples/fairseq/criterions/masked_lm_moe.py |
import importlib
import os
# automatically import any Python files in the criterions/ directory
for file in sorted(os.listdir(os.path.dirname(__file__))):
if file.endswith(".py") and not file.startswith("_"):
file_name = file[: file.find(".py")]
importlib.import_module("criterions." + file_name) | torchscale-flash-master | examples/fairseq/criterions/__init__.py |
from distutils.core import setup
from setuptools import find_packages
with open("README.md", "r", encoding = "utf-8") as readme:
long_description = readme.read()
setup(
name="The Distiller",
version="0.0.2",
description="Generate textual and conversational datasets with LLMs.",
long_description = ... | The-Distiller-master | setup.py |
from .cli import distiller
from .conversations import *
from .texts import *
from .outputs import *
| The-Distiller-master | src/distiller/__init__.py |
import click
from typing import List, Tuple
from .conversations import ConversationsGeneratorConfig, ConversationsGenerator
from .texts import TextsGeneratorConfig, TextsGenerator
from .outputs import DatasetWriter
@click.group()
def distiller() -> None:
"""Command line interface that generates datasets with LLM... | The-Distiller-master | src/distiller/cli.py |
from dataclasses import dataclass, field
from typing import List, Any, Dict, Tuple, Union
from langchain.prompts import PromptTemplate
from langchain.llms import BaseLLM
from langchain.chains import LLMChain
from .base import DatasetGenerator
OPTIONS_CONFIG_KEYS = ["backend", "max_length", "temperature"]
GENERATOR_C... | The-Distiller-master | src/distiller/texts.py |
from .cli import main
main()
| The-Distiller-master | src/distiller/__main__.py |
from dataclasses import dataclass, field
from typing import List, Any, Dict, Tuple, Union
from langchain.prompts import (
ChatPromptTemplate,
MessagesPlaceholder,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate
)
from langchain.chains import ConversationChain
from langchain.chat_models import ... | The-Distiller-master | src/distiller/conversations.py |
import itertools
from typing import List, Any, Dict, Tuple, Generator, Iterator, Protocol
OPTIONS_CONFIG_KEYS = ["temperature"]
GENERATOR_CONFIG_KEYS = ["temperatures"]
class DatasetGeneratorConfig(Protocol):
"""Base generator configuration protocol."""
openai_api_key: str
"""OpenAI API key."""
num_... | The-Distiller-master | src/distiller/base.py |
import os
import json
from uuid import uuid4
from typing import Dict, Any, List
class DatasetWriter:
"""Handle outputting dataset items."""
single_file: bool
"""Whether to save all dataset items in a single file."""
path: str
"""Path of the output file or directory."""
dataset_items: List[Di... | The-Distiller-master | src/distiller/outputs.py |
from abc import ABC, abstractmethod
class AbstractLanguageModel(ABC):
@abstractmethod
def generate_thoughts(self, state, k):
pass
@abstractmethod
def evaluate_states(self, states):
pass
| The-Distiller-master | src/distiller/agents/abstract.py |
from abc import ABC, abstractmethod
from transformers import AutoModelForCausalLM, AutoTokenizer
from abstract import AbstractLanguageModel
class HuggingLanguageModel(AbstractLanguageModel):
def __init__(self, model_name, model_tokenizer=None, verbose=False):
self.model = AutoModelForCausalLM.from_pretr... | The-Distiller-master | src/distiller/agents/huggingface.py |
import torch
import torch.nn as nn
import numpy as np
#define the loss function class
class LossFunction:
def compute_loss(self, y_pred, y_true):
raise NotImplemented("compute_loss method must be implemented")
#implement specific loss functions that inherit from LossFunction
class L1Loss(LossFuncti... | nebula-master | nebula_old.py |
from setuptools import setup, find_packages
setup(
name = 'nebula-loss',
packages = find_packages(exclude=[]),
version = '0.4.1',
license='MIT',
description = '1 Loss Function to rule them all!',
author = 'Agora',
author_email = 'kye@apac.ai',
long_description_content_type = 'text/markdown',
url = 'h... | nebula-master | setup.py |
import unittest
import torch
from nebula.nebula import MSELoss, CrossEntropyLoss, MultiLabelSoftMarginLoss, Nebula
class TestNebula(unittest.TestCase):
def setUp(self):
self.nebula = Nebula()
self.tolerance = 1e-5
self.y_true_regression = torch.tensor([1.1, 2.2, 3.3, 4.4, 5.5], dtype=to... | nebula-master | testing.py |
#using gradient boosted greedy algorithms to compute loss
import xgboost as xgb
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, accuracy_score
# Load your dataset
# X, y = load_your_data()
# For demonstration purposes, we'll use random data
X =... | nebula-master | experimental/xgboostV3.py |
import torch
import torch.nn as nn
import numpy as np
#define the loss function class
class LossFunction:
def compute_loss(self, y_pred, y_true):
raise NotImplemented("compute_loss method must be implemented")
#implement specific loss functions that inherit from LossFunction
class L1Loss(LossFuncti... | nebula-master | experimental/nebulaV2.py |
import numpy as np
from torch.nn import BCELoss
# Define the base LossFunction class
class LossFunction:
def compute_loss(self, y_pred, y_true):
raise NotImplementedError("compute_loss method must be implemented in the derived class")
# Define specific loss function classes that inherit from LossFunction
... | nebula-master | experimental/nebula.py |
import torch
import torch.nn as nn
# import torch.jit
import numpy as np
class LossFunction:
def compute_Loss(self, y_pred, y_true):
raise NotImplemented("compute_loss method must be implemented!")
class L1Loss(LossFunction):
def __init__(self):
self.loss_function = nn.L1Loss()
def c... | nebula-master | experimental/reinforcement/nebula.py |
import torch
import torch.nn as nn
# import torch.jit
import numpy as np
class LossFunction:
def compute_Loss(self, y_pred, y_true):
raise NotImplemented("compute_loss method must be implemented!")
class L1Loss(LossFunction):
def __init__(self):
self.loss_function = nn.L1Loss()
def c... | nebula-master | experimental/reinforcement/experimental/nebula2.py |
import torch
import torch.nn as nn
# import torch.jit
import numpy as np
class LossFunction:
def compute_Loss(self, y_pred, y_true):
raise NotImplemented("compute_loss method must be implemented!")
class L1Loss(LossFunction):
def __init__(self):
self.loss_function = nn.L1Loss()
def c... | nebula-master | experimental/reinforcement/experimental/nebula3.py |
import torch
import torch.nn as nn
# import torch.jit
import numpy as np
class LossFunction:
def compute_Loss(self, y_pred, y_true):
raise NotImplemented("compute_loss method must be implemented!")
class L1Loss(LossFunction):
def __init__(self):
self.loss_function = nn.L1Loss()
def c... | nebula-master | experimental/reinforcement/experimental/nebula1.py |
import torch
import torch.nn as nn
import numpy as np
# Continual Learning Mechanism Class
class ContinualLearningMechanism(nn.Module):
def __init__(self, pretrained_model=None):
super(ContinualLearningMechanism, self).__init__()
self.model = nn.Sequential(
nn.Linear(128, 64),
... | nebula-master | nebula/nebula_multimodal.py |
# !pip install deap
import random
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from deap import creator, base, tools, algorithms
# Create the model
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(10, 32)
self.f... | nebula-master | nebula/nebula_genetic.py |
from nebula.nebula import Nebula
from nebula.nebula import one_hot_encoding | nebula-master | nebula/__init__.py |
import torch
import torch.nn as nn
import numpy as np
from sklearn.model_selection import train_test_split
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(10, 32)
self.fc2 = nn.Linear(32, 3)
def forward(self, x):
x = torch.relu(self.f... | nebula-master | nebula/nebula_search.py |
import torch
import torch.nn as nn
# import torch.jit
import numpy as np
import logging
class LossFunction:
def compute_Loss(self, y_pred, y_true):
raise NotImplemented("compute_loss method must be implemented!")
class L1Loss(LossFunction):
def __init__(self):
self.loss_function = nn.L1L... | nebula-master | nebula/nebula.py |
# from nebulaV4 import one_hot_encoding
# from nebulaV4 import Nebula
# import torch
# import numpy as np
# import matplotlib.pyplot as plt
# import torch.nn as nn
# class LossFunction:
# def compute_loss(self, y_pred, y_true):
# raise NotImplemented("compute_loss method must be implemented")
# #impl... | nebula-master | testing/test.py |
from setuptools import setup, find_packages
#
setup(
name = 'SwarmLogic',
packages = find_packages(exclude=[]),
version = '0.6.3',
license='MIT',
description = 'SwarmLogic - Pytorch',
author = 'Kye Gomez',
author_email = 'kye@apac.ai',
long_description_content_type = 'text/markdown',
url = 'https://... | SwarmLogic-main | setup.py |
from swarm_logic.SwarmLogic import api | SwarmLogic-main | swarm_logic/__init__.py |
from fastapi import FastAPI, HTTPException
from typing import Optional
import json
import logging
from pydantic import BaseModel
from swarms import Worker
class AppState(BaseModel):
app_name: str
api_call: str
# Set up logging
logging.basicConfig(filename="app.log", level=logging.INFO, format='%(asctime)s %(... | SwarmLogic-main | swarm_logic/SwarmLogic.py |
from typing import Iterable
from base import DatabaseConnector
import opendal
class OpenDALConnector(DatabaseConnector):
def __init__(self, scheme, **kwargs):
self.op = opendal.Operator(scheme, **kwargs)
def read(self, path: str) -> bytes:
return self.op.read(path)
def write(self, path... | SwarmLogic-main | swarm_logic/connectors/dal.py |
from sqlalchemy import create_engine, MetaData, Table, select
from sqlalchemy.orm import sessionmaker, scoped_session
import opendal
from base import DatabaseConnector
class SQLAlchemyConnector(DatabaseConnector):
def __init__(self, database_url):
self.engine = create_engine(database_url)
self.met... | SwarmLogic-main | swarm_logic/connectors/alchemy.py |
from swarm_logic.connectors.alchemy import SQLAlchemyConnector
from swarm_logic.connectors.base import DatabaseConnector
from swarm_logic.connectors.dal import OpenDALConnector
from swarm_logic.connectors.json import JsonDBConnector
| SwarmLogic-main | swarm_logic/connectors/__init__.py |
from base import DatabaseConnector
class JsonDBConnector(DatabaseConnector):
def read(self, path: str) -> bytes:
with open(path, 'r') as f:
return f.read().encode()
def write(self, path: str, bs: bytes):
with open(path, 'w') as f:
f.write(bs.decode())
| SwarmLogic-main | swarm_logic/connectors/json.py |
from abc import ABC, abstractmethod
from typing import Iterable
class DatabaseConnector(ABC):
@abstractmethod
def read(self, path: str) -> bytes:
pass
@abstractmethod
def write(self, path: str, bs: bytes):
pass
@abstractmethod
def stat(self, path: str) -> opendal.Metadata:
... | SwarmLogic-main | swarm_logic/connectors/base.py |
SwarmLogic-main | swarm_logic/experimental/__init__.py | |
from fastapi import FastAPI, HTTPException
from typing import Optional
import json
import logging
from pydantic import BaseModel
from swarms import Swarms
from swarm_logic.connectors import SQLAlchemyConnector, OpenDALConnector, JsonDBConnector
class AppState(BaseModel):
app_name: str
api_call: str
db_ty... | SwarmLogic-main | swarm_logic/experimental/SwarmLogicExperimental.py |
from fastapi import FastAPI, HTTPException
from typing import Optional
import json
import logging
from pydantic import BaseModel
from swarms import Worker
class AppState(BaseModel):
app_name: str
api_call: str
# Set up logging
logging.basicConfig(filename="app.log", level=logging.INFO, format='%(asctime)s %(... | SwarmLogic-main | swarm_logic/experimental/SwarmLogicWorker.py |
SwarmLogic-main | swarm_logic/utils/__init__.py | |
#open up the swarms class to intake external tooks like Swarm(tool)
import traceback
import logging
from swarms import Swarms
api_key = "your-api-key-here"
swarm = Swarms(openai_api_key=api_key)
logging.basicConfig(filename="app.log", level=logging.INFO, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y... | SwarmLogic-main | swarm_logic/utils/error_handling.py |
MultiGroupQueryAttention-main | example.py | |
MultiGroupQueryAttention-main | mgqa/__init__.py | |
MultiGroupQueryAttention-main | mgqa/main.py | |
from aot.main import AoT
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 developing efficient al... | Algorithm-Of-Thoughts-main | neural_search_example.py |
from aot.main import AoT
task = """
Use numbers and basic arithmetic operations (+ - * /) to obtain 24. When
considering the next steps, do not choose operations that will result in a
negative or fractional number. In order to help with the calculations, the
numbers in the parenthesis represent the numbers that are l... | Algorithm-Of-Thoughts-main | examples.py |
from aot.main import AoT
| Algorithm-Of-Thoughts-main | aot/__init__.py |
import os
import openai
import time
import logging
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="... | Algorithm-Of-Thoughts-main | aot/openai.py |
from aot.openai import OpenAI
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
class AoT:
def __init__(
self,
num_thoughts: int = None,
max_steps: int = None,
value_threshold: float ... | Algorithm-Of-Thoughts-main | aot/main.py |
import os
# specify example image paths:
image_paths = [
'synpic50962.jpg',
'synpic52767.jpg',
'synpic30324.jpg',
'synpic21044.jpg',
'synpic54802.jpg',
'synpic57813.jpg'
]
image_paths = [os.path.join('../img', p) for p in image_paths]
def clean_generation(response):
"""
for som... | med-flamingo1-master | scripts/demo_utils.py |
from huggingface_hub import hf_hub_download
import torch
import os
from open_flamingo import create_model_and_transforms
from accelerate import Accelerator
from einops import repeat
from PIL import Image
import sys
sys.path.append('..')
from src.utils import FlamingoProcessor
from demo_utils import image_paths, clean_g... | med-flamingo1-master | scripts/demo.py |
med-flamingo1-master | src/__init__.py | |
import torch
from abc import ABC, abstractmethod
class AbstractProcessor(ABC):
"""
Abstract class for processors to show what methods they need to implement.
Processors handle text encoding and image preprocessing.
"""
@abstractmethod
def encode_text(self, prompt):
pass
@abstractm... | med-flamingo1-master | src/utils.py |
import os
import asyncio
import signal
import sys
import threading
import traceback
from pathlib import Path
from platform import system
import discord
import pinecone
from pycord.multicog import apply_multicog
from swarmsdiscord.cogs.search_service_cog import SearchService
from swarmsdiscord.cogs.text_service_cog im... | SwarmsDiscord-main | main.py |
"""
Store information about a discord user, for the purposes of enabling conversations. We store a message
history, message count, and the id of the user in order to track them.
"""
class RedoUser:
def __init__(self, prompt, instruction, message, ctx, response, paginator):
self.prompt = prompt
sel... | SwarmsDiscord-main | swarmsdiscord/models/user_model.py |
import functools
import os
import random
import tempfile
import traceback
import asyncio
from collections import defaultdict
import aiohttp
import discord
import aiofiles
import openai
import tiktoken
from functools import partial
from typing import List, Optional
from pathlib import Path
from datetime import date
fr... | SwarmsDiscord-main | swarmsdiscord/models/index_model.py |
from pathlib import Path
import os
import re
import discord
from models.deepl_model import TranslationModel
from services.moderations_service import ModerationOptions
from services.usage_service import UsageService
from models.openai_model import ImageSize, Model, ModelLimits, Models, Mode
from services.environment_s... | SwarmsDiscord-main | swarmsdiscord/models/autocomplete_model.py |
SwarmsDiscord-main | swarmsdiscord/models/__init__.py | |
import os
import traceback
import aiohttp
import backoff
COUNTRY_CODES = {
"EN": "English",
"ES": "Spanish",
"FR": "French",
"ZH": "Chinese (simplified)",
"BG": "Bulgarian",
"CS": "Czech",
"DA": "Danish",
"DE": "German",
"EL": "Greek",
"FI": "Finnish",
"HU": "Hungarian",
... | SwarmsDiscord-main | swarmsdiscord/models/deepl_model.py |
import discord
from services.environment_service import EnvService
BOT_NAME = EnvService.get_custom_bot_name()
class EmbedStatics:
def __init__(self):
pass
@staticmethod
def get_api_timeout_embed():
embed = discord.Embed(
title="The API timed out. Try again later.",
... | SwarmsDiscord-main | swarmsdiscord/models/embed_statics_model.py |
import asyncio
import functools
import math
import os
import re
import tempfile
import traceback
import uuid
from typing import Any, Tuple
import aiohttp
import backoff
import discord
# An enum of two modes, TOP_P or TEMPERATURE
import requests
from services.environment_service import EnvService
from PIL import Image... | SwarmsDiscord-main | swarmsdiscord/models/openai_model.py |
import base64
import json
import os
import aiohttp
from services.environment_service import EnvService
import replicate
class ImageUnderstandingModel:
def __init__(self):
# Try to get the replicate API key from the environment
self.replicate_key = EnvService.get_replicate_api_key()
# Set... | SwarmsDiscord-main | swarmsdiscord/models/image_understanding_model.py |
import discord
import re
import aiohttp
from services.environment_service import EnvService
from typing import Callable
ADMIN_ROLES = EnvService.get_admin_roles()
DALLE_ROLES = EnvService.get_dalle_roles()
GPT_ROLES = EnvService.get_gpt_roles()
INDEX_ROLES = EnvService.get_index_roles()
TRANSLATOR_ROLES = EnvService.... | SwarmsDiscord-main | swarmsdiscord/models/check_model.py |
import asyncio
import os
import tempfile
import traceback
from datetime import datetime, date
from functools import partial
from pathlib import Path
import discord
import aiohttp
import openai
import tiktoken
from langchain.chat_models import ChatOpenAI
from llama_index import (
QuestionAnswerPrompt,
GPTVecto... | SwarmsDiscord-main | swarmsdiscord/models/search_model.py |
import asyncio
import traceback
import os
from functools import partial
from pathlib import Path
from yt_dlp import YoutubeDL
import discord
from discord.ext import pages
from models.deepl_model import TranslationModel
from models.embed_statics_model import EmbedStatics
from models.check_model import UrlCheck
from s... | SwarmsDiscord-main | swarmsdiscord/cogs/transcription_service_cog.py |
import datetime
import io
import json
import os
import sys
import tempfile
import traceback
from typing import Optional, Dict, Any
import aiohttp
import re
import discord
import openai
from bs4 import BeautifulSoup
from discord.ext import pages
from langchain import (
GoogleSearchAPIWrapper,
WolframAlphaAPIWra... | SwarmsDiscord-main | swarmsdiscord/cogs/search_service_cog.py |
SwarmsDiscord-main | swarmsdiscord/cogs/__init__.py | |
import asyncio
import discord
from sqlitedict import SqliteDict
from services.environment_service import EnvService
from services.moderations_service import Moderation, ThresholdSet
MOD_DB = None
try:
print("Attempting to retrieve the General and Moderations DB")
MOD_DB = SqliteDict(
EnvService.find_... | SwarmsDiscord-main | swarmsdiscord/cogs/moderations_service_cog.py |
import asyncio
import datetime
import pickle
import re
import traceback
import sys
from pathlib import Path
import aiofiles
import json
import discord
from discord.ext import pages
from models.deepl_model import TranslationModel
from models.embed_statics_model import EmbedStatics
from models.image_understanding_mod... | SwarmsDiscord-main | swarmsdiscord/cogs/text_service_cog.py |
import datetime
import traceback
from pathlib import Path
import discord
import os
from models.embed_statics_model import EmbedStatics
from services.deletion_service import Deletion
from services.environment_service import EnvService
from services.moderations_service import Moderation
from services.text_service impor... | SwarmsDiscord-main | swarmsdiscord/cogs/index_service_cog.py |
import asyncio
import os
import traceback
import discord
# We don't use the converser cog here because we want to be able to redo for the last images and text prompts at the same time
from sqlitedict import SqliteDict
from services.environment_service import EnvService
from services.image_service import ImageService... | SwarmsDiscord-main | swarmsdiscord/cogs/image_service_cog.py |
import traceback
import aiohttp
import discord
from models.deepl_model import TranslationModel
from services.environment_service import EnvService
ALLOWED_GUILDS = EnvService.get_allowed_guilds()
def build_translation_embed(
text,
translated_text,
translated_language,
detected_language,
reques... | SwarmsDiscord-main | swarmsdiscord/cogs/translation_service_cog.py |
import re
import traceback
import discord
from sqlitedict import SqliteDict
from models.openai_model import Override, Models
from services.environment_service import EnvService
from models.user_model import RedoUser
from services.image_service import ImageService
from services.moderations_service import Moderation
f... | SwarmsDiscord-main | swarmsdiscord/cogs/prompt_optimizer_cog.py |
import discord
from pycord.multicog import add_to_group
from services.environment_service import EnvService
from models.check_model import Check
from models.autocomplete_model import (
Settings_autocompleter,
File_autocompleter,
Translations_autocompleter,
)
ALLOWED_GUILDS = EnvService.get_allowed_guilds(... | SwarmsDiscord-main | swarmsdiscord/cogs/commands.py |
import asyncio
import traceback
from datetime import datetime
import discord
class Deletion:
def __init__(self, message, timestamp):
self.message = message
self.timestamp = timestamp
# This function will be called by the bot to process the message queue
@staticmethod
async def proces... | SwarmsDiscord-main | swarmsdiscord/services/deletion_service.py |
import json
import aiohttp
class ShareGPTService:
def __init__(self):
self.API_URL = "https://sharegpt.com/api/conversations"
def format_conversation(
self, conversation_history, avatar_url="https://i.imgur.com/SpuAF0v.png"
):
# The format is { 'avatarUrl' : <url>, 'items': [ { '... | SwarmsDiscord-main | swarmsdiscord/services/sharegpt_service.py |
import asyncio
import os
import random
import traceback
from datetime import datetime, timedelta
from pathlib import Path
import discord
from models.openai_model import Model
from services.environment_service import EnvService
from services.usage_service import UsageService
usage_service = UsageService(Path(os.envir... | SwarmsDiscord-main | swarmsdiscord/services/moderations_service.py |
import pinecone
class PineconeService:
def __init__(self, index: pinecone.Index):
self.index = index
def upsert_basic(self, text, embeddings):
self.index.upsert([(text, embeddings)])
def get_all_for_conversation(self, conversation_id: int):
response = self.index.query(
... | SwarmsDiscord-main | swarmsdiscord/services/pinecone_service.py |
import datetime
import traceback
from flask import Flask
from multiprocessing import Process
app = Flask(__name__)
start_time = datetime.datetime.now()
@app.route("/healthz")
def health():
# Find the difference between the current time and start_time in seconds
uptime = (datetime.datetime.now() - start_time... | SwarmsDiscord-main | swarmsdiscord/services/health_service.py |
SwarmsDiscord-main | swarmsdiscord/services/__init__.py | |
import os
import sys
import traceback
from pathlib import Path
from typing import Union
from dotenv import load_dotenv
from sqlitedict import SqliteDict
def app_root_path():
app_path = Path(sys.argv[0]).resolve()
try:
if app_path.parent.name == "bin": # Installed in unixy hierachy
return... | SwarmsDiscord-main | swarmsdiscord/services/environment_service.py |
import asyncio
import random
import tempfile
import traceback
from io import BytesIO
import aiohttp
import discord
from PIL import Image
from models.user_model import RedoUser
class ImageService:
def __init__(self):
pass
@staticmethod
async def encapsulated_send(
image_service_cog,
... | SwarmsDiscord-main | swarmsdiscord/services/image_service.py |
import asyncio
class Message:
def __init__(self, content, channel):
self.content = content
self.channel = channel
# This function will be called by the bot to process the message queue
@staticmethod
async def process_message_queue(message_queue, PROCESS_WAIT_TIME, EMPTY_WAIT_TIME):
... | SwarmsDiscord-main | swarmsdiscord/services/message_queue_service.py |
from pathlib import Path
import aiofiles
from typing import Literal
import tiktoken
class UsageService:
def __init__(self, data_dir: Path):
self.usage_file_path = data_dir / "usage.txt"
# If the usage.txt file doesn't currently exist in the directory, create it and write 0.00 to it.
if no... | SwarmsDiscord-main | swarmsdiscord/services/usage_service.py |
import asyncio.exceptions
import datetime
import re
import traceback
from collections import defaultdict
import aiofiles
import aiohttp
import discord
import requests
from discord.ext import pages
import unidecode
from models.embed_statics_model import EmbedStatics
from models.image_understanding_model import ImageUn... | SwarmsDiscord-main | swarmsdiscord/services/text_service.py |
import asyncio
import pickle
import traceback
from datetime import datetime
import aiofiles
import discord
from services.environment_service import EnvService
class Pickler:
def __init__(
self,
full_conversation_history,
conversation_threads,
conversation_thread_owners,
i... | SwarmsDiscord-main | swarmsdiscord/services/pickle_service.py |
SwarmsDiscord-main | tests/__init__.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.