repo_name
stringlengths
7
71
file_path
stringlengths
5
118
context
list
import_statement
stringlengths
45
12.5k
token_num
int64
641
99.4k
cropped_code
stringlengths
44
17k
all_code
stringlengths
43
754k
next_line
stringlengths
2
330
gold_snippet_index
int64
0
68
created_at
stringlengths
25
25
level
stringclasses
9 values
Harvard-Ophthalmology-AI-Lab/FairSeg
SAMed/segment_anything/modeling/image_encoder.py
[ { "identifier": "LayerNorm2d", "path": "SAMed/segment_anything/modeling/common.py", "snippet": "class LayerNorm2d(nn.Module):\n def __init__(self, num_channels: int, eps: float = 1e-6) -> None:\n super().__init__()\n self.weight = nn.Parameter(torch.ones(num_channels))\n self.bia...
import torch import torch.nn as nn import torch.nn.functional as F from icecream import ic from typing import Optional, Tuple, Type from .common import LayerNorm2d, MLPBlock
1,147
# 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. # This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github....
# 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. # This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github....
LayerNorm2d(out_chans),
0
2023-11-03 17:05:40+00:00
2k
anand2312/quill-server
quill_server/realtime/events.py
[ { "identifier": "User", "path": "quill_server/db/models.py", "snippet": "class User(Base):\n __tablename__ = \"user\"\n\n id: Mapped[UUID] = mapped_column(pg_UUID(as_uuid=True), primary_key=True, default=uuid4) # noqa: A003\n username: Mapped[str] = mapped_column(unique=True)\n password: Ma...
from enum import StrEnum, auto from functools import partial from typing import Any, Generic, TypeVar from collections.abc import Awaitable from loguru import logger from pydantic import BaseModel from redis.asyncio import Redis from quill_server.db.models import User from quill_server.realtime.room import GameMember, ...
1,548
DataT = TypeVar("DataT", bound=BaseModel) # the excalidraw element event contains many fields # https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L27-L141 ExcalidrawElement = dict[str, Any] class Drawing(BaseModel):
DataT = TypeVar("DataT", bound=BaseModel) # the excalidraw element event contains many fields # https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L27-L141 ExcalidrawElement = dict[str, Any] class Drawing(BaseModel):
user: GameMember
1
2023-11-03 12:43:18+00:00
2k
OPTML-Group/DeepZero
algorithm/prune/main.py
[ { "identifier": "zoo_grasp_importance_score", "path": "algorithm/prune/importance_scores.py", "snippet": "def zoo_grasp_importance_score(\n model,\n dataloader,\n samples_per_class,\n class_num,\n zoo_rs_size,\n zoo_step_size,\n loss_func = torch.nn.CrossEntropyLoss()\n ):\n\n ...
import torch from torch.nn.utils import prune from copy import deepcopy from .importance_scores import zoo_grasp_importance_score, grasp_importance_score, random_importance_score
963
__all__ = ['global_prune', 'check_sparsity', 'check_grad_sparsity', 'custom_prune', 'extract_mask', 'remove_prune', 'layer_sparsity'] def global_prune(model, ratio, method, class_num=None, dataloader=None, sample_per_classes=25, zoo_sample_size=None, zoo_step_size=None, layer_wise_sparsity=None): if method == 'gr...
__all__ = ['global_prune', 'check_sparsity', 'check_grad_sparsity', 'custom_prune', 'extract_mask', 'remove_prune', 'layer_sparsity'] def global_prune(model, ratio, method, class_num=None, dataloader=None, sample_per_classes=25, zoo_sample_size=None, zoo_step_size=None, layer_wise_sparsity=None): if method == 'gr...
score_dict = zoo_grasp_importance_score(model, dataloader, sample_per_classes, class_num, zoo_sample_size, zoo_step_size)
0
2023-11-01 14:47:38+00:00
2k
S3raphimCS/Hackathon_telehack
backend/SPO_KROT/metrics/admin.py
[ { "identifier": "ExcelFile", "path": "backend/SPO_KROT/metrics/models.py", "snippet": "class ExcelFile(models.Model):\n file = models.FileField(\n upload_to='metrics',\n unique=True,\n blank=True, null=True,\n validators=[FileExtensionValidator(['xlsx', 'xls', 'xlsm'])],\n...
from django.contrib import admin from .models import ExcelFile, Measurements, Operator, Report
1,372
@admin.register(Operator) class OperatorAdmin(admin.ModelAdmin): list_display = ('name',) list_per_page = 15 search_fields = ("name",) readonly_fields = ('id',)
@admin.register(Operator) class OperatorAdmin(admin.ModelAdmin): list_display = ('name',) list_per_page = 15 search_fields = ("name",) readonly_fields = ('id',)
@admin.register(Report)
3
2023-11-09 12:55:04+00:00
2k
lz1oceani/LLM-As-Hierarchical-Policy
hlm/utils/metric_utils.py
[ { "identifier": "normalize_answer", "path": "hlm/utils/math_answer_utils.py", "snippet": "def normalize_answer(text, answer_type=\"text\"):\n ret = normalize_answer_core(text, answer_type)\n try:\n str(ret)\n except:\n ret = None\n return \"No answer!\" if ret is None else ret"...
import os, warnings import numpy as np, re, time, signal, sympy, scipy from sympy.utilities.exceptions import SymPyDeprecationWarning from collections import defaultdict from numbers import Number from IPython import embed from copy import deepcopy from itertools import chain from sympy.parsing.latex import parse_latex...
1,417
os.environ["USE_SYMENGINE"] = "1" warnings.simplefilter("ignore", SyntaxWarning) warnings.simplefilter("ignore", RuntimeWarning) warnings.filterwarnings("ignore", category=SymPyDeprecationWarning) # from sympy import Symbol, Eq, simplify, solve NO_ANSWER = "No answer!" SKIP_ANSWER_TEMPLATE = [ "Code cannot b...
os.environ["USE_SYMENGINE"] = "1" warnings.simplefilter("ignore", SyntaxWarning) warnings.simplefilter("ignore", RuntimeWarning) warnings.filterwarnings("ignore", category=SymPyDeprecationWarning) # from sympy import Symbol, Eq, simplify, solve NO_ANSWER = "No answer!" SKIP_ANSWER_TEMPLATE = [ "Code cannot b...
source = normalize_answer(source, answer_type)
0
2023-11-01 17:15:42+00:00
2k
mitre/arlin
tests/test_dataset/test_collectors/test_sb3_collectors.py
[ { "identifier": "SB3DQNDataCollector", "path": "arlin/dataset/collectors/sb3_collectors.py", "snippet": "class SB3DQNDataCollector(BaseDataCollector):\n \"\"\"Data collector for a model trained with DQN in stable-baselines3.\"\"\"\n\n def __init__(self, datapoint_cls: Type[BaseDatapoint], policy: ...
import pytest from stable_baselines3 import DQN from arlin.dataset.collectors import SB3DQNDataCollector, SB3PPODataCollector from arlin.dataset.collectors.datapoints import SB3DQNDatapoint, SB3PPODatapoint
1,031
@pytest.fixture def dqn_model(env): model = DQN("MlpPolicy", env, verbose=1) model.learn(total_timesteps=int(100)) return model class TestSB3Collectors: def test_sb3_ppo_collector(self, ppo_model, env):
@pytest.fixture def dqn_model(env): model = DQN("MlpPolicy", env, verbose=1) model.learn(total_timesteps=int(100)) return model class TestSB3Collectors: def test_sb3_ppo_collector(self, ppo_model, env):
collector = SB3PPODataCollector(SB3PPODatapoint, ppo_model.policy)
1
2023-11-08 13:57:45+00:00
2k
Giftify-Bot/Giftify-Bot
utils/paginator.py
[ { "identifier": "ARROW_BACK_EMOJI", "path": "utils/constants.py", "snippet": "ARROW_BACK_EMOJI = \"<:GiftifyBack:1120372002939744308>\"" }, { "identifier": "ARROW_EMOJI", "path": "utils/constants.py", "snippet": "ARROW_EMOJI = \"<:GiftifyArrow:1117849870678638653>\"" }, { "identi...
import abc import discord from typing import TYPE_CHECKING, Any, Dict, Generic, List, Optional, TypeVar, Union from discord.ext import commands from typing import TypeAlias from typing_extensions import TypeAlias from utils.constants import ARROW_BACK_EMOJI, ARROW_EMOJI, STOP_EMOJI from utils.tree import Intera...
1,496
@property def max_page(self) -> int: """The max page count for this paginator.""" return len(self.pages) @property def min_page(self) -> int: """The min page count for this paginator.""" return 1 @property def current_page(self) -> int: """The current pa...
from __future__ import annotations try: except ImportError: if TYPE_CHECKING: T = TypeVar("T") TargetType: TypeAlias = Union[Interaction, commands.Context["Giftify"]] class BaseButtonPaginator(Generic[T], discord.ui.View, abc.ABC): """The base implementation of a button paginator. This class should be inher...
@discord.ui.button(emoji=STOP_EMOJI)
2
2023-11-09 15:00:15+00:00
2k
Zjy0401/CoCoFormer
model/rpr.py
[ { "identifier": "get_device", "path": "utilities/device.py", "snippet": "def get_device():\n\n if((not USE_CUDA) or (TORCH_CUDA_DEVICE is None)):\n return TORCH_CPU_DEVICE\n else:\n return TORCH_CUDA_DEVICE" }, { "identifier": "parse_train_args", "path": "utilities/argume...
import torch import torch.nn as nn from torch.nn import functional as F from torch.nn.parameter import Parameter from torch.nn import Module from torch.nn.modules.transformer import _get_clones from torch.nn.modules.linear import Linear from torch.nn.modules.dropout import Dropout from torch.nn.modules.normalization im...
1,158
# TransformerEncoderRPR class TransformerEncoderRPR(Module): def __init__(self, encoder_layer, num_layers, encoder_past, max_seq, c_max_seq, b_max_seq, norm=None): super(TransformerEncoderRPR, self).__init__() self.past_layers = _get_clones(encoder_past, 1) self.layers = _get_clones(enco...
# TransformerEncoderRPR class TransformerEncoderRPR(Module): def __init__(self, encoder_layer, num_layers, encoder_past, max_seq, c_max_seq, b_max_seq, norm=None): super(TransformerEncoderRPR, self).__init__() self.past_layers = _get_clones(encoder_past, 1) self.layers = _get_clones(enco...
args = parse_train_args()
1
2023-11-01 08:33:08+00:00
2k
a16z-infra/sunlight
model/agent.py
[ { "identifier": "DiffbotClient", "path": "model/diffbot.py", "snippet": "class DiffbotClient(object):\n\n BASE_API_URL = 'http://api.diffbot.com'\n TIMEOUT_MS = 15000\n\n def request(self, url, token, api, version=3):\n ''' Issue a request to the Diffbot API and return the response if va...
from datetime import datetime from threading import Thread from langchain.callbacks.base import BaseCallbackHandler from langchain.chains import LLMChain from langchain.chat_models import ChatOpenAI from langchain.prompts import PromptTemplate from .diffbot import DiffbotClient from .prompts import BIAS_REPORT, FACTUAL...
1,398
DIFFBOT_API_KEY = os.environ['DIFFBOT_API_KEY'] REQUEST_LOG_FILE = os.environ['REQUEST_LOG_FILE'] MAX_MODEL_CONTEXT = { 'gpt-3.5-turbo': 4096, 'text-davinci-003': 4096, 'gpt-4': 8192, } class OpenAIStreamHandler(BaseCallbackHandler): def __init__(self, stream_queue, *args, **kwargs): supe...
DIFFBOT_API_KEY = os.environ['DIFFBOT_API_KEY'] REQUEST_LOG_FILE = os.environ['REQUEST_LOG_FILE'] MAX_MODEL_CONTEXT = { 'gpt-3.5-turbo': 4096, 'text-davinci-003': 4096, 'gpt-4': 8192, } class OpenAIStreamHandler(BaseCallbackHandler): def __init__(self, stream_queue, *args, **kwargs): supe...
diffbot = DiffbotClient()
0
2023-11-01 17:19:54+00:00
2k
elenacliu/GraspStudio
cameras/realsense.py
[ { "identifier": "CameraConfig", "path": "cameras/camera.py", "snippet": "class CameraConfig(InstantiateConfig):\n \"\"\"Camera Config\"\"\"\n _target: Type = field(default_factory=lambda : Camera)\n # focal length of x axis\n fx: float = 0.0\n # focal length of y axis\n fy: float = 0.0...
from dataclasses import dataclass, field from typing import Type from .camera import CameraConfig, Camera import pyrealsense2 as rs import numpy as np import cv2
1,298
# Copyright 2023 Chang Liu. 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 applicable law or a...
# Copyright 2023 Chang Liu. 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 applicable law or a...
class RealSenseCamera(Camera):
1
2023-11-08 09:44:22+00:00
2k
serl-robot/serl
serl/wrappers/pixels.py
[ { "identifier": "FrameStack", "path": "serl/wrappers/frame_stack.py", "snippet": "class FrameStack(gym.Wrapper):\n def __init__(self, env, num_stack: int, stacking_key: str = \"pixels\"):\n super().__init__(env)\n self._num_stack = num_stack\n self._stacking_key = stacking_key\n\...
from typing import Optional, Tuple from gym.wrappers.pixel_observation import PixelObservationWrapper from serl.wrappers.frame_stack import FrameStack from serl.wrappers.repeat_action import RepeatAction from serl.wrappers.universal_seed import UniversalSeed import gym
809
def wrap_pixels( env: gym.Env, action_repeat: int, image_size: int = 84, num_stack: Optional[int] = 3, camera_id: int = 0, pixel_keys: Tuple[str, ...] = ("pixels",), ) -> gym.Env: if action_repeat > 1: env = RepeatAction(env, action_repeat)
def wrap_pixels( env: gym.Env, action_repeat: int, image_size: int = 84, num_stack: Optional[int] = 3, camera_id: int = 0, pixel_keys: Tuple[str, ...] = ("pixels",), ) -> gym.Env: if action_repeat > 1: env = RepeatAction(env, action_repeat)
env = UniversalSeed(env)
2
2023-11-02 23:32:24+00:00
2k
daily-demos/ai-meeting-assistant
server/llm/openai_assistant.py
[ { "identifier": "Assistant", "path": "server/llm/assistant.py", "snippet": "class Assistant(ABC):\n \"\"\"Abstract class defining methods that should be implemented by any assistant\"\"\"\n\n @abstractmethod\n def register_new_context(self, new_text: str,\n name: lis...
import asyncio import logging import threading from collections import deque from openai import OpenAI from openai.types.beta import Assistant from openai.types.chat import ChatCompletionMessageParam, ChatCompletionSystemMessageParam, \ ChatCompletionUserMessageParam from server.llm.assistant import Assistant, NoCo...
1,479
def probe_api_key(api_key: str) -> bool: """Probes the OpenAI API with the provided key to ensure it is valid.""" try: client = OpenAI(api_key=api_key) client.chat.completions.create( model="gpt-3.5-turbo", messages=[ ChatCompletionUserMessageParam( ...
"""Module that defines an OpenAI assistant.""" _assistant_name = "daily-ai-assistant" def probe_api_key(api_key: str) -> bool: """Probes the OpenAI API with the provided key to ensure it is valid.""" try: client = OpenAI(api_key=api_key) client.chat.completions.create( model="gp...
raise NoContextError()
1
2023-11-02 11:17:16+00:00
2k
Kushalhk/AutoFilter
plugins/inline.py
[ { "identifier": "get_search_results", "path": "database/ia_filterdb.py", "snippet": "async def get_search_results(chat_id, query, file_type=None, max_results=10, offset=0, filter=False):\n \"\"\"For given query return (results, next_offset)\"\"\"\n if chat_id is not None:\n settings = await...
import logging from pyrogram import Client, emoji, filters from pyrogram.errors.exceptions.bad_request_400 import QueryIdInvalid from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, InlineQueryResultCachedDocument, InlineQuery from database.ia_filterdb import get_search_results from utils import is_su...
1,485
logger = logging.getLogger(__name__) cache_time = 0 if AUTH_USERS or AUTH_CHANNEL else CACHE_TIME async def inline_users(query: InlineQuery): if AUTH_USERS: if query.from_user and query.from_user.id in AUTH_USERS: return True else: return False if query.from_user and qu...
logger = logging.getLogger(__name__) cache_time = 0 if AUTH_USERS or AUTH_CHANNEL else CACHE_TIME async def inline_users(query: InlineQuery): if AUTH_USERS: if query.from_user and query.from_user.id in AUTH_USERS: return True else: return False if query.from_user and qu...
if CUSTOM_FILE_CAPTION:
7
2023-11-03 12:21:26+00:00
2k
tiendatnguyen-vision/Orbit-symmetrize
RotatedMNIST/LPS/emlp-pytorch/tests/model_tests.py
[ { "identifier": "rel_error", "path": "RotatedMNIST/LPS/emlp-pytorch/tests/equivariance_tests.py", "snippet": "def rel_error(t1, t2):\r\n \"\"\" Computes the relative error of two tensors. \"\"\"\r\n error = torch.sqrt(torch.mean(torch.abs(t1-t2)**2))\r\n scale = torch.sqrt(torch.mean(torch.abs(...
import torch from torch.utils.data import DataLoader from oil.utils.utils import FixedNumpySeed, FixedPytorchSeed from emlp_pytorch.nn import EMLP from emlp_pytorch.groups import S, SO, DirectProduct from emlp_pytorch.reps import vis, sparsify_basis, V, Rep, LazyKron, T from .equivariance_tests import rel_error, scale_...
1,384
""" Tests for the EMLP model.""" def equivariance_err(model, mb, repin, repout, group): """ Computes the equivariance error of a model on a minibatch mb. """ x, y = mb gs = group.samples(x.size(0)) rho_gin = torch.vmap(repin(group).rho_dense)(gs) rho_gout = torch.vmap(repout(group).rho_dense)(gs) ...
""" Tests for the EMLP model.""" def equivariance_err(model, mb, repin, repout, group): """ Computes the equivariance error of a model on a minibatch mb. """ x, y = mb gs = group.samples(x.size(0)) rho_gin = torch.vmap(repin(group).rho_dense)(gs) rho_gout = torch.vmap(repout(group).rho_dense)(gs) ...
assert rel_error(out1, out2) < 1e-4, "EMLP equivariance fails on bespoke productsubrep"
0
2023-11-01 07:19:02+00:00
2k
crizbae/PictoPlan
backend/mongo_api/app/server/routes/item_routes.py
[ { "identifier": "collection", "path": "backend/mongo_api/app/server/database.py", "snippet": "MONGO_URI = config(\"MONGO_URI\")\ndef item_helper(item) -> dict:\ndef ret_link(item) -> dict:\nasync def retrieve_all_items():\nasync def retrieve_item(item_id: str):\nasync def retrieve_links(session_id: str)...
from fastapi import APIRouter, Depends, HTTPException from ..database import collection from ..models.item import Item from ..database import retrieve_all_items, retrieve_item, update_item_in_db, delete_item_from_db, retrieve_links
815
router = APIRouter() @router.post("/items/") def create_item(item: Item): item_dict = item.dict() inserted_item = collection.insert_one(item_dict) item_id = str(inserted_item.inserted_id) del item_dict["_id"] item_dict["id"] = item_id return item_dict @router.get("/items/") async def get_all_...
router = APIRouter() @router.post("/items/") def create_item(item: Item): item_dict = item.dict() inserted_item = collection.insert_one(item_dict) item_id = str(inserted_item.inserted_id) del item_dict["_id"] item_dict["id"] = item_id return item_dict @router.get("/items/") async def get_all_...
success = await delete_item_from_db(item_id)
5
2023-11-04 16:48:55+00:00
2k
xenxxxx/BitPay-Crypto-Signal-Trading-Bot
tests/data/test_btanalysis.py
[ { "identifier": "CURRENT_TEST_STRATEGY", "path": "tests/conftest.py", "snippet": "CURRENT_TEST_STRATEGY = 'StrategyTestV3'" }, { "identifier": "create_mock_trades", "path": "tests/conftest.py", "snippet": "def create_mock_trades(fee, is_short: Optional[bool] = False, use_db: bool = True)...
from datetime import datetime, timedelta, timezone from pathlib import Path from unittest.mock import MagicMock from pandas import DataFrame, DateOffset, Timestamp, to_datetime from freqtrade.configuration import TimeRange from freqtrade.constants import LAST_BT_RESULT_FN from freqtrade.data.btanalysis import (BT_DATA_...
1,532
def test_get_latest_backtest_filename(testdatadir, mocker): with pytest.raises(ValueError, match=r"Directory .* does not exist\."): get_latest_backtest_filename(testdatadir / 'does_not_exist') with pytest.raises(ValueError, match=r"Directory .* does not seem to contain .*"): ...
def test_get_latest_backtest_filename(testdatadir, mocker): with pytest.raises(ValueError, match=r"Directory .* does not exist\."): get_latest_backtest_filename(testdatadir / 'does_not_exist') with pytest.raises(ValueError, match=r"Directory .* does not seem to contain .*"): ...
create_mock_trades(fee, is_short)
1
2023-11-07 18:46:03+00:00
2k
ssajedi/SAiF-GPT
bin/main.py
[ { "identifier": "anonymize_text", "path": "utils.py", "snippet": "def augment_prompt(prompt,ref_doc):\ndef extract_pdf_text(file):" }, { "identifier": "extract_pdf_text", "path": "utils.py", "snippet": "def extract_pdf_text(file):\n \"\"\"\n Extracts text paragraphs from a PDF file...
import streamlit as st import random import time import openai import openai import streamlit as st from utils import anonymize_text, deanonymize_text, chatbot_response from utils import extract_pdf_text from text_effects import highlight_phrases_in_paragraph from DetectEntity import DetectEntity
815
st.title("AInonymous") system_prompt="""You are a helpful assistant, your task is to review an uploaded document\ uploaded by a user.\ The user query is delimited by triple asterisks.\ The reference documents in that message are delimited with triple backticks.\ A user might ask follow up questions. """ # add a se...
st.title("AInonymous") system_prompt="""You are a helpful assistant, your task is to review an uploaded document\ uploaded by a user.\ The user query is delimited by triple asterisks.\ The reference documents in that message are delimited with triple backticks.\ A user might ask follow up questions. """ # add a se...
_,chunks = extract_pdf_text(uploaded_file)
1
2023-11-04 18:14:49+00:00
2k
awslabs/optimizing-multitask-training-through-dynamic-pipelines
tests/test_kv_store.py
[ { "identifier": "_get_from_shared_kv_store", "path": "dynapipe/pipe/data_loader.py", "snippet": "def _get_from_shared_kv_store(\n kv_store: RedisKVStore,\n key: str,\n reader_idx: int,\n n_total_readers: int,\n decode: bool = True,\n logger=None,\n):\n reader_count_key = key + \"_rc...
import multiprocessing as mp import time import traceback import traceback from dynapipe.pipe.data_loader import ( _get_from_shared_kv_store, _init_kv_store, _put_to_shared_kv_store, )
1,336
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # Note: this test requires torch # to run this test, exec: # DYNAPIPE_DEBUG=DEBUG DYNAPIPE_LOGGING_DEBUG_DIR=./test_debug \ # torchrun --standalone --nnodes=1 --nproc_per_node=1 test_kv_store.py def _producer...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # Note: this test requires torch # to run this test, exec: # DYNAPIPE_DEBUG=DEBUG DYNAPIPE_LOGGING_DEBUG_DIR=./test_debug \ # torchrun --standalone --nnodes=1 --nproc_per_node=1 test_kv_store.py def _producer...
payload = _get_from_shared_kv_store(
0
2023-11-08 07:58:20+00:00
2k
dask-contrib/dask-databricks
dask_databricks/tests/test_databricks.py
[ { "identifier": "DatabricksCluster", "path": "dask_databricks/databrickscluster.py", "snippet": "class DatabricksCluster(Cluster):\n \"\"\"Connect to a Dask cluster deployed via databricks.\"\"\"\n\n def __init__(\n self,\n loop: Optional[IOLoop] = None,\n asynchronous: bool =...
import os import pytest from dask.distributed import Client from distributed.deploy import Cluster, LocalCluster from dask_databricks import DatabricksCluster, get_client
669
@pytest.fixture(scope="session") def dask_cluster(): """Start a LocalCluster to simulate the cluster that would be started on Databricks.""" return LocalCluster(scheduler_port=8786) @pytest.fixture def remove_spark_local_ip(): original_spark_local_ip = os.getenv("SPARK_LOCAL_IP") if original_spark...
@pytest.fixture(scope="session") def dask_cluster(): """Start a LocalCluster to simulate the cluster that would be started on Databricks.""" return LocalCluster(scheduler_port=8786) @pytest.fixture def remove_spark_local_ip(): original_spark_local_ip = os.getenv("SPARK_LOCAL_IP") if original_spark...
DatabricksCluster()
0
2023-11-02 13:49:27+00:00
2k
indiefan/king_smith
custom_components/king_smith/coordinator.py
[ { "identifier": "DOMAIN", "path": "custom_components/king_smith/const.py", "snippet": "DOMAIN = \"king_smith\"" }, { "identifier": "WalkingPadApi", "path": "custom_components/king_smith/walking_pad.py", "snippet": "class WalkingPadApi:\n \"\"\"Walkingpad device.\"\"\"\n\n def __ini...
from datetime import datetime from homeassistant.core import CALLBACK_TYPE, HassJob, HomeAssistant, callback from homeassistant.helpers.event import async_call_later from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from ph4_walkingpad.pad import WalkingPadCurStatus from .const import DOMAIN fr...
1,339
"""The Walking Pad Coordinator.""" _LOGGER = logging.getLogger(__name__) NEVER_TIME = -86400.0 DEBOUNCE_SECONDS = 1.0 class WalkingPadCoordinator(DataUpdateCoordinator[None]): """Data coordinator for receiving Walking Pad updates.""" def __init__(self, hass: HomeAssistant, walking_pad_api: WalkingPadApi...
"""The Walking Pad Coordinator.""" _LOGGER = logging.getLogger(__name__) NEVER_TIME = -86400.0 DEBOUNCE_SECONDS = 1.0 class WalkingPadCoordinator(DataUpdateCoordinator[None]): """Data coordinator for receiving Walking Pad updates.""" def __init__(self, hass: HomeAssistant, walking_pad_api: WalkingPadApi...
name=DOMAIN,
0
2023-11-03 20:45:03+00:00
2k
ndiamant/spice
spice/conditional_histogram.py
[ { "identifier": "BaseLightning", "path": "spice/utils.py", "snippet": "class BaseLightning(LightningModule):\n def _configure_optimizers(self, parameters: Iterator[torch.nn.Parameter]):\n opt = optim.AdamW(\n parameters, lr=self.hparams.lr, weight_decay=self.hparams.wd,\n )\n...
import copy import math import torch import torch.nn.functional as F import matplotlib.pyplot as plt import matplotlib.patches as mpatches from tqdm import tqdm from torch import nn from spice.utils import ( BaseLightning, MLP, unique_quantile, score_to_q_hat, compute_conformal_metrics, )
1,548
def select_bins(y: torch.Tensor, n_bins: int) -> torch.Tensor: return unique_quantile(y, n_bins, first_bin_zero=False) def discretize(y: torch.Tensor, bins: torch.Tensor) -> torch.Tensor: return torch.bucketize(y.clip(max=bins[-1] - 1e-5), boundaries=bins)
def select_bins(y: torch.Tensor, n_bins: int) -> torch.Tensor: return unique_quantile(y, n_bins, first_bin_zero=False) def discretize(y: torch.Tensor, bins: torch.Tensor) -> torch.Tensor: return torch.bucketize(y.clip(max=bins[-1] - 1e-5), boundaries=bins)
class ConditionalHist(BaseLightning):
0
2023-11-01 18:04:29+00:00
2k
nik-sm/com-hom-emg
tests/test_data.py
[ { "identifier": "get_datasets", "path": "com_hom_emg/data.py", "snippet": "def get_datasets(\n per_subj_data: dict,\n fold: int,\n n_train_subj: int,\n n_val_subj: int,\n n_test_subj: int,\n use_preprocessed_data: bool,\n return_subj_names: bool = False, # For testing\n) -> Tuple[T...
import torch from com_hom_emg.data import get_datasets, get_per_subj_data
1,309
def test_get_datasets_disjoint_val_test(): # The subject used for val should be different each time # Likewise for test per_subj_data = get_per_subj_data() all_val_subj = [] all_test_subj = [] n_train = 8 n_val = 1 n_test = 1 expected_train_size = 8 * 1224 # 1224 gestures per s...
def test_get_datasets_disjoint_val_test(): # The subject used for val should be different each time # Likewise for test per_subj_data = get_per_subj_data() all_val_subj = [] all_test_subj = [] n_train = 8 n_val = 1 n_test = 1 expected_train_size = 8 * 1224 # 1224 gestures per s...
train_set, val_set, test_set, train_subj, val_subj, test_subj = get_datasets(
0
2023-11-01 21:12:05+00:00
2k
alengwenus/ha-sma-ev-charger
custom_components/smaev/select.py
[ { "identifier": "DOMAIN", "path": "custom_components/smaev/const.py", "snippet": "DOMAIN = \"smaev\"" }, { "identifier": "SMAEV_COORDINATOR", "path": "custom_components/smaev/const.py", "snippet": "SMAEV_COORDINATOR = \"coordinator\"" }, { "identifier": "SMAEV_DEVICE_INFO", "...
from dataclasses import dataclass, field from datetime import datetime from typing import TYPE_CHECKING from pysmaev.const import SmaEvChargerParameters from pysmaev.helpers import get_parameters_channel from homeassistant.components.select import SelectEntity, SelectEntityDescription from homeassistant.config_entries ...
1,047
"""Select platform for SMA EV Charger integration.""" from __future__ import annotations _LOGGER = logging.getLogger(__name__) @dataclass class SmaEvChargerSelectEntityDescription(SelectEntityDescription): """Describes SMA EV Charger select entities.""" type: str = "" channel: str = "" value_map...
"""Select platform for SMA EV Charger integration.""" from __future__ import annotations _LOGGER = logging.getLogger(__name__) @dataclass class SmaEvChargerSelectEntityDescription(SelectEntityDescription): """Describes SMA EV Charger select entities.""" type: str = "" channel: str = "" value_map...
value = channel[SMAEV_VALUE]
5
2023-11-04 07:08:41+00:00
2k
microsoft/promptbase
azureml/components/src/shared/jsonl_utils.py
[ { "identifier": "JSONLReader", "path": "azureml/components/src/shared/jsonl_file_utils.py", "snippet": "class JSONLReader:\n \"\"\"Line-by-line iteration over a JSONL file\n\n Can be used in a 'with' statement, and then iterated over.\n The returned value is a decoded JSON object, rather than\n...
import json import pathlib import tempfile import traceback from typing import Any, Callable, Tuple from .jsonl_file_utils import JSONLReader, JSONLWriter from .logging_utils import get_standard_logger_for_file
808
# Copied from Medprompt.... perhaps those utils should go to PyPi? _logger = get_standard_logger_for_file(__file__) def line_map( *, map_func: Callable[[dict[str, Any]], dict[str, Any] | None], source_file: pathlib.Path, dest_file: pathlib.Path, source_encoding: str, dest_encoding: str, ...
# Copied from Medprompt.... perhaps those utils should go to PyPi? _logger = get_standard_logger_for_file(__file__) def line_map( *, map_func: Callable[[dict[str, Any]], dict[str, Any] | None], source_file: pathlib.Path, dest_file: pathlib.Path, source_encoding: str, dest_encoding: str, ...
with JSONLReader(source_file, source_encoding) as in_file:
0
2023-12-12 08:00:11+00:00
2k
openai/weak-to-strong
weak_to_strong/train.py
[ { "identifier": "clear_mem", "path": "weak_to_strong/common.py", "snippet": "def clear_mem(verbose: bool = False):\n \"\"\"\n This function is used to clear the memory allocated by PyTorch.\n It does so by calling the garbage collector to release unused GPU memory.\n After clearing the memor...
import itertools import os import pickle import time import datasets import numpy as np import torch import torch_optimizer as toptim import weak_to_strong.logger as logger from dataclasses import dataclass from typing import Callable, Optional from transformers.modeling_utils import load_sharded_checkpoint from weak_t...
1,558
@dataclass class ModelConfig: name: str default_lr: float eval_batch_size: int custom_kwargs: Optional[dict] = None gradient_checkpointing: bool = False model_parallel: bool = False default_optimizer: str = "adam" def train_model( model: torch.nn.Module, ds: datasets.Dataset, ...
@dataclass class ModelConfig: name: str default_lr: float eval_batch_size: int custom_kwargs: Optional[dict] = None gradient_checkpointing: bool = False model_parallel: bool = False default_optimizer: str = "adam" def train_model( model: torch.nn.Module, ds: datasets.Dataset, ...
loss_fn: Callable = xent_loss,
2
2023-12-13 23:53:13+00:00
2k
SqueezeAILab/LLMCompiler
configs/hotpotqa/configs.py
[ { "identifier": "OUTPUT_PROMPT", "path": "configs/hotpotqa/gpt_prompts.py", "snippet": "OUTPUT_PROMPT = (\n \"Solve a question answering task with interleaving Observation, Thought, and Action steps. Here are some guidelines:\\n\"\n \" - You will be given a Question and some Wikipedia passages, w...
from configs.hotpotqa.gpt_prompts import OUTPUT_PROMPT, PLANNER_PROMPT
945
CONFIGS = { "default_model": "gpt-3.5-turbo-1106", "planner_prompt": PLANNER_PROMPT,
CONFIGS = { "default_model": "gpt-3.5-turbo-1106", "planner_prompt": PLANNER_PROMPT,
"output_prompt": OUTPUT_PROMPT,
0
2023-12-06 21:12:54+00:00
2k
open-compass/MixtralKit
mixtralkit/layers/attention.py
[ { "identifier": "ModelArgs", "path": "mixtralkit/layers/utils.py", "snippet": "class ModelArgs:\n dim: int = 4096\n n_layers: int = 32\n n_heads: int = 32\n n_kv_heads: Optional[int] = None\n vocab_size: int = -1 # defined later by tokenizer\n multiple_of: int = 256 # make SwiGLU hid...
import math import torch import torch.nn.functional as F import fairscale.nn.model_parallel.initialize as fs_init from typing import Optional, Tuple from torch import nn from .utils import ModelArgs, repeat_kv from .position_embeding import apply_rotary_emb from fairscale.nn.model_parallel.layers import...
1,488
# Copyright (c) OpenMMLab. and affiliates. # Copyright (c) Meta Platforms, Inc. and affiliates. class TorchAttention(nn.Module): """Multi-head attention module.""" def __init__(self, args: ModelArgs): """ Initialize the Attention module. Args: args (ModelArgs): Mo...
# Copyright (c) OpenMMLab. and affiliates. # Copyright (c) Meta Platforms, Inc. and affiliates. class TorchAttention(nn.Module): """Multi-head attention module.""" def __init__(self, args: ModelArgs): """ Initialize the Attention module. Args: args (ModelArgs): Mo...
xq, xk = apply_rotary_emb(xq, xk, freqs_cis=freqs_cis)
2
2023-12-09 15:05:26+00:00
2k
aymenfurter/microagents
gradio_ui/agent_manager.py
[ { "identifier": "MicroAgentManager", "path": "agents/microagent_manager.py", "snippet": "class MicroAgentManager:\n \"\"\"\n Manages the creation and retrieval of micro agents.\n \"\"\"\n\n def __init__(self, api_key: str, max_agents: int = 20, db_filename=\"agents.db\"):\n self.api_k...
import logging from typing import Any, List from agents.microagent_manager import MicroAgentManager from agents.microagent import MicroAgent
1,527
logger = logging.getLogger(__name__) class GradioAgentManager: """ A wrapper class for interacting with MicroAgentManager in a Gradio interface. """ def __init__(self, api_key: str): self.manager = MicroAgentManager(api_key) self.manager.create_agents() def get_agents_info(self)...
logger = logging.getLogger(__name__) class GradioAgentManager: """ A wrapper class for interacting with MicroAgentManager in a Gradio interface. """ def __init__(self, api_key: str): self.manager = MicroAgentManager(api_key) self.manager.create_agents() def get_agents_info(self)...
def format_agent_info(self, agent: MicroAgent) -> dict:
1
2023-12-11 08:17:09+00:00
2k
bytedance/ImageDream
extern/ldm_zero123/thirdp/psp/model_irse.py
[ { "identifier": "Flatten", "path": "extern/ldm_zero123/thirdp/psp/helpers.py", "snippet": "class Flatten(Module):\n def forward(self, input):\n return input.view(input.size(0), -1)" }, { "identifier": "bottleneck_IR", "path": "extern/ldm_zero123/thirdp/psp/helpers.py", "snippet...
from torch.nn import ( BatchNorm1d, BatchNorm2d, Conv2d, Dropout, Linear, Module, PReLU, Sequential, ) from extern.ldm_zero123.thirdp.psp.helpers import ( Flatten, bottleneck_IR, bottleneck_IR_SE, get_blocks, l2_norm, )
1,205
# https://github.com/eladrich/pixel2style2pixel """ Modified Backbone implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch) """ class Backbone(Module): def __init__(self, input_size, num_layers, mode="ir", drop_ratio=0.4, affine=True): super(Backbone, self).__init__() as...
# https://github.com/eladrich/pixel2style2pixel """ Modified Backbone implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch) """ class Backbone(Module): def __init__(self, input_size, num_layers, mode="ir", drop_ratio=0.4, affine=True): super(Backbone, self).__init__() as...
unit_module = bottleneck_IR
1
2023-12-13 21:09:37+00:00
2k
TencentARC/MotionCtrl
lvdm/modules/attention_temporal.py
[ { "identifier": "checkpoint", "path": "lvdm/common.py", "snippet": "def checkpoint(func, inputs, params, flag):\n \"\"\"\n Evaluate a function without caching intermediate activations, allowing for\n reduced memory at the expense of extra compute in the backward pass.\n :param func: the func...
import math import torch import torch as th import torch.nn.functional as F import xformers import xformers.ops from inspect import isfunction from torch import nn, einsum from einops import rearrange, repeat from lvdm.common import ( checkpoint, exists, uniq, default, max_neg_value, ini...
842
try: XFORMERS_IS_AVAILBLE = True except: XFORMERS_IS_AVAILBLE = False class GEGLU(nn.Module): def __init__(self, dim_in, dim_out): super().__init__() self.proj = nn.Linear(dim_in, dim_out * 2) def forward(self, x): x, gate = self.proj(x).chunk(2, dim=-1) return x...
try: XFORMERS_IS_AVAILBLE = True except: XFORMERS_IS_AVAILBLE = False class GEGLU(nn.Module): def __init__(self, dim_in, dim_out): super().__init__() self.proj = nn.Linear(dim_in, dim_out * 2) def forward(self, x): x, gate = self.proj(x).chunk(2, dim=-1) return x...
dim_out = default(dim_out, dim)
3
2023-12-06 07:27:45+00:00
2k
s-casci/tinyzero
tictactoe/one_dim/eval.py
[ { "identifier": "LinearNetwork", "path": "models.py", "snippet": "class LinearNetwork(nn.Module):\n def __init__(self, input_shape, action_space, first_layer_size=512, second_layer_size=256):\n super().__init__()\n self.first_layer = nn.Linear(input_shape[0], first_layer_size)\n self.second_la...
from game import TicTacToe from train import OUT_DIR, SEARCH_ITERATIONS from tqdm import tqdm from models import LinearNetwork # noqa: E402 from agents import AlphaZeroAgent, ClassicMCTSAgent # noqa: E402 from mcts import pit # noqa: E402 import torch import os import sys
948
sys.path.append(os.getcwd()) EVAL_GAMES = 100 if __name__ == "__main__": game = TicTacToe() model = LinearNetwork(game.observation_shape, game.action_space) model.load_state_dict(torch.load(f"{OUT_DIR}/model.pth")) agent = AlphaZeroAgent(model) agent_play_kwargs = {"search_iterations": SEARCH_ITERATIONS...
sys.path.append(os.getcwd()) EVAL_GAMES = 100 if __name__ == "__main__": game = TicTacToe() model = LinearNetwork(game.observation_shape, game.action_space) model.load_state_dict(torch.load(f"{OUT_DIR}/model.pth")) agent = AlphaZeroAgent(model) agent_play_kwargs = {"search_iterations": SEARCH_ITERATIONS...
result = pit(
3
2023-12-14 11:36:50+00:00
2k
facebookresearch/PurpleLlama
CybersecurityBenchmarks/insecure_code_detector/tests/test_python_insecure_code_detector.py
[ { "identifier": "Language", "path": "CybersecurityBenchmarks/insecure_code_detector/languages.py", "snippet": "class Language(str, enum.Enum):\n C = \"c\"\n CPP = \"cpp\"\n CSHARP = \"csharp\"\n HACK = \"hack\"\n JAVA = \"java\"\n JAVASCRIPT = \"javascript\"\n KOTLIN = \"kotlin\"\n ...
from ..languages import Language from .insecure_code_detector_test import InsecureCodeDetectorTest
716
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # the following test cases contain an input string, and the corresponding number of expected insecure pattern matches PYTHON_TEST_CASES = ...
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # the following test cases contain an input string, and the corresponding number of expected insecure pattern matches PYTHON_TEST_CASES = ...
class TestPythonInsecureCodeDetector(InsecureCodeDetectorTest):
1
2023-12-06 21:29:41+00:00
2k
allenai/unified-io-2
t5x/examples/unified_io/modality_processing.py
[ { "identifier": "AudioEncoder", "path": "t5x/examples/unified_io/audio_encoder.py", "snippet": "class AudioEncoder(nn.Module):\n \"\"\"Encodes raw audio spectrograms as features\"\"\"\n config: Union[ImageVitFeatureConfig, AudioVitFeatureConfig]\n\n def setup(self):\n cfg = self.config\n # `vis...
from collections import OrderedDict from typing import Mapping from flax import traverse_util from seqio import TaskRegistry, FeatureConverter from t5x.examples.unified_io.audio_encoder import AudioEncoder from t5x.examples.unified_io.image_encoder import ImageEncoder from t5x.examples.unified_io.input_modalities impor...
890
"""Code for handling modalities""" @gin.configurable def get_target_modalities( target_modality=['text', 'image', 'audio'], image_vae_config: ImageViTVQGANConfig=VAEConfig(), audio_vae_config: AudioViTVQGANConfig=AudioViTVQGANConfig(), ) -> Dict[str, ModalityEncoder]: """Return the encoders to use ...
"""Code for handling modalities""" @gin.configurable def get_target_modalities( target_modality=['text', 'image', 'audio'], image_vae_config: ImageViTVQGANConfig=VAEConfig(), audio_vae_config: AudioViTVQGANConfig=AudioViTVQGANConfig(), ) -> Dict[str, ModalityEncoder]: """Return the encoders to use ...
audio_encoder = AudioEncoder(audio_vit_cfg)
0
2023-12-12 20:23:33+00:00
2k
zju3dv/EasyVolcap
scripts/gaussian/merge_pcd.py
[ { "identifier": "load_pts", "path": "easyvolcap/utils/data_utils.py", "snippet": "def load_pts(filename: str):\n from pyntcloud import PyntCloud\n cloud = PyntCloud.from_file(filename)\n verts = cloud.xyz\n if 'red' in cloud.points and 'green' in cloud.points and 'blue' in cloud.points:\n ...
from easyvolcap.utils.console_utils import * from easyvolcap.utils.data_utils import load_pts, export_pts from os.path import join import argparse import numpy as np
1,196
""" This script will load and convert a .ply visual hull to a points3D file """ @catch_throw def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--data_root', default='data/enerf_outdoor/actor2_3') parser.add_argument('--vhulls_dir', default='merged') parser.add_ar...
""" This script will load and convert a .ply visual hull to a points3D file """ @catch_throw def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--data_root', default='data/enerf_outdoor/actor2_3') parser.add_argument('--vhulls_dir', default='merged') parser.add_ar...
v, c, n, s = load_pts(vhull)
0
2023-12-07 08:53:42+00:00
2k
minghanqin/LangSplat
scene/cameras.py
[ { "identifier": "getWorld2View2", "path": "utils/graphics_utils.py", "snippet": "def getWorld2View2(R, t, translate=np.array([.0, .0, .0]), scale=1.0):\n Rt = np.zeros((4, 4))\n Rt[:3, :3] = R.transpose()\n Rt[:3, 3] = t\n Rt[3, 3] = 1.0\n\n C2W = np.linalg.inv(Rt)\n cam_center = C2W[:...
import os import pickle import torch import numpy as np from torch import nn from utils.graphics_utils import getWorld2View2, getProjectionMatrix
922
# # Copyright (C) 2023, Inria # GRAPHDECO research group, https://team.inria.fr/graphdeco # All rights reserved. # # This software is free for non-commercial, research and evaluation use # under the terms of the LICENSE.md file. # # For inquiries contact george.drettakis@inria.fr # class Camera(nn.Module): def _...
# # Copyright (C) 2023, Inria # GRAPHDECO research group, https://team.inria.fr/graphdeco # All rights reserved. # # This software is free for non-commercial, research and evaluation use # under the terms of the LICENSE.md file. # # For inquiries contact george.drettakis@inria.fr # class Camera(nn.Module): def _...
self.projection_matrix = getProjectionMatrix(znear=self.znear, zfar=self.zfar, fovX=self.FoVx, fovY=self.FoVy).transpose(0,1).cuda()
1
2023-12-11 06:33:35+00:00
2k
SciPhi-AI/agent-search
agent_search/search/base.py
[ { "identifier": "AgentSearchResult", "path": "agent_search/core/search_types.py", "snippet": "class AgentSearchResult(BaseModel):\n \"\"\"A dataclass to store the search result\"\"\"\n\n score: float\n url: str\n title: Optional[str]\n dataset: Optional[str]\n # TODO - Add dict(str, [s...
import csv import json import logging import os import numpy as np import psycopg2 import psycopg2 from typing import List from qdrant_client import QdrantClient from transformers import AutoModel from agent_search.core import AgentSearchResult from agent_search.core.utils import ( cosine_similarity, ...
650
logger = logging.getLogger(__name__) class WebSearchEngine: """A simple search client for the OpenSearch collection""" def __init__( self, ): try: except ImportError as e: raise ImportError( f"Error {e} while imoprting psycopg2. Please install it wit...
logger = logging.getLogger(__name__) class WebSearchEngine: """A simple search client for the OpenSearch collection""" def __init__( self, ): try: except ImportError as e: raise ImportError( f"Error {e} while imoprting psycopg2. Please install it wit...
self.config = load_config()["agent_search"]
3
2023-12-11 17:41:03+00:00
2k
yohanshin/WHAM
lib/data/_dataset.py
[ { "identifier": "constants", "path": "configs/constants.py", "snippet": "IMG_FEAT_DIM = {\n 'resnet': 2048,\n 'vit': 1024\n}\nN_JOINTS = 17\n PARSED_DATA = f'{root}/parsed_data'\n THREEDPW_PTH = f'{root}/3DPW'\n RICH_PTH = f'{root}/RICH'\n EMDB_PTH = f'{root}/EMDB'\n NUM_JOINTS = N_...
import torch import numpy as np from skimage.util.shape import view_as_windows from configs import constants as _C from .normalizer import Normalizer from lib.utils.imutils import transform
1,499
from __future__ import absolute_import from __future__ import print_function from __future__ import division class BaseDataset(torch.utils.data.Dataset): def __init__(self, cfg, training=True): super(BaseDataset, self).__init__() self.n_joints = _C.KEYPOINTS.NUM_JOINTS self.epoch = 0 ...
from __future__ import absolute_import from __future__ import print_function from __future__ import division class BaseDataset(torch.utils.data.Dataset): def __init__(self, cfg, training=True): super(BaseDataset, self).__init__() self.n_joints = _C.KEYPOINTS.NUM_JOINTS self.epoch = 0 ...
self.keypoints_normalizer = Normalizer(cfg)
1
2023-12-08 09:17:54+00:00
2k
octo-models/octo
octo/data/oxe/oxe_standardization_transforms.py
[ { "identifier": "binarize_gripper_actions", "path": "octo/data/utils/data_utils.py", "snippet": "def binarize_gripper_actions(actions: tf.Tensor) -> tf.Tensor:\n \"\"\"Converts gripper actions from continous to binary values (0 and 1).\n\n We exploit that fact that most of the time, the gripper is...
from typing import Any, Dict from octo.data.utils.data_utils import ( binarize_gripper_actions, invert_gripper_actions, rel2abs_gripper_actions, relabel_actions, ) import tensorflow as tf import tensorflow_graphics.geometry.transformation as tft import tensorflow_graphics.geometry.transformation...
1,251
"""Open X-Embodiment Dataset Transforms input: dict of features, each is batched, i.e. has leading time dimension expected output: step = { 'observation': { <image_keys, depth_image_keys> state in chosen state representation }, 'action': action in chosen action representation, 'language...
"""Open X-Embodiment Dataset Transforms input: dict of features, each is batched, i.e. has leading time dimension expected output: step = { 'observation': { <image_keys, depth_image_keys> state in chosen state representation }, 'action': action in chosen action representation, 'language...
binarize_gripper_actions(trajectory["action"][:, -1])[:, None],
0
2023-12-13 09:58:56+00:00
2k
mistralai/client-python
tests/test_chat.py
[ { "identifier": "mock_chat_response_payload", "path": "tests/utils.py", "snippet": "def mock_chat_response_payload():\n return orjson.dumps(\n {\n \"id\": \"chat-98c8c60e3fbf4fc49658eddaf447357c\",\n \"object\": \"chat.completion\",\n \"created\": 1703165682,\n...
import unittest.mock as mock import pytest from mistralai.client import MistralClient from mistralai.models.chat_completion import ( ChatCompletionResponse, ChatCompletionStreamResponse, ChatMessage, ) from .utils import ( mock_chat_response_payload, mock_chat_response_streaming_payload, mock_re...
1,007
@pytest.fixture() def client(): client = MistralClient() client._client = mock.MagicMock() return client class TestChat: def test_chat(self, client): client._client.request.return_value = mock_response( 200, mock_chat_response_payload(), ) result = ...
@pytest.fixture() def client(): client = MistralClient() client._client = mock.MagicMock() return client class TestChat: def test_chat(self, client): client._client.request.return_value = mock_response( 200, mock_chat_response_payload(), ) result = ...
client._client.stream.return_value = mock_stream_response(
3
2023-12-07 10:09:51+00:00
2k
kijai/ComfyUI-Marigold
marigold/model/marigold_pipeline.py
[ { "identifier": "RGBEncoder", "path": "marigold/model/rgb_encoder.py", "snippet": "class RGBEncoder(nn.Module):\n \"\"\"\n The encoder of pretrained Stable Diffusion VAE\n \"\"\"\n \n def __init__(self, pretrained_path, subfolder=None) -> None:\n super().__init__()\n \n ...
import logging import numpy as np import torch from typing import Dict from diffusers import ( DDIMScheduler, DDPMScheduler, PNDMScheduler, DEISMultistepScheduler, SchedulerMixin, UNet2DConditionModel, ) from torch import nn from torch.nn import Conv2d from torch.nn.parameter import Parameter fr...
1,225
# Author: Bingxin Ke # Last modified: 2023-12-11 class MarigoldPipeline(nn.Module): """ Marigold monocular depth estimator. """ def __init__( self, unet_pretrained_path: Dict, # {path: xxx, subfolder: xxx} rgb_encoder_pretrained_path: Dict, depht_ae_pretrained_path...
# Author: Bingxin Ke # Last modified: 2023-12-11 class MarigoldPipeline(nn.Module): """ Marigold monocular depth estimator. """ def __init__( self, unet_pretrained_path: Dict, # {path: xxx, subfolder: xxx} rgb_encoder_pretrained_path: Dict, depht_ae_pretrained_path...
self.rgb_encoder = RGBEncoder(
0
2023-12-12 12:25:52+00:00
2k
modelscope/richdreamer
extern/ldm_zero123/thirdp/psp/model_irse.py
[ { "identifier": "Flatten", "path": "extern/ldm_zero123/thirdp/psp/helpers.py", "snippet": "class Flatten(Module):\n def forward(self, input):\n return input.view(input.size(0), -1)" }, { "identifier": "bottleneck_IR", "path": "extern/ldm_zero123/thirdp/psp/helpers.py", "snippet...
from torch.nn import (BatchNorm1d, BatchNorm2d, Conv2d, Dropout, Linear, Module, PReLU, Sequential,) from extern.ldm_zero123.thirdp.psp.helpers import (Flatten, bottleneck_IR, bottleneck_IR_SE, ge...
1,210
# https://github.com/eladrich/pixel2style2pixel """ Modified Backbone implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch) """ class Backbone(Module): def __init__(self, input_size, num_layers, mode="ir", drop_ratio=0.4, affine=True): super(Backbone, self).__init__() as...
# https://github.com/eladrich/pixel2style2pixel """ Modified Backbone implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch) """ class Backbone(Module): def __init__(self, input_size, num_layers, mode="ir", drop_ratio=0.4, affine=True): super(Backbone, self).__init__() as...
unit_module = bottleneck_IR_SE
2
2023-12-06 07:53:11+00:00
2k
rehg-lab/RAVE
annotator/mmpkg/mmcv/runner/base_module.py
[ { "identifier": "master_only", "path": "annotator/mmpkg/mmcv/runner/dist_utils.py", "snippet": "def master_only(func):\n\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n rank, _ = get_dist_info()\n if rank == 0:\n return func(*args, **kwargs)\n\n return wrappe...
import copy import warnings import torch.nn as nn from abc import ABCMeta from collections import defaultdict from logging import FileHandler from annotator.mmpkg.mmcv.runner.dist_utils import master_only from annotator.mmpkg.mmcv.utils.logging import get_logger, logger_initialized, print_log from ..cnn import ...
999
# Copyright (c) OpenMMLab. All rights reserved. class BaseModule(nn.Module, metaclass=ABCMeta): """Base module for all modules in openmmlab. ``BaseModule`` is a wrapper of ``torch.nn.Module`` with additional functionality of parameter initialization. Compared with ``torch.nn.Module``, ``BaseModule`...
# Copyright (c) OpenMMLab. All rights reserved. class BaseModule(nn.Module, metaclass=ABCMeta): """Base module for all modules in openmmlab. ``BaseModule`` is a wrapper of ``torch.nn.Module`` with additional functionality of parameter initialization. Compared with ``torch.nn.Module``, ``BaseModule`...
print_log(
1
2023-12-05 02:51:53+00:00
2k
worldcoin/open-iris
tests/e2e_tests/pipelines/test_e2e_iris_pipeline.py
[ { "identifier": "compare_debug_pipeline_outputs", "path": "tests/e2e_tests/utils.py", "snippet": "def compare_debug_pipeline_outputs(pipeline_output_1: Dict[str, Any], pipeline_output_2: Dict[str, Any]):\n \"\"\"Compare two IRISPipeline outputs for debugging.\n\n Args:\n pipeline_output_1 (...
import os import pickle import cv2 import numpy as np import pytest from typing import Any, Dict from iris.pipelines.iris_pipeline import IRISPipeline from tests.e2e_tests.utils import compare_debug_pipeline_outputs, compare_iris_pipeline_outputs
906
@pytest.fixture def ir_image() -> np.ndarray: ir_image_path = os.path.join(os.path.dirname(__file__), "mocks", "inputs", "anonymized.png") img_data = cv2.imread(ir_image_path, cv2.IMREAD_GRAYSCALE) return img_data @pytest.fixture def expected_iris_pipeline_output() -> Dict[str, Any]: expected_iris...
@pytest.fixture def ir_image() -> np.ndarray: ir_image_path = os.path.join(os.path.dirname(__file__), "mocks", "inputs", "anonymized.png") img_data = cv2.imread(ir_image_path, cv2.IMREAD_GRAYSCALE) return img_data @pytest.fixture def expected_iris_pipeline_output() -> Dict[str, Any]: expected_iris...
compare_debug_pipeline_outputs(computed_pipeline_output, expected_debug_pipeline_output)
0
2023-12-09 22:43:09+00:00
2k
laixintao/mactop
mactop/panels/cpu_percpu_usage.py
[ { "identifier": "LabeledColorBar", "path": "mactop/widgets/labeled_colorbar.py", "snippet": "class LabeledColorBar(Static):\n percentages = reactive(None)\n\n DEFAULT_CSS = \"\"\"\n LabeledColorBar {\n layout: horizontal;\n }\n LabeledColorBar > ColorBar {\n width: 1fr;\n ...
import logging from functools import partial from textual.app import ComposeResult from mactop.widgets import LabeledColorBar from mactop.metrics_store import metrics from mactop.utils.formatting import render_cpu_percentage_100 from ._base import BaseStatic from mactop import const
1,272
logger = logging.getLogger(__name__) def get_percpu_percent(index): cpus = metrics.psutilmetrics.cpu_percent_percpu if not cpus: return [0, 0, 0, 0] cpu_percent = cpus[index] return [ cpu_percent.user, cpu_percent.nice, cpu_percent.system, cpu_percent.idle,...
logger = logging.getLogger(__name__) def get_percpu_percent(index): cpus = metrics.psutilmetrics.cpu_percent_percpu if not cpus: return [0, 0, 0, 0] cpu_percent = cpus[index] return [ cpu_percent.user, cpu_percent.nice, cpu_percent.system, cpu_percent.idle,...
value_render_fn=render_cpu_percentage_100,
2
2023-12-05 09:12:42+00:00
2k
geopavlakos/hamer
hamer/datasets/vitdet_dataset.py
[ { "identifier": "convert_cvimg_to_tensor", "path": "hamer/datasets/utils.py", "snippet": "def convert_cvimg_to_tensor(cvimg: np.array):\n \"\"\"\n Convert image from HWC to CHW format.\n Args:\n cvimg (np.array): Image of shape (H, W, 3) as loaded by OpenCV.\n Returns:\n np.arr...
from typing import Dict from skimage.filters import gaussian from yacs.config import CfgNode from .utils import (convert_cvimg_to_tensor, expand_to_aspect_ratio, generate_image_patch_cv2) import cv2 import numpy as np import torch
1,342
DEFAULT_MEAN = 255. * np.array([0.485, 0.456, 0.406]) DEFAULT_STD = 255. * np.array([0.229, 0.224, 0.225]) class ViTDetDataset(torch.utils.data.Dataset): def __init__(self, cfg: CfgNode, img_cv2: np.array, boxes: np.array, right: np.array, ...
DEFAULT_MEAN = 255. * np.array([0.485, 0.456, 0.406]) DEFAULT_STD = 255. * np.array([0.229, 0.224, 0.225]) class ViTDetDataset(torch.utils.data.Dataset): def __init__(self, cfg: CfgNode, img_cv2: np.array, boxes: np.array, right: np.array, ...
bbox_size = expand_to_aspect_ratio(scale*200, target_aspect_ratio=BBOX_SHAPE).max()
1
2023-12-08 09:07:07+00:00
2k
rogeriochaves/driver
driver/annotator.py
[ { "identifier": "detect_components", "path": "driver/UIED/run_single.py", "snippet": "def detect_components(\n input_path_img, ocr_result: AnnotatedImage, showOCR=False, showUIED=False\n) -> DetectElementsResponse:\n output_root = \"output\"\n\n # Resizes the image to be smaller because this pr...
import math import os import cv2 from PIL import Image, ImageDraw, ImageFont from driver.UIED.run_single import detect_components from driver.UIED.utils import show_image from driver.ocr_call import ocr_text_detection from driver.types import DebugConfig, ImgMultiplierFactor, LabelMap from driver.utils import is_retina...
1,310
def annotate_image(input_image_path, debug: DebugConfig): ocr_result = ocr_text_detection(input_image_path, debug) components = detect_components( input_image_path, ocr_result, showOCR=debug["ocr"], showUIED=debug["uied"], ) original_image = Image.open(input_image_p...
def annotate_image(input_image_path, debug: DebugConfig): ocr_result = ocr_text_detection(input_image_path, debug) components = detect_components( input_image_path, ocr_result, showOCR=debug["ocr"], showUIED=debug["uied"], ) original_image = Image.open(input_image_p...
label_map: LabelMap = {}
3
2023-12-10 17:18:28+00:00
2k
baidubce/app-builder
appbuilder/core/components/embeddings/base.py
[ { "identifier": "Component", "path": "appbuilder/core/component.py", "snippet": "class Component:\n r\"\"\"Component基类, 其它实现的Component子类需要继承该基类,并至少实现run方法.\"\"\"\n\n def __init__(self,\n meta: Optional[ComponentArguments] = ComponentArguments(),\n secret_key: Option...
from abc import abstractmethod from typing import List, Union from appbuilder.core.component import Component from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments
1,120
""" base """ # Copyright (c) 2023 Baidu, Inc. 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 a...
""" base """ # Copyright (c) 2023 Baidu, Inc. 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 a...
meta: ComponentArguments
2
2023-12-05 01:48:12+00:00
2k
corfyi/UCMCTrack
run_mot20_test.py
[ { "identifier": "run_ucmc", "path": "util/run_ucmc.py", "snippet": "def run_ucmc(args, det_path = \"det_results/mot17/yolox_x_ablation\",\n cam_path = \"cam_para/mot17\",\n gmc_path = \"gmc/mot17\",\n out_path = \"output/mot17\",\n ...
from util.run_ucmc import run_ucmc, make_args
1,416
if __name__ == '__main__': det_path = "det_results/mot20" cam_path = "cam_para/mot20" gmc_path = "gmc/mot20" out_path = "output/mot20" exp_name = "test" dataset = "MOT20"
if __name__ == '__main__': det_path = "det_results/mot20" cam_path = "cam_para/mot20" gmc_path = "gmc/mot20" out_path = "output/mot20" exp_name = "test" dataset = "MOT20"
args = make_args()
1
2023-12-12 07:29:20+00:00
2k
ingra14m/Specular-Gaussians
metrics.py
[ { "identifier": "ssim", "path": "utils/loss_utils.py", "snippet": "def ssim(img1, img2, window_size=11, size_average=True):\n channel = img1.size(-3)\n window = create_window(window_size, channel)\n\n if img1.is_cuda:\n window = window.cuda(img1.get_device())\n window = window.type_as...
from pathlib import Path from PIL import Image from utils.loss_utils import ssim from tqdm import tqdm from utils.image_utils import psnr from argparse import ArgumentParser import os import torch import torchvision.transforms.functional as tf import lpips import json
721
# # Copyright (C) 2023, Inria # GRAPHDECO research group, https://team.inria.fr/graphdeco # All rights reserved. # # This software is free for non-commercial, research and evaluation use # under the terms of the LICENSE.md file. # # For inquiries contact george.drettakis@inria.fr # # from lpipsPyTorch import lpips ...
# # Copyright (C) 2023, Inria # GRAPHDECO research group, https://team.inria.fr/graphdeco # All rights reserved. # # This software is free for non-commercial, research and evaluation use # under the terms of the LICENSE.md file. # # For inquiries contact george.drettakis@inria.fr # # from lpipsPyTorch import lpips ...
ssims.append(ssim(renders[idx], gts[idx]))
0
2023-12-12 14:59:01+00:00
2k
u2seg/U2Seg
detectron2/evaluation/evaluator.py
[ { "identifier": "get_world_size", "path": "detectron2/utils/comm.py", "snippet": "def get_world_size() -> int:\n if not dist.is_available():\n return 1\n if not dist.is_initialized():\n return 1\n return dist.get_world_size()" }, { "identifier": "is_main_process", "pat...
import datetime import logging import time import torch from collections import OrderedDict, abc from contextlib import ExitStack, contextmanager from typing import List, Union from torch import nn from detectron2.utils.comm import get_world_size, is_main_process from detectron2.utils.logger import log_every_n_seconds
1,151
# Copyright (c) Facebook, Inc. and its affiliates. class DatasetEvaluator: """ Base class for a dataset evaluator. The function :func:`inference_on_dataset` runs the model over all samples in the dataset, and have a DatasetEvaluator to process the inputs/outputs. This class will accumulate info...
# Copyright (c) Facebook, Inc. and its affiliates. class DatasetEvaluator: """ Base class for a dataset evaluator. The function :func:`inference_on_dataset` runs the model over all samples in the dataset, and have a DatasetEvaluator to process the inputs/outputs. This class will accumulate info...
num_devices = get_world_size()
0
2023-12-05 01:13:31+00:00
2k
upfusion3d/upfusion
control_net/cldm/ddim_hacked.py
[ { "identifier": "make_ddim_sampling_parameters", "path": "control_net/ldm/modules/diffusionmodules/util.py", "snippet": "def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):\n # select alphas for computing the variance schedule\n alphas = alphacums[ddim_timesteps]\n ...
import torch import numpy as np from tqdm import tqdm from control_net.ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like, extract_into_tensor
844
"""SAMPLING ONLY.""" class DDIMSampler(object): def __init__(self, model, schedule="linear", **kwargs): super().__init__() self.model = model self.ddpm_num_timesteps = model.num_timesteps self.schedule = schedule def register_buffer(self, name, attr): if type(attr) =...
"""SAMPLING ONLY.""" class DDIMSampler(object): def __init__(self, model, schedule="linear", **kwargs): super().__init__() self.model = model self.ddpm_num_timesteps = model.num_timesteps self.schedule = schedule def register_buffer(self, name, attr): if type(attr) =...
self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
1
2023-12-12 00:49:11+00:00
2k
modelscope/normal-depth-diffusion
libs/ControlNet-v1-1-nightly/annotator/normalbae/models/baseline.py
[ { "identifier": "UpSampleBN", "path": "libs/ControlNet-v1-1-nightly/annotator/normalbae/models/submodules/submodules.py", "snippet": "class UpSampleBN(nn.Module):\n\n def __init__(self, skip_input, output_features):\n super(UpSampleBN, self).__init__()\n\n self._net = nn.Sequential(\n ...
import torch import torch.nn as nn import torch.nn.functional as F from .submodules.submodules import UpSampleBN, norm_normalize
928
# This is the baseline encoder-decoder we used in the ablation study class NNET(nn.Module): def __init__(self, args=None): super(NNET, self).__init__() self.encoder = Encoder() self.decoder = Decoder(num_classes=4) def forward(self, x, **kwargs): out = self.decoder(self.enco...
# This is the baseline encoder-decoder we used in the ablation study class NNET(nn.Module): def __init__(self, args=None): super(NNET, self).__init__() self.encoder = Encoder() self.decoder = Decoder(num_classes=4) def forward(self, x, **kwargs): out = self.decoder(self.enco...
self.up1 = UpSampleBN(skip_input=2048 + 176, output_features=1024)
0
2023-12-06 07:29:34+00:00
2k
daswer123/xtts-webui
scripts/resemble_enhance/denoiser/inference.py
[ { "identifier": "inference", "path": "scripts/resemble_enhance/inference.py", "snippet": "def inference(model, dwav, sr, device, chunk_seconds: float = 30.0, overlap_seconds: float = 1.0):\n remove_weight_norm_recursively(model)\n\n hp: HParams = model.hp\n\n dwav = resample(\n dwav,\n ...
import logging import torch from functools import cache from ..inference import inference from .train import Denoiser, HParams
664
logger = logging.getLogger(__name__) @cache def load_denoiser(run_dir, device): if run_dir is None:
logger = logging.getLogger(__name__) @cache def load_denoiser(run_dir, device): if run_dir is None:
return Denoiser(HParams())
1
2023-12-14 06:34:12+00:00
2k
FrozenBurning/PrimDiffusion
dva/io.py
[ { "identifier": "AttrDict", "path": "dva/attr_dict.py", "snippet": "class AttrDict:\n def __init__(self, entries):\n self.add_entries_(entries)\n\n def keys(self):\n return self.__dict__.keys()\n\n def values(self):\n return self.__dict__.values()\n\n def __getitem__(sel...
import json import cv2 import numpy as np import copy import importlib import pickle import os from typing import Any, Dict from dva.attr_dict import AttrDict from dva.geom import compute_v2uv, compute_neighbours
1,514
# 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. def load_module(module_name, class_name=None, silent: bool = False): module = importlib.import_module(module_name)...
# 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. def load_module(module_name, class_name=None, silent: bool = False): module = importlib.import_module(module_name)...
topology["v2uv"] = compute_v2uv(
1
2023-12-06 05:12:55+00:00
2k
Nearcyan/papers.day
backend/admin.py
[ { "identifier": "ArxivPaper", "path": "backend/models.py", "snippet": "class ArxivPaper(models.Model):\n created_at = models.DateTimeField(auto_now_add=True)\n modified_at = models.DateTimeField(auto_now=True)\n arxiv_id = models.CharField(max_length=20, unique=True)\n\n # fields scraped fro...
from django.contrib import admin from .models import ArxivPaper, Author, Subject, PaperImage, PaperSource
1,096
class ArxivPaperAdmin(admin.ModelAdmin): list_display = ('title', 'citations', 'total_author_citations', 'summary', 'publication_date', 'arxiv_id', 'created_at') search_fields = ('title', 'abstract', 'arxiv_id') readonly_fields = ('created_at', 'modified_at') ordering = ('-publica...
class ArxivPaperAdmin(admin.ModelAdmin): list_display = ('title', 'citations', 'total_author_citations', 'summary', 'publication_date', 'arxiv_id', 'created_at') search_fields = ('title', 'abstract', 'arxiv_id') readonly_fields = ('created_at', 'modified_at') ordering = ('-publica...
admin.site.register(ArxivPaper, ArxivPaperAdmin)
0
2023-12-14 08:23:05+00:00
2k
LSimon95/megatts2
models/trainer.py
[ { "identifier": "MegaVQ", "path": "models/megatts2.py", "snippet": "class MegaVQ(nn.Module):\n def __init__(\n self,\n mrte: MRTE,\n vqpe: VQProsodyEncoder,\n decoder: ConvNet,\n ):\n super(MegaVQ, self).__init__()\n\n self.mrte = mrte\n ...
import lightning.pytorch as pl import torch import torchaudio import torch.nn.functional as F import transformers import numpy as np import math from .megatts2 import MegaVQ from modules.dscrm import Discriminator from utils.utils import plot_spectrogram_to_numpy
1,002
class MegaGANTrainer(pl.LightningModule): def __init__( self,
class MegaGANTrainer(pl.LightningModule): def __init__( self,
G: MegaVQ,
0
2023-12-10 15:02:54+00:00
2k
wanghao-cst/Omni-VideoAssistant
llava/serve/controller.py
[ { "identifier": "CONTROLLER_HEART_BEAT_EXPIRATION", "path": "llava/constants.py", "snippet": "CONTROLLER_HEART_BEAT_EXPIRATION = 30" }, { "identifier": "build_logger", "path": "llava/utils.py", "snippet": "def build_logger(logger_name, logger_filename):\n def __init__(self, logger, lo...
import argparse import asyncio import dataclasses import json import logging import time import threading import numpy as np import requests import uvicorn from enum import Enum, auto from typing import List, Union from fastapi import FastAPI, Request from fastapi.responses import StreamingResponse from llava.constants...
1,519
if not worker_status: return False self.worker_info[worker_name] = WorkerInfo( worker_status["model_names"], worker_status["speed"], worker_status["queue_length"], check_heart_beat, time.time()) logger.info(f"Register done: {worker_name}, {worker_status}") ...
""" A controller manages distributed workers. It sends worker addresses to clients. """ logger = build_logger("controller", "controller.log") class DispatchMethod(Enum): LOTTERY = auto() SHORTEST_QUEUE = auto() @classmethod def from_str(cls, name): if name == "lottery": return...
"text": server_error_msg,
1
2023-12-05 08:02:17+00:00
2k
RobertCsordas/moe_attention
layers/transformer/transformer.py
[ { "identifier": "MultiHeadAttention", "path": "layers/transformer/multi_head_attention.py", "snippet": "class MultiHeadAttention(AttentionMergeMixin, AbsPosAttentionBase):\n def __init__(self, state_size: int, n_heads: int, dropout: float = 0.1, input_size: Optional[int] = None,\n out...
import torch import torch.nn import torch.nn.functional as F from .multi_head_attention import MultiHeadAttention, AttentionMask from typing import Optional, Callable, Dict, Type, Sequence, Union from dataclasses import dataclass
686
# This file is based on PyTorch's internal implementation ActivationFunction = Callable[[torch.Tensor], torch.Tensor] class TransformerEncoderLayer(torch.nn.Module): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation: ActivationFunction = F.relu, attention_dropout=0...
# This file is based on PyTorch's internal implementation ActivationFunction = Callable[[torch.Tensor], torch.Tensor] class TransformerEncoderLayer(torch.nn.Module): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation: ActivationFunction = F.relu, attention_dropout=0...
def forward(self, src: torch.Tensor, mask: Optional[AttentionMask] = None) -> torch.Tensor:
1
2023-12-13 08:45:02+00:00
2k
riccardomusmeci/mlx-llm
src/mlx_llm/model/_registry.py
[ { "identifier": "phi2", "path": "src/mlx_llm/model/phi2.py", "snippet": "def phi2() -> Phi2:\n return Phi2(\n dim=2560,\n vocab_size=51200,\n n_heads=32,\n n_layers=32,\n rotary_dim=32\n )" }, { "identifier": "llama_2_7B_chat", "path": "src/mlx_llm/mo...
from .phi2 import phi2 from .transformer import ( llama_2_7B_chat, tiny_llama_chat_v06, openhermes_25_mistral_7B, # mistral_7B_instruct_v01, mistral_7B_instruct_v02, e5_mistral_7b_instruct )
756
MODEL_ENTRYPOINTS = { "Phi2": phi2, "LLaMA-2-7B-chat": llama_2_7B_chat, "TinyLlama-1.1B-Chat-v0.6": tiny_llama_chat_v06, # "Mistral-7B-Instruct-v0.1": mistral_7B_instruct_v01,
MODEL_ENTRYPOINTS = { "Phi2": phi2, "LLaMA-2-7B-chat": llama_2_7B_chat, "TinyLlama-1.1B-Chat-v0.6": tiny_llama_chat_v06, # "Mistral-7B-Instruct-v0.1": mistral_7B_instruct_v01,
"Mistral-7B-Instruct-v0.2": mistral_7B_instruct_v02,
4
2023-12-07 16:19:47+00:00
2k
xetdata/xetcache
xetcache/xetmemo_kernel_extension.py
[ { "identifier": "hash_anything", "path": "xetcache/util.py", "snippet": "def hash_anything(x):\n return hashlib.sha256(pickle.dumps(x)).hexdigest()" }, { "identifier": "probe_memo", "path": "xetcache/util.py", "snippet": "def probe_memo(memopath, inputhashstr, key=None):\n \"\"\"\n...
import os import time from .util import hash_anything, probe_memo, store_memo from .config import get_memo_path, get_runtime_threshold from IPython.core.magic import Magics, magics_class, cell_magic
1,389
@magics_class class XMemoMagics(Magics): """Memoization for data science tasks %load_ext xetcache to load the extension """ def __init__(self, *args, **kwargs): print(self.xetmemo.__doc__) memopath = get_memo_path() print(f"Memoizing to {memopath}") super()._...
@magics_class class XMemoMagics(Magics): """Memoization for data science tasks %load_ext xetcache to load the extension """ def __init__(self, *args, **kwargs): print(self.xetmemo.__doc__) memopath = get_memo_path() print(f"Memoizing to {memopath}") super()._...
inputhashes = [hash_anything(line), hash_anything(cell)]
0
2023-12-05 21:59:08+00:00
2k
open-compass/T-Eval
teval/evaluators/planning_evaluator.py
[ { "identifier": "format_load", "path": "teval/utils/format_load.py", "snippet": "def format_load(raw_data: str, start_character: str = '', end_character: str = ''):\n \"\"\"Format the raw data into the format that can be evaluated.\n\n Args:\n raw_data (str): The raw data.\n start_ch...
from collections import defaultdict from numpy import mean from mmengine import load from teval.utils.format_load import format_load from tqdm import tqdm from teval.schema import ResponseDataSample from sentence_transformers import SentenceTransformer, util import json import itertools import networkx as nx import num...
1,293
# import evaluate class PlanningEvaluator: """Planning Evaluation Args: dataset_path(str): File path of evaluation dataset name_weight(float): the weight of action_name in bert_score match, default = 0.9 args_weight(float): the weight of action_args in bert_score match, default = 0.1 ...
# import evaluate class PlanningEvaluator: """Planning Evaluation Args: dataset_path(str): File path of evaluation dataset name_weight(float): the weight of action_name in bert_score match, default = 0.9 args_weight(float): the weight of action_args in bert_score match, default = 0.1 ...
) -> ResponseDataSample:
1
2023-12-10 05:18:46+00:00
2k
rabilrbl/gemini-pro-bot
gemini_pro_bot/handlers.py
[ { "identifier": "model", "path": "gemini_pro_bot/llm.py", "snippet": "SAFETY_SETTINGS = {\n HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE,\n HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,\n HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBl...
import asyncio import PIL.Image as load_image from gemini_pro_bot.llm import model, img_model from google.generativeai.types.generation_types import ( StopCandidateException, BlockedPromptException, ) from telegram import Update from telegram.ext import ( ContextTypes, ) from telegram.error import NetworkEr...
1,017
def new_chat(context: ContextTypes.DEFAULT_TYPE) -> None: context.chat_data["chat"] = model.start_chat() async def start(update: Update, _: ContextTypes.DEFAULT_TYPE) -> None: """Send a message when the command /start is issued.""" user = update.effective_user await update.message.reply_html( ...
def new_chat(context: ContextTypes.DEFAULT_TYPE) -> None: context.chat_data["chat"] = model.start_chat() async def start(update: Update, _: ContextTypes.DEFAULT_TYPE) -> None: """Send a message when the command /start is issued.""" user = update.effective_user await update.message.reply_html( ...
message = format_message(full_plain_message)
1
2023-12-14 16:57:14+00:00
2k
nox-410/tvm.tl
python/tvm/target/x86.py
[ { "identifier": "register_func", "path": "python/tvm/_ffi/registry.py", "snippet": "def register_func(func_name, f=None, override=False):\n \"\"\"Register global function\n\n Parameters\n ----------\n func_name : str or function\n The function name\n\n f : function, optional\n ...
from .._ffi import register_func from .codegen import target_has_features
940
# Licensed to the Apache Software Foundation (ASF) 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 u...
# Licensed to the Apache Software Foundation (ASF) 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 u...
if target_has_features(["avx512bw", "avx512f"]):
1
2023-12-14 02:37:47+00:00
2k
kakaobrain/honeybee
tasks/mme/mme_dataset.py
[ { "identifier": "TaskDataset", "path": "tasks/base_dataset.py", "snippet": "class TaskDataset(Dataset):\n def build_prompt(self, question, image_prompt=\"Human: <image>\"):\n prompt = f\"\"\"{SYSTEM}\n{image_prompt}\nHuman: {question}\nAI: \"\"\"\n return prompt\n\n def collate_fn(se...
from pathlib import Path from PIL import Image from tasks.base_dataset import TaskDataset, Example import utils
763
EVAL_TYPE_DICT = { "Perception": ["existence", "count", "position", "color", "posters", "celebrity", "scene", "landmark", "artwork", "OCR"], "Cognition": ["commonsense_reasoning", "numerical_calculation", "text_translation", "code_reasoning"] } def load_subset(dir_path): root = Path(dir_path) dset_n...
EVAL_TYPE_DICT = { "Perception": ["existence", "count", "position", "color", "posters", "celebrity", "scene", "landmark", "artwork", "OCR"], "Cognition": ["commonsense_reasoning", "numerical_calculation", "text_translation", "code_reasoning"] } def load_subset(dir_path): root = Path(dir_path) dset_n...
ex = Example(index, image, prompt, data)
1
2023-12-06 14:48:41+00:00
2k
NVlabs/RADIO
radio/hf_model.py
[ { "identifier": "eradio", "path": "radio/eradio_model.py", "snippet": "@register_model\ndef eradio(pretrained=False, **kwargs):\n return fastervit2_large_fullres_ws16(pretrained=pretrained, **kwargs)" }, { "identifier": "create_model_from_args", "path": "radio/radio_model.py", "snippe...
from collections import namedtuple from typing import Optional from timm.models import VisionTransformer from transformers import PretrainedConfig, PreTrainedModel from .eradio_model import eradio from .radio_model import create_model_from_args from .radio_model import RADIOModel as RADIOModelBase from .input_condition...
1,421
# Copyright (c) 2023, NVIDIA CORPORATION. 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 appli...
# Copyright (c) 2023, NVIDIA CORPORATION. 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 appli...
model = create_model_from_args(args)
1
2023-12-08 19:53:01+00:00
2k
taikinman/langrila
src/langrila/database/chroma.py
[ { "identifier": "BaseModule", "path": "src/langrila/base.py", "snippet": "class BaseModule(ABC):\n @abstractmethod\n def run(self, *args, **kwargs):\n raise NotImplementedError\n\n async def arun(self, *args, **kwargs):\n raise NotImplementedError\n\n def stream(self, *args, **...
import sys import chromadb from pathlib import Path from typing import Optional from ..base import BaseModule from ..result import RetrievalResult from ..usage import Usage
1,570
python_version = sys.version_info # NOTE : Python version < 3.10 is bundled by lower version sqlite client, so in that case sqlite modules is override # https://docs.trychroma.com/troubleshooting#sqlite __import__("pysqlite3") sys.modules["sqlite3"] = sys.modules.pop("pysqlite3") class ChromaCollectionModule(Base...
python_version = sys.version_info # NOTE : Python version < 3.10 is bundled by lower version sqlite client, so in that case sqlite modules is override # https://docs.trychroma.com/troubleshooting#sqlite __import__("pysqlite3") sys.modules["sqlite3"] = sys.modules.pop("pysqlite3") class ChromaCollectionModule(Base...
usage=Usage(
2
2023-12-10 09:42:35+00:00
2k
Open-All-Scale-Causal-Engine/OpenASCE
openasce/inference/learner/dml_test.py
[ { "identifier": "DML", "path": "openasce/inference/learner/dml.py", "snippet": "class DML(_DML, InferenceModel):\n def fit(\n self,\n *,\n X: Iterable[np.ndarray],\n Y: Iterable[np.ndarray],\n T: Iterable[np.ndarray],\n **kwargs\n ):\n \"\"\"Feed th...
from unittest import TestCase from econml.sklearn_extensions.linear_model import WeightedLassoCVWrapper from sklearn.linear_model import LassoCV from openasce.inference.learner.dml import DML from tests.datasets.ihdp_data import get_ihdp_data from openasce.utils.logger import logger import numpy as np
1,324
# Copyright 2023 AntGroup CO., Ltd. # # 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 ...
# Copyright 2023 AntGroup CO., Ltd. # # 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 ...
logger.info(f"dml result: {avg}")
2
2023-12-06 05:54:36+00:00
2k
latorc/Wechat-AI-Assistant
chatbot.py
[ { "identifier": "WcfWrapper", "path": "wcf_wrapper.py", "snippet": "class WcfWrapper:\r\n def __init__(self) -> None:\r\n def __del__(self):\r\n def msg_preview_str(self, msg:WxMsg) -> str:\r\n def wxid_to_nickname(self, wxid) -> str:\r\n def wxid_to_wxcode(self, wxid) -> str:\r\n def ...
import queue import re import config import common import openai_wrapper import preset from typing import Tuple from wcf_wrapper import WcfWrapper, ContentType from wcferry import WxMsg from config import AdminCmd from common import ContentType, ChatMsg
1,525
class Chatbot(): """ 管理微信机器人逻辑. 管理与微信客户端 (如Wechat Ferry) 和 AI 客户端 (如 OpenAI )的交互逻辑 """ def __init__(self, config: config.Config, wcfw: WcfWrapper, oaiw: openai_wrapper.OpenAIWrapper) -> None: """ 初始化 args: config (Config): Config对象 wcfw (WcfWrapper): Wechat Fer...
class Chatbot(): """ 管理微信机器人逻辑. 管理与微信客户端 (如Wechat Ferry) 和 AI 客户端 (如 OpenAI )的交互逻辑 """ def __init__(self, config: config.Config, wcfw: WcfWrapper, oaiw: openai_wrapper.OpenAIWrapper) -> None: """ 初始化 args: config (Config): Config对象 wcfw (WcfWrapper): Wechat Fer...
def callback_msg(msg:ChatMsg) -> int:
3
2023-12-07 12:17:15+00:00
2k
tensorsense/faceflow
params/datamodule.py
[ { "identifier": "LocalNaturalDatasetCfg", "path": "lib/data/cfg/local.py", "snippet": "class LocalNaturalDatasetCfg:\n name: str\n root: str\n labels_filename: str = \"au.csv\"\n crops_dir: str = \"crops\"\n aus: List[str] = field(\n default_factory=lambda: [\n \"AU1\",\...
import albumentations as A import wandb from albumentations.pytorch import ToTensorV2 from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from lib.data.cfg.local import LocalNaturalDatasetCfg from lib.data.datamodules.vanilla import AUDataModule
1,019
project = "disfa" aus = [ "AU1", "AU2", "AU4", "AU5", "AU6", "AU9", "AU12", "AU15", "AU17", "AU20", "AU26", ] TRAIN_LABELED = [
project = "disfa" aus = [ "AU1", "AU2", "AU4", "AU5", "AU6", "AU9", "AU12", "AU15", "AU17", "AU20", "AU26", ] TRAIN_LABELED = [
LocalNaturalDatasetCfg(
0
2023-12-05 13:15:58+00:00
2k
Psivant/femto
femto/fe/atm/_setup.py
[ { "identifier": "OpenMMForceGroup", "path": "femto/md/constants.py", "snippet": "class OpenMMForceGroup(enum.IntEnum):\n \"\"\"Standard force groups to assign to common OpenMM forces to make them easier to\n identify.\"\"\"\n\n BOND = 0\n ANGLE = 1\n DIHEDRAL = 2\n\n NONBONDED = 3\n\n ...
import logging import tempfile import typing import numpy import openmm import openmm.app import openmm.unit import parmed import scipy.spatial.distance import femto.fe.reference import femto.md.rest import femto.md.restraints import femto.md.solvate import femto.md.system import femto.md.utils.openmm import femto....
1,395
_LOGGER = logging.getLogger(__name__) def select_displacement( receptor: parmed.amber.AmberParm, ligand_1: parmed.amber.AmberParm, ligand_2: parmed.amber.AmberParm | None, distance: openmm.unit.Quantity, ) -> openmm.unit.Quantity: """Attempts to automatically select a displacement vector for the ...
"""Set up the system for ATM calculations.""" if typing.TYPE_CHECKING: _LOGGER = logging.getLogger(__name__) def select_displacement( receptor: parmed.amber.AmberParm, ligand_1: parmed.amber.AmberParm, ligand_2: parmed.amber.AmberParm | None, distance: openmm.unit.Quantity, ) -> openmm.unit.Quanti...
com_restraint.setName(OpenMMForceName.COM_RESTRAINT)
1
2023-12-07 15:28:18+00:00
2k
AIFSH/NativeDancer
nativedancer/third_part/detectron2/evaluation/cityscapes_evaluation.py
[ { "identifier": "MetadataCatalog", "path": "nativedancer/third_part/detectron2/data/catalog.py", "snippet": "class _DatasetCatalog(UserDict):\nclass Metadata(types.SimpleNamespace):\nclass _MetadataCatalog(UserDict):\n def register(self, name, func):\n def get(self, name):\n def list(self) -> L...
import glob import logging import numpy as np import os import tempfile import torch import cityscapesscripts.evaluation.evalInstanceLevelSemanticLabeling as cityscapes_eval import cityscapesscripts.evaluation.evalPixelLevelSemanticLabeling as cityscapes_eval from collections import OrderedDict from PIL...
1,295
# Copyright (c) Facebook, Inc. and its affiliates. class CityscapesEvaluator(DatasetEvaluator): """ Base class for evaluation using cityscapes API. """ def __init__(self, dataset_name): """ Args: dataset_name (str): the name of the dataset. It must have t...
# Copyright (c) Facebook, Inc. and its affiliates. class CityscapesEvaluator(DatasetEvaluator): """ Base class for evaluation using cityscapes API. """ def __init__(self, dataset_name): """ Args: dataset_name (str): the name of the dataset. It must have t...
comm.get_local_size() == comm.get_world_size()
1
2023-12-10 20:14:00+00:00
2k
ethanweber/nerfiller
nerfiller/inpaint/saicinpainting/training/modules/base.py
[ { "identifier": "DepthWiseSeperableConv", "path": "nerfiller/inpaint/saicinpainting/training/modules/depthwise_sep_conv.py", "snippet": "class DepthWiseSeperableConv(nn.Module):\n def __init__(self, in_dim, out_dim, *args, **kwargs):\n super().__init__()\n if \"groups\" in kwargs:\n ...
import abc import torch import torch.nn as nn from typing import Tuple, List from nerfiller.inpaint.saicinpainting.training.modules.depthwise_sep_conv import ( DepthWiseSeperableConv, ) from nerfiller.inpaint.saicinpainting.training.modules.multidilated_conv import ( MultidilatedConv, )
1,459
class BaseDiscriminator(nn.Module): @abc.abstractmethod def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, List[torch.Tensor]]: """ Predict scores and get intermediate activations. Useful for feature matching loss :return tuple (scores, list of intermediate activations) ...
class BaseDiscriminator(nn.Module): @abc.abstractmethod def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, List[torch.Tensor]]: """ Predict scores and get intermediate activations. Useful for feature matching loss :return tuple (scores, list of intermediate activations) ...
return MultidilatedConv
1
2023-12-07 19:12:08+00:00
2k
nnanhuang/Customize-it-3D
ldm/models/diffusion/plms.py
[ { "identifier": "make_ddim_sampling_parameters", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):\n # select alphas for computing the variance schedule\n alphas = alphacums[ddim_timesteps]\n alphas_prev ...
import torch import numpy as np from tqdm import tqdm from functools import partial from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like from ldm.models.diffusion.sampling_util import norm_thresholding
868
"""SAMPLING ONLY.""" class PLMSSampler(object): def __init__(self, model, schedule="linear", **kwargs): super().__init__() self.model = model self.ddpm_num_timesteps = model.num_timesteps self.schedule = schedule def register_buffer(self, name, attr): if type(attr) =...
"""SAMPLING ONLY.""" class PLMSSampler(object): def __init__(self, model, schedule="linear", **kwargs): super().__init__() self.model = model self.ddpm_num_timesteps = model.num_timesteps self.schedule = schedule def register_buffer(self, name, attr): if type(attr) =...
self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
1
2023-12-14 11:03:35+00:00
2k
TaoHuang13/diffusion_reward
diffusion_reward/models/codec_models/vqgan/vqgan.py
[ { "identifier": "Codebook", "path": "diffusion_reward/models/codec_models/vqgan/codebook.py", "snippet": "class Codebook(nn.Module):\n def __init__(self, args):\n super(Codebook, self).__init__()\n self.num_codebook_vectors = args.num_codebook_vectors\n self.latent_dim = args.lat...
import torch import torch.nn as nn from .codebook import Codebook from .decoder import Decoder from .encoder import Encoder
1,162
class VQGAN(nn.Module): def __init__(self, args): super(VQGAN, self).__init__() self.encoder = Encoder(args).to(device=args.device)
class VQGAN(nn.Module): def __init__(self, args): super(VQGAN, self).__init__() self.encoder = Encoder(args).to(device=args.device)
self.decoder = Decoder(args).to(device=args.device)
1
2023-12-05 02:42:28+00:00
2k
its0x4d/fastapi-jet
fastapi_jet/commands/startproject.py
[ { "identifier": "app", "path": "fastapi_jet/cli.py", "snippet": "def _version_callback(value: bool) -> None:\ndef _register_commands() -> None:\ndef main(\n version: Optional[bool] = typer.Option(\n None,\n \"--version\",\n \"-v\",\n help=\"Show the app...
import os import typer from questionary.form import form from fastapi_jet.cli import app from fastapi_jet.context import ProjectContext from fastapi_jet.generator import generate_template from fastapi_jet.utils import binary_question, name_fixer
1,211
@app.command(name="startproject") def startproject( name: str = typer.Argument( ..., help="Name of the project", callback=lambda name: name_fixer(name), metavar="PROJECT_NAME" ), interactive: bool = typer.Option(False, "--interactive", "-i", help="Interact...
@app.command(name="startproject") def startproject( name: str = typer.Argument( ..., help="Name of the project", callback=lambda name: name_fixer(name), metavar="PROJECT_NAME" ), interactive: bool = typer.Option(False, "--interactive", "-i", help="Interact...
use_templates=binary_question("Do you want to use templates?", default=True),
3
2023-12-12 00:15:53+00:00
2k
WithSecureLabs/damn-vulnerable-llm-agent
main.py
[ { "identifier": "get_current_user_tool", "path": "tools.py", "snippet": "def get_current_user(input : str):\ndef get_transactions(userId : str):" }, { "identifier": "display_instructions", "path": "utils.py", "snippet": "def display_instructions():\n # Markdown with some basic CSS sty...
import langchain import streamlit as st from dotenv import load_dotenv from langchain.agents import ConversationalChatAgent, AgentExecutor from langchain.callbacks import StreamlitCallbackHandler from langchain.chat_models import ChatOpenAI from langchain.memory import ConversationBufferMemory from langchain.memory.cha...
1,244
load_dotenv() # Initialise tools tools = [get_current_user_tool, get_recent_transactions_tool] system_msg = """Assistant helps the current user retrieve the list of their recent bank transactions ans shows them as a table. Assistant will ONLY operate on the userId returned by the GetCurrentUser() tool, and REFUSE t...
load_dotenv() # Initialise tools tools = [get_current_user_tool, get_recent_transactions_tool] system_msg = """Assistant helps the current user retrieve the list of their recent bank transactions ans shows them as a table. Assistant will ONLY operate on the userId returned by the GetCurrentUser() tool, and REFUSE t...
display_logo()
2
2023-12-07 09:37:47+00:00
2k
MarcoGorelli/polars-upgrade
polars_upgrade/_plugins/map_dict.py
[ { "identifier": "ast_to_offset", "path": "polars_upgrade/_ast_helpers.py", "snippet": "def ast_to_offset(node: ast.expr | ast.stmt) -> Offset:\n return Offset(node.lineno, node.col_offset)" }, { "identifier": "register", "path": "polars_upgrade/_data.py", "snippet": "def register(tp: ...
import ast import functools from typing import Iterable from tokenize_rt import NON_CODING_TOKENS from tokenize_rt import Offset from tokenize_rt import Token from polars_upgrade._ast_helpers import ast_to_offset from polars_upgrade._data import register from polars_upgrade._data import State from polars_upgrade._data ...
1,010
from __future__ import annotations def rename( i: int, tokens: list[Token], *, name: str, new: str, ) -> None: while not (tokens[i].name == 'NAME' and tokens[i].src == name): i += 1 tokens[i] = tokens[i]._replace(src=new) def rename_and_add_default( i: int, tokens: lis...
from __future__ import annotations def rename( i: int, tokens: list[Token], *, name: str, new: str, ) -> None: while not (tokens[i].name == 'NAME' and tokens[i].src == name): i += 1 tokens[i] = tokens[i]._replace(src=new) def rename_and_add_default( i: int, tokens: lis...
is_simple_expression(node.func.value, state.aliases) and
5
2023-12-09 19:31:35+00:00
2k
I-am-PUID-0/pd_zurg
main.py
[ { "identifier": "rclone", "path": "rclone_rd/rclone.py", "snippet": "def get_port_from_config(config_file_path, key_type):\ndef setup():\n RCLONEMN_RD = f\"{RCLONEMN}_RD\"\n RCLONEMN_AD = f\"{RCLONEMN}_AD\"\n RCLONEMN_RD = RCLONEMN_AD = RCLONEMN" }, { "identifier...
from base import * from rclone_rd import rclone from cleanup import duplicate_cleanup from update import auto_update import plex_debrid_ as p import zurg as z
720
def main(): logger = get_logger() version = '2.0.1' ascii_art = f''' _______ ______ _______ _______ _______ ( ____ )( __ \ / ___ )|\ /|( ____ )( ____ \\ | ( )|| ( \ ) \/ ) || ) ( ||...
def main(): logger = get_logger() version = '2.0.1' ascii_art = f''' _______ ______ _______ _______ _______ ( ____ )( __ \ / ___ )|\ /|( ____ )( ____ \\ | ( )|| ( \ ) \/ ) || ) ( ||...
z_updater.auto_update('Zurg',True)
2
2023-12-05 14:49:38+00:00
2k
JeffersonQin/DungeonAssistant
registration.py
[ { "identifier": "o3dobj", "path": "utils/o3dobj.py", "snippet": "def get_o3d_unit_block_at_origin():\ndef get_o3d_trajectory_object(points, color=(1, 0, 0)):\n def transform_o3d_format(points):" }, { "identifier": "io", "path": "utils/io.py", "snippet": "def load_point_clouds(\n po...
import json import argparse import os import os.path as osp import time import open3d as o3d import numpy as np import copy import matplotlib.pyplot as plt from utils import o3dobj from utils import io from utils import tfm
1,505
default=0.05, help="voxel size for global fast registration downsampling. default is 0.05", ) parser.add_argument( "--voxel_size_icp", type=float, default=0.05, help="voxel size for icp downsampling. default is 0.05", ) parser.add_argument("--skip_icp", action="store_true", help="skip icp and on...
parser = argparse.ArgumentParser() parser.add_argument( "--pointcloud1", type=str, default="pointcloud1.ply", help="first point cloud file path (1 --[transform]-> 2)", ) parser.add_argument( "--pointcloud2", type=str, default="pointcloud2.ply", help="second point cloud file path (1 --...
unit_block = o3dobj.get_o3d_unit_block_at_origin()
0
2023-12-08 19:52:08+00:00
2k
KAIST-VICLab/From_Ground_To_Objects
networks/depth_decoder.py
[ { "identifier": "ConvBlock", "path": "networks/layers.py", "snippet": "class ConvBlock(nn.Module):\r\n \"\"\"Layer to perform a convolution followed by ELU\r\n \"\"\"\r\n\r\n def __init__(self, in_channels, out_channels):\r\n super(ConvBlock, self).__init__()\r\n\r\n self.conv = C...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict from .layers import ConvBlock, Conv3x3, upsample, disp_to_depth, coords_to_normals from timm.models.layers import trunc_normal_ from .cadepth import SPM, DEM
1,539
# Copyright Niantic 2021. Patent Pending. All rights reserved. # # This software is licensed under the terms of the ManyDepth licence # which allows for non-commercial use only, the full terms of which are made # available in the LICENSE file. class DepthDecoder(nn.Module): def __init__(self, num_ch_enc, scales...
# Copyright Niantic 2021. Patent Pending. All rights reserved. # # This software is licensed under the terms of the ManyDepth licence # which allows for non-commercial use only, the full terms of which are made # available in the LICENSE file. class DepthDecoder(nn.Module): def __init__(self, num_ch_enc, scales...
self.convs[("dispconv", s)] = Conv3x3(self.num_ch_dec[s], self.num_output_channels)
1
2023-12-12 08:29:30+00:00
2k
marc-rigter/polygrad-world-models
polygrad/agent/a2c.py
[ { "identifier": "EMA", "path": "polygrad/utils/training.py", "snippet": "class EMA():\n '''\n empirical moving average\n '''\n def __init__(self, beta):\n super().__init__()\n self.beta = beta\n\n def update_model_average(self, ma_model, current_model):\n for curr...
import torch import copy import torch.nn as nn import copy import torch.nn.functional as F import torch.distributions as D import importlib import wandb from torch import Tensor from polygrad.utils.training import EMA from .functions import * from .common import * from polygrad.utils.evaluation import get_standardized_...
1,009
class ActorCritic(nn.Module): def __init__(self, in_dim, out_actions, normalizer, device="cuda:0", hidden_dim=256, min_std=0.01, fixed_std=False, decay_std_steps=500000, ...
class ActorCritic(nn.Module): def __init__(self, in_dim, out_actions, normalizer, device="cuda:0", hidden_dim=256, min_std=0.01, fixed_std=False, decay_std_steps=500000, ...
self.ema = EMA(ema)
0
2023-12-12 21:05:26+00:00
2k
Chat-3D/Chat-3D-v2
utils/logger.py
[ { "identifier": "get_rank", "path": "utils/distributed.py", "snippet": "def get_rank():\n if not is_dist_avail_and_initialized():\n return 0\n return dist.get_rank()" }, { "identifier": "is_main_process", "path": "utils/distributed.py", "snippet": "def is_main_process():\n ...
import functools import logging import os import sys import time import wandb import torch from typing import Any, Dict, Union from .distributed import get_rank, is_main_process from termcolor import colored from torch.utils.tensorboard import SummaryWriter
831
# from MMF: https://github.com/facebookresearch/mmf/blob/master/mmf/utils/logger.py # Copyright (c) Facebook, Inc. and its affiliates. def log_dict_to_wandb(log_dict, step, prefix=""): """include a separator `/` at the end of `prefix`""" if not is_main_process(): return log_dict = {f"{prefix}{k...
# from MMF: https://github.com/facebookresearch/mmf/blob/master/mmf/utils/logger.py # Copyright (c) Facebook, Inc. and its affiliates. def log_dict_to_wandb(log_dict, step, prefix=""): """include a separator `/` at the end of `prefix`""" if not is_main_process(): return log_dict = {f"{prefix}{k...
distributed_rank = get_rank()
0
2023-12-11 14:39:58+00:00
2k
SqueezeBits/owlite
owlite/calib/mse_calibrator.py
[ { "identifier": "log", "path": "owlite/logger.py", "snippet": "class Logger(logging.Logger):\n class _WarningFilterContext:\n class WarningFilter(logging.Filter):\n ENV_VAR = \"OWLITE_LOG_LEVEL\"\n DEBUG_WARNING = 15\n ULTRA_VERBOSE = -10\n def ignore_warnings(self):\n ...
import torch from ..logger import log from ._histogram_calibrator import _HistogramCalibrator
1,461
"""MSE(Mean Squared Error) calibrator""" class MSECalibrator(_HistogramCalibrator): """MSE Calibrator Class""" def update(self): # update step_size using "mse" if self.quantizer.histogram is None or self.quantizer.bin_edges is None:
"""MSE(Mean Squared Error) calibrator""" class MSECalibrator(_HistogramCalibrator): """MSE Calibrator Class""" def update(self): # update step_size using "mse" if self.quantizer.histogram is None or self.quantizer.bin_edges is None:
log.error(f"quantizer.histogram : {self.quantizer.histogram}")
0
2023-12-08 06:41:50+00:00
2k
ximinng/PyTorch-SVGRender
pytorch_svgrender/svgtools/process.py
[ { "identifier": "circle_tag", "path": "pytorch_svgrender/svgtools/shape.py", "snippet": "def circle_tag(cx: float, cy: float, r: float, transform: str = None):\n attrib = {\n 'cx': f'{cx}', 'cy': f'{cy}', 'r': f'{r}'\n }\n if transform is not None:\n attrib['transform'] = transfor...
import xml.etree.ElementTree as ET import omegaconf from typing import Tuple from .shape import circle_tag, rect_tag from .type import is_valid_svg
768
# -*- coding: utf-8 -*- # Author: ximing # Description: process # Copyright (c) 2023, XiMing Xing. # License: MIT License def delete_empty_path(input_svg: str, output_svg: str): is_valid_svg(input_svg) # read svg tree = ET.parse(input_svg) root = tree.getroot() group = ET.Element('g') for ...
# -*- coding: utf-8 -*- # Author: ximing # Description: process # Copyright (c) 2023, XiMing Xing. # License: MIT License def delete_empty_path(input_svg: str, output_svg: str): is_valid_svg(input_svg) # read svg tree = ET.parse(input_svg) root = tree.getroot() group = ET.Element('g') for ...
circle_tag(cx=attrs.cx, cy=attrs.cy, r=attrs.r)
0
2023-12-13 08:18:01+00:00
2k
lyhisme/DeST
libs/models/SP.py
[ { "identifier": "Graph", "path": "libs/models/graph/graph.py", "snippet": "class Graph:\n def __init__(self, labeling_mode='spatial', layout='MCFS-22'):\n\n self.get_edge(layout)\n self.A = self.get_adjacency_matrix(labeling_mode)\n\n def get_edge(self, layout):\n if layout ==...
import torch import torch.nn as nn import numpy as np from .graph.graph import Graph from .graph.tools import k_adjacency, normalize_adjacency_matrix, get_adjacency_matrix
1,214
class MultiScale_GraphConv(nn.Module): def __init__(self, num_scales, # 13 in_channels, out_channels, dataset, disentangled_agg=True, use_mask=True, dropout=0, activation='relu...
class MultiScale_GraphConv(nn.Module): def __init__(self, num_scales, # 13 in_channels, out_channels, dataset, disentangled_agg=True, use_mask=True, dropout=0, activation='relu...
self.graph = Graph(labeling_mode='spatial', layout=dataset)
0
2023-12-12 02:27:15+00:00
2k
soCzech/GenHowTo
genhowto.py
[ { "identifier": "load_genhowto_model", "path": "genhowto_utils.py", "snippet": "def load_genhowto_model(weights_path, device=\"cpu\"):\n with open(os.path.join(weights_path, \"GenHowTo_controlnet_config.json\")) as file:\n gef_controlnet_config = json.load(file)\n\n controlnet = ControlNetM...
import os import math import torch import argparse import numpy as np from PIL import Image from genhowto_utils import load_genhowto_model, DDIMSkipScheduler
1,103
def main(args): if os.path.exists(args.output_path): print(f"{args.output_path} already exists.") return pipe = load_genhowto_model(args.weights_path, device=args.device) pipe.scheduler.set_timesteps(args.num_inference_steps) if args.num_steps_to_skip is not None: # possibly do not...
def main(args): if os.path.exists(args.output_path): print(f"{args.output_path} already exists.") return pipe = load_genhowto_model(args.weights_path, device=args.device) pipe.scheduler.set_timesteps(args.num_inference_steps) if args.num_steps_to_skip is not None: # possibly do not...
pipe.scheduler = DDIMSkipScheduler.from_config(pipe.scheduler.config)
1
2023-12-11 08:47:51+00:00
2k
bolna-ai/bolna
bolna/helpers/utils.py
[ { "identifier": "configure_logger", "path": "bolna/helpers/logger_config.py", "snippet": "def configure_logger(file_name, enabled=True, logging_level='INFO'):\n if logging_level not in VALID_LOGGING_LEVELS:\n logging_level = \"INFO\"\n\n logging.basicConfig(\n level=logging_level,\n ...
import json import asyncio import re import numpy as np import copy import hashlib import os import traceback import ast from botocore.exceptions import BotoCoreError, ClientError from aiobotocore.session import AioSession from contextlib import AsyncExitStack from dotenv import load_dotenv from pydantic import BaseMod...
1,049
logger = configure_logger(__name__) load_dotenv() BUCKET_NAME = os.getenv('BUCKET_NAME') def load_file(file_path, is_json=False): data = None with open(file_path, "r") as f: if is_json: data = json.load(f) else: data = f.read() return data def write_json_file(f...
logger = configure_logger(__name__) load_dotenv() BUCKET_NAME = os.getenv('BUCKET_NAME') def load_file(file_path, is_json=False): data = None with open(file_path, "r") as f: if is_json: data = json.load(f) else: data = f.read() return data def write_json_file(f...
file_name = f"{PREPROCESS_DIR}/{agent_name}/{audio_format}/{b64_string}.{audio_format}"
1
2023-12-13 09:07:35+00:00
2k
relari-ai/continuous-eval
continuous_eval/metrics/generation_LLM_based_metrics.py
[ { "identifier": "DefaultLLM", "path": "continuous_eval/llm_factory.py", "snippet": " GOOGLE_GENAI_AVAILABLE = True\n GOOGLE_GENAI_AVAILABLE = False\n ANTHROPIC_AVAILABLE = True\n ANTHROPIC_AVAILABLE = False\nclass LLMInterface(ABC):\nclass LLMFactory(LLMInterface):\n def run(self, prompt,...
from continuous_eval.llm_factory import DefaultLLM, LLMInterface from continuous_eval.metrics.base import LLMBasedMetric from continuous_eval.metrics.retrieval_LLM_based_metrics import LLMBasedContextCoverage
1,293
class LLMBasedFaithfulness(LLMBasedMetric): """ The LLM based faithfulness metric. Measures whether the generated answer is faithful to the retrieved context. """ def __init__( self, model: LLMInterface = DefaultLLM, use_few_shot: bool = True, classify_by_statement...
class LLMBasedFaithfulness(LLMBasedMetric): """ The LLM based faithfulness metric. Measures whether the generated answer is faithful to the retrieved context. """ def __init__( self, model: LLMInterface = DefaultLLM, use_few_shot: bool = True, classify_by_statement...
context_coverage = LLMBasedContextCoverage(use_few_shot=self.use_few_shot)
2
2023-12-08 21:30:39+00:00
2k
ryanhe312/STSSNet-AAAI2024
eval.py
[ { "identifier": "matlab_metric", "path": "utils/matlab_metric.py", "snippet": "def rgb2ycbcr(img, only_y=True):\ndef calc_metrics(img1, img2, crop_border, test_Y=True, norm=False, mask=None):\ndef calc_metrics_y(img1, img2, crop_border, test_Y=True):\ndef calc_psnr(img1, img2, mask=None):\ndef ssim(img1...
import os import cv2 import lpips import torch import numpy as np import torch.nn.functional as F import torch.utils.data as data import matplotlib.pyplot as plt from tqdm import tqdm from utils import matlab_metric, metrics from dataloaders import * from model import STSSNet
1,184
def ImgWrite(mPath,prefix,idx,img): cv2.imwrite(os.path.join(mPath,prefix+"."+str(idx).zfill(4)+".png"),img) @torch.no_grad() def save_res(dataLoaderIns, model, modelPath, save_dir, save_img=True, mode='all'): if not os.path.exists(save_dir): os.makedirs(save_dir) if modelPath.endswith(".tar"):...
def ImgWrite(mPath,prefix,idx,img): cv2.imwrite(os.path.join(mPath,prefix+"."+str(idx).zfill(4)+".png"),img) @torch.no_grad() def save_res(dataLoaderIns, model, modelPath, save_dir, save_img=True, mode='all'): if not os.path.exists(save_dir): os.makedirs(save_dir) if modelPath.endswith(".tar"):...
psnr, ssim = matlab_metric.calc_metrics(res[0].permute(1,2,0).detach().cpu().numpy(), label[0].permute(1,2,0).detach().cpu().numpy(), 0, norm=True, mask=mask)
0
2023-12-10 02:02:37+00:00
2k
Seunggu0305/VLCounter
tools/models/ViT_Encoder_add.py
[ { "identifier": "LayerNorm", "path": "tools/models/Encoder_utils.py", "snippet": "class LayerNorm(nn.LayerNorm):\n \"\"\"Subclass torch's LayerNorm to handle fp16.\"\"\"\n\n def forward(self, x: torch.Tensor):\n orig_type = x.dtype\n ret = super().forward(x.type(torch.float32))\n ...
import torch import torch.nn.functional as F import math from torch.nn import Dropout from torch import nn from functools import reduce from operator import mul from .Encoder_utils import LayerNorm, Transformer, Attention
1,124
class SPTCLIPVisionTransformer(nn.Module): def __init__(self, input_resolution=384, patch_size=16, width=768, layers=12, heads=12, output_dim=512, drop_path_rate=0.1, out_indices=[5,6,7,8,11], pretrained=None, get_embeddings=True, num_tokens=10, prompt_dim=768, total_d_layer=11, **kwargs): ...
class SPTCLIPVisionTransformer(nn.Module): def __init__(self, input_resolution=384, patch_size=16, width=768, layers=12, heads=12, output_dim=512, drop_path_rate=0.1, out_indices=[5,6,7,8,11], pretrained=None, get_embeddings=True, num_tokens=10, prompt_dim=768, total_d_layer=11, **kwargs): ...
self.ln_pre = LayerNorm(width)
0
2023-12-13 08:00:28+00:00
2k
qitan/devops-backend-lite
apps/workflow/serializers.py
[ { "identifier": "Product", "path": "dbapp/models.py", "snippet": "" }, { "identifier": "RecursiveField", "path": "common/recursive.py", "snippet": "class RecursiveField(Field):\n \"\"\"\n A field that gets its representation from its parent.\n\n This method could be used to seri...
from rest_framework import serializers from dbapp.models import Product, Project from common.recursive import RecursiveField from dbapp.models import UserProfile from dbapp.models import WorkflowCategory, Workflow, WorkflowNodeHistory, WorkflowTemplate, \ WorkflowTemplateRevisionHistory, WorkflowNodeHistoryCallback...
1,600
""" @Author : Ken Chen @Contact : 316084217@qq.com @Time : 2021/11/2 上午9:50 """ logger = logging.getLogger(__name__) class WorkflowTemplateSerializer(ModelSerializer): projects_info = serializers.SerializerMethodField() env_info = serializers.SerializerMethodField() def get_env_info(self, instance): ...
""" @Author : Ken Chen @Contact : 316084217@qq.com @Time : 2021/11/2 上午9:50 """ logger = logging.getLogger(__name__) class WorkflowTemplateSerializer(ModelSerializer): projects_info = serializers.SerializerMethodField() env_info = serializers.SerializerMethodField() def get_env_info(self, instance): ...
model = WorkflowTemplateRevisionHistory
3
2023-12-13 03:09:32+00:00
2k
timo-reymann/python-oauth2-cli-auth
oauth2_cli_auth/simplified_flow.py
[ { "identifier": "OAuthCallbackHttpServer", "path": "oauth2_cli_auth/http_server.py", "snippet": "class OAuthCallbackHttpServer(HTTPServer):\n \"\"\"\n Simplistic HTTP Server to provide local callback URL for oauth2 provider\n \"\"\"\n\n def __init__(self, port):\n super().__init__((\"...
from oauth2_cli_auth import OAuthCallbackHttpServer, get_auth_url, exchange_code_for_access_token, OAuth2ClientInfo, \ open_browser
1,227
def get_access_token_with_browser_open(client_info: OAuth2ClientInfo, server_port: int = 8080) -> str: """ Provides a simplified API to: - Spin up the callback server - Open the browser with the authorization URL - Wait for the code to arrive - Get access token from code :param client_inf...
def get_access_token_with_browser_open(client_info: OAuth2ClientInfo, server_port: int = 8080) -> str: """ Provides a simplified API to: - Spin up the callback server - Open the browser with the authorization URL - Wait for the code to arrive - Get access token from code :param client_inf...
open_browser(auth_url)
4
2023-12-09 12:14:33+00:00
2k
solanav/phishflood
phishflood/__main__.py
[ { "identifier": "extract_inputs", "path": "credfind/utils.py", "snippet": "def extract_inputs(html: str) -> InputList:\n \"\"\"Given an HTML page, returns a list of inputs or None if nothing was found\"\"\"\n soup = BeautifulSoup(html, \"html.parser\")\n\n print(\"Finding all forms in the page\...
import json import os import sys import time import requests from hashlib import sha256 from typing import Any, Dict, List, Optional, Tuple from credfind.utils import extract_inputs from credfind.objects import Input, InputList, InputType from playwright.sync_api import sync_playwright, TimeoutError, Page from credgen....
1,591
SCREENSHOT_I = 0 Actions = List[Dict[str, Any]] def screenshot(page: Page): global SCREENSHOT_I SCREENSHOT_I += 1 page.screenshot(path=f"samples/{SCREENSHOT_I}.png") def hash_inputs(inputs: List[Input]) -> str: """Returns a unique string identifying the inputs in the website""" return sha256("...
SCREENSHOT_I = 0 Actions = List[Dict[str, Any]] def screenshot(page: Page): global SCREENSHOT_I SCREENSHOT_I += 1 page.screenshot(path=f"samples/{SCREENSHOT_I}.png") def hash_inputs(inputs: List[Input]) -> str: """Returns a unique string identifying the inputs in the website""" return sha256("...
text = creds_from_input(inp)
2
2023-12-11 16:38:36+00:00
2k
abing7k/redroid-script
stuffs/ndk.py
[ { "identifier": "General", "path": "stuffs/general.py", "snippet": "class General:\n def download(self):\n loc_md5 = \"\"\n if os.path.isfile(self.dl_file_name):\n with open(self.dl_file_name,\"rb\") as f:\n bytes = f.read()\n loc_md5 = hashlib.m...
import os import shutil from stuffs.general import General from tools.helper import bcolors, get_download_dir, print_color, run
845
class Ndk(General): download_loc = get_download_dir() copy_dir = "./ndk" dl_link = "https://github.com/supremegamers/vendor_google_proprietary_ndk_translation-prebuilt/archive/181d9290a69309511185c4417ba3d890b3caaaa8.zip" dl_file_name = os.path.join(download_loc, "libndktranslation.zip") extract_to...
class Ndk(General): download_loc = get_download_dir() copy_dir = "./ndk" dl_link = "https://github.com/supremegamers/vendor_google_proprietary_ndk_translation-prebuilt/archive/181d9290a69309511185c4417ba3d890b3caaaa8.zip" dl_file_name = os.path.join(download_loc, "libndktranslation.zip") extract_to...
print_color("Downloading libndk now .....", bcolors.GREEN)
3
2023-12-06 09:03:05+00:00
2k
zvict/papr
dataset/dataset.py
[ { "identifier": "load_meta_data", "path": "dataset/utils.py", "snippet": "def load_meta_data(args, mode=\"train\"):\n \"\"\"\n 0 -----------> W\n |\n |\n |\n ⬇\n H\n [H, W, 4]\n \"\"\"\n image_paths = None\n\n if args.type == \"synthetic\":\n images, poses, hwf, i...
import torch import numpy as np import imageio from torch.utils.data import Dataset from PIL import Image from .utils import load_meta_data, get_rays, extract_patches
1,572
class RINDataset(Dataset): """ Ray Image Normal Dataset """ def __init__(self, args, mode='train'): self.args = args
class RINDataset(Dataset): """ Ray Image Normal Dataset """ def __init__(self, args, mode='train'): self.args = args
images, c2w, H, W, focal_x, focal_y, image_paths = load_meta_data(
0
2023-12-08 19:51:42+00:00
2k
rinnakk/nue-asr
nue_asr/cli.py
[ { "identifier": "transcribe", "path": "nue_asr/transcribe.py", "snippet": "@torch.inference_mode()\ndef transcribe(\n model: NueASRModel,\n tokenizer: PreTrainedTokenizer,\n audio: Union[str, np.ndarray, torch.Tensor],\n **decode_options,\n) -> ASRResult:\n device = model.device\n sr =...
import argparse import os import torch from .transcribe import transcribe from .utils import load_model, load_tokenizer, set_seed, str2bool
1,542
#!/usr/bin/env python3 # Copyright 2023 rinna Co., Ltd. # # 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 la...
#!/usr/bin/env python3 # Copyright 2023 rinna Co., Ltd. # # 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 la...
"--fp16", type=str2bool, default=True, help="Whether to fp16 inference."
4
2023-12-07 01:37:23+00:00
2k
AdaCheng/EgoThink
models/instruct_blip/processors/blip_processors.py
[ { "identifier": "registry", "path": "models/instruct_blip/common/registry.py", "snippet": "class Registry:\n def register_model(cls, name):\n def wrap(model_cls):\n def register_processor(cls, name):\n def wrap(processor_cls):\n def register_lr_scheduler(cls, name):\n def w...
import re from ..common.registry import registry from .base_processor import BaseProcessor from .randaugment import RandomAugment from omegaconf import OmegaConf from torchvision import transforms from torchvision.transforms.functional import InterpolationMode
805
""" Copyright (c) 2022, salesforce.com, inc. All rights reserved. SPDX-License-Identifier: BSD-3-Clause For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause """ class BlipImageBaseProcessor(BaseProcessor): def __init__(self, mean=None, std=None): ...
""" Copyright (c) 2022, salesforce.com, inc. All rights reserved. SPDX-License-Identifier: BSD-3-Clause For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause """ class BlipImageBaseProcessor(BaseProcessor): def __init__(self, mean=None, std=None): ...
@registry.register_processor("blip_caption")
0
2023-12-05 14:17:17+00:00
2k
TristanBilot/mlx-GCN
main_torch.py
[ { "identifier": "download_cora", "path": "datasets.py", "snippet": "def download_cora():\n \"\"\"Downloads the cora dataset into a local cora folder.\"\"\"\n\n url = \"https://linqs-data.soe.ucsc.edu/public/lbc/cora.tgz\"\n extract_to = \".\"\n\n if os.path.exists(os.path.join(extract_to, \"...
from argparse import ArgumentParser from time import time from datasets import download_cora, load_data, train_val_test_mask import torch import torch.nn as nn
1,238
class GCNLayer(nn.Module): def __init__(self, x_dim, h_dim, bias=True): super(GCNLayer, self).__init__() self.weight = nn.Parameter(torch.FloatTensor(torch.zeros(size=(x_dim, h_dim)))) if bias: self.bias = nn.Parameter(torch.FloatTensor(torch.zeros(size=(h_dim,)))) el...
class GCNLayer(nn.Module): def __init__(self, x_dim, h_dim, bias=True): super(GCNLayer, self).__init__() self.weight = nn.Parameter(torch.FloatTensor(torch.zeros(size=(x_dim, h_dim)))) if bias: self.bias = nn.Parameter(torch.FloatTensor(torch.zeros(size=(h_dim,)))) el...
train_mask, val_mask, test_mask = train_val_test_mask(y, args.nb_classes)
2
2023-12-11 09:40:09+00:00
2k
3dlg-hcvc/cage
models/denoiser.py
[ { "identifier": "FinalLayer", "path": "models/utils.py", "snippet": "class FinalLayer(nn.Module):\n def __init__(self, in_ch, out_ch=None, dropout=0.):\n super().__init__()\n out_ch = in_ch if out_ch is None else out_ch\n self.linear = nn.Linear(in_ch, out_ch)\n self.norm ...
import torch import models from torch import nn from models.utils import FinalLayer, PEmbeder, AAB
1,352
@models.register('denoiser') class AABModel(nn.Module): ''' Denoiser based on Attribute Attention Block (AAB) 3 sequential attentions: local -> global -> graph ''' def __init__(self, hparams): super(AABModel, self).__init__() self.hparams = hparams in_ch = hparams.in_ch ...
@models.register('denoiser') class AABModel(nn.Module): ''' Denoiser based on Attribute Attention Block (AAB) 3 sequential attentions: local -> global -> graph ''' def __init__(self, hparams): super(AABModel, self).__init__() self.hparams = hparams in_ch = hparams.in_ch ...
self.final_layer = FinalLayer(attn_dim, in_ch, dropout=dropout)
0
2023-12-06 23:08:41+00:00
2k
modelscope/llmuses
llmuses/benchmarks/data_adapter.py
[ { "identifier": "Benchmark", "path": "llmuses/benchmarks/benchmark.py", "snippet": "class Benchmark(object):\n \"\"\"\n Wrapper for loading datasets from ModelScope or HuggingFace.\n \"\"\"\n\n def __init__(self):\n ...\n\n @staticmethod\n def load(dataset_name: str,\n ...
from abc import ABC, abstractmethod from typing import Any, Optional from llmuses.benchmarks import Benchmark from llmuses.constants import DEFAULT_ROOT_CACHE_DIR, AnswerKeys from llmuses.utils.logger import get_logger import random
1,377
# Copyright (c) Alibaba, Inc. and its affiliates. logger = get_logger() class DataAdapter(ABC): def __init__(self, subset_list: list, metric_list: list, few_shot_num: Optional[int] = 0, train_split: Optional[str] = None, eval...
# Copyright (c) Alibaba, Inc. and its affiliates. logger = get_logger() class DataAdapter(ABC): def __init__(self, subset_list: list, metric_list: list, few_shot_num: Optional[int] = 0, train_split: Optional[str] = None, eval...
dataset = Benchmark.load(dataset_name=dataset_name_or_path,
0
2023-12-07 06:10:49+00:00
2k