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 |
|---|---|---|---|---|---|---|---|---|---|---|
daswer123/rvc-python | rvc_python/__main__.py | [
{
"identifier": "infer_file",
"path": "rvc_python/infer.py",
"snippet": "def infer_file(\n input_path,\n model_path,\n index_path = \"\",\n device = \"cpu:0\",\n f0method = \"harvest\",\n opt_path = \"out.wav\",\n index_rate = 0.5,\n filter_radius = 3,\n resample_sr = 0,\n ... | import argparse
import sys
import os
from argparse import ArgumentParser
from rvc_python.infer import infer_file,infer_files | 1,356 |
parser = ArgumentParser(description="RVC inference")
# Create a mutually exclusive group for input - only one of them can be provided
input_group = parser.add_mutually_exclusive_group(required=True)
input_group.add_argument("-i", "--input", type=str, help="Path to input file")
input_group.add_argument("-d", "--dir", type=str, help="Directory path containing audio files")
parser.add_argument("-pi","--pitch", default=0, type=int, help="Transpose (integer, number of semitones)")
parser.add_argument("-ip","--index", type=str, nargs='?', default="", help="Path to index file (optional)")
parser.add_argument("-me","--method", type=str, default="harvest", choices=['harvest', "crepe", "rmvpe", 'pm'], help="Pitch extraction algorithm")
parser.add_argument("-v","--version", type=str, default="v2", choices=['v1', "v2"], help="Model version")
parser.add_argument("-o","--output", type=str, nargs='?', default="out.wav", help="Output path for single file, or output directory for multiple files")
parser.add_argument("-mp","--model", type=str, required=True, help="Path to model file")
parser.add_argument("-ir","--index_rate", type=float, default=0.5, help="Search feature ratio")
parser.add_argument("-de","--device", type=str, default="cuda:0", help="Device to use (e.g., cpu:0, cuda:0)")
parser.add_argument("-fr","--filter_radius", type=int, default=3, help="Apply median filtering to the pitch results")
parser.add_argument("-rsr","--resample_sr", type=int, default=0, help="Resample rate for the output audio")
parser.add_argument("-rmr","--rms_mix_rate", type=float,default=0.25 ,help="Volume envelope mix rate")
parser.add_argument("-pr",'--protect' ,type=float,default=0.33 ,help='Protect voiceless consonants and breath sounds')
args = parser.parse_args()
if args.input:
# Single file processing
inferred_path = infer_file(
input_path=args.input,
model_path=args.model,
index_path=args.index,
device=args.device,
f0method=args.method,
f0up_key=args.pitch,
opt_path=args.output,
index_rate=args.index_rate,
filter_radius=args.filter_radius,
resample_sr=args.resample_sr,
rms_mix_rate=args.rms_mix_rate,
protect=args.protect,
version=args.version
)
elif args.dir:
# Directory processing
|
parser = ArgumentParser(description="RVC inference")
# Create a mutually exclusive group for input - only one of them can be provided
input_group = parser.add_mutually_exclusive_group(required=True)
input_group.add_argument("-i", "--input", type=str, help="Path to input file")
input_group.add_argument("-d", "--dir", type=str, help="Directory path containing audio files")
parser.add_argument("-pi","--pitch", default=0, type=int, help="Transpose (integer, number of semitones)")
parser.add_argument("-ip","--index", type=str, nargs='?', default="", help="Path to index file (optional)")
parser.add_argument("-me","--method", type=str, default="harvest", choices=['harvest', "crepe", "rmvpe", 'pm'], help="Pitch extraction algorithm")
parser.add_argument("-v","--version", type=str, default="v2", choices=['v1', "v2"], help="Model version")
parser.add_argument("-o","--output", type=str, nargs='?', default="out.wav", help="Output path for single file, or output directory for multiple files")
parser.add_argument("-mp","--model", type=str, required=True, help="Path to model file")
parser.add_argument("-ir","--index_rate", type=float, default=0.5, help="Search feature ratio")
parser.add_argument("-de","--device", type=str, default="cuda:0", help="Device to use (e.g., cpu:0, cuda:0)")
parser.add_argument("-fr","--filter_radius", type=int, default=3, help="Apply median filtering to the pitch results")
parser.add_argument("-rsr","--resample_sr", type=int, default=0, help="Resample rate for the output audio")
parser.add_argument("-rmr","--rms_mix_rate", type=float,default=0.25 ,help="Volume envelope mix rate")
parser.add_argument("-pr",'--protect' ,type=float,default=0.33 ,help='Protect voiceless consonants and breath sounds')
args = parser.parse_args()
if args.input:
# Single file processing
inferred_path = infer_file(
input_path=args.input,
model_path=args.model,
index_path=args.index,
device=args.device,
f0method=args.method,
f0up_key=args.pitch,
opt_path=args.output,
index_rate=args.index_rate,
filter_radius=args.filter_radius,
resample_sr=args.resample_sr,
rms_mix_rate=args.rms_mix_rate,
protect=args.protect,
version=args.version
)
elif args.dir:
# Directory processing | processed_files = infer_files( | 1 | 2023-12-26 19:05:42+00:00 | 2k |
CodeBrugs/ToolSculpt | tests/test_tools/test_tool2.py | [
{
"identifier": "process_data",
"path": "src/tools/Tool2/tool2_functions.py",
"snippet": "def process_data(data):\n \"\"\"\n Procesa los datos utilizando la lógica específica de Tool2.\n\n Parameters:\n - data (str): Datos de entrada.\n\n Returns:\n - result (str): Resultado del proces... | import unittest
from src.tools.Tool2.tool2_functions import process_data, analyze_data, perform_additional_task | 649 | # tests/test_tools/test_tool2.py
class TestTool2Functions(unittest.TestCase):
def test_process_data(self):
# Prueba para la función process_data
input_data = "example_data"
result = process_data(input_data)
self.assertEqual(result, "Tool2 processed the data: A_SPECIAL_TRANSFORMATION")
def test_analyze_data(self):
# Prueba para la función analyze_data
input_data = "example_data"
result = analyze_data(input_data)
self.assertEqual(result, "Tool2 analyzed the data: example_data. Alphabetic characters: 11")
def test_perform_additional_task(self):
# Prueba para la función perform_additional_task
| # tests/test_tools/test_tool2.py
class TestTool2Functions(unittest.TestCase):
def test_process_data(self):
# Prueba para la función process_data
input_data = "example_data"
result = process_data(input_data)
self.assertEqual(result, "Tool2 processed the data: A_SPECIAL_TRANSFORMATION")
def test_analyze_data(self):
# Prueba para la función analyze_data
input_data = "example_data"
result = analyze_data(input_data)
self.assertEqual(result, "Tool2 analyzed the data: example_data. Alphabetic characters: 11")
def test_perform_additional_task(self):
# Prueba para la función perform_additional_task | result = perform_additional_task() | 2 | 2023-12-26 17:03:20+00:00 | 2k |
run-llama/rags | pages/3_🤖_Generated_RAG_Agent.py | [
{
"identifier": "add_sidebar",
"path": "st_utils.py",
"snippet": "def add_sidebar() -> None:\n \"\"\"Add sidebar.\"\"\"\n with st.sidebar:\n agent_registry = cast(AgentCacheRegistry, st.session_state.agent_registry)\n st.session_state.cur_agent_ids = agent_registry.get_agent_ids()\n ... | import streamlit as st
import pandas as pd
from st_utils import add_sidebar, get_current_state
from core.utils import get_image_and_text_nodes
from llama_index.schema import MetadataMode
from llama_index.chat_engine.types import AGENT_CHAT_RESPONSE_TYPE
from typing import Dict, Optional | 1,164 | """Streamlit page showing builder config."""
####################
#### STREAMLIT #####
####################
st.set_page_config(
page_title="Generated RAG Agent",
page_icon="🦙",
layout="centered",
initial_sidebar_state="auto",
menu_items=None,
)
st.title("Generated RAG Agent")
current_state = get_current_state()
add_sidebar()
if (
"agent_messages" not in st.session_state.keys()
): # Initialize the chat messages history
st.session_state.agent_messages = [
{"role": "assistant", "content": "Ask me a question!"}
]
def display_sources(response: AGENT_CHAT_RESPONSE_TYPE) -> None:
| """Streamlit page showing builder config."""
####################
#### STREAMLIT #####
####################
st.set_page_config(
page_title="Generated RAG Agent",
page_icon="🦙",
layout="centered",
initial_sidebar_state="auto",
menu_items=None,
)
st.title("Generated RAG Agent")
current_state = get_current_state()
add_sidebar()
if (
"agent_messages" not in st.session_state.keys()
): # Initialize the chat messages history
st.session_state.agent_messages = [
{"role": "assistant", "content": "Ask me a question!"}
]
def display_sources(response: AGENT_CHAT_RESPONSE_TYPE) -> None: | image_nodes, text_nodes = get_image_and_text_nodes(response.source_nodes) | 2 | 2023-11-16 07:49:44+00:00 | 2k |
open-mmlab/Amphion | modules/diffusion/bidilconv/residual_block.py | [
{
"identifier": "GaU",
"path": "modules/activation_functions/gated_activation_unit.py",
"snippet": "class GaU(nn.Module):\n r\"\"\"Gated Activation Unit (GaU) proposed in `Gated Activation Units for Neural\n Networks <https://arxiv.org/pdf/1606.05328.pdf>`_.\n\n Args:\n channels: number ... | import math
import torch
import torch.nn as nn
from modules.activation_functions import GaU
from modules.general.utils import Conv1d | 701 | # Copyright (c) 2023 Amphion.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
class ResidualBlock(nn.Module):
r"""Residual block with dilated convolution, main portion of ``BiDilConv``.
Args:
channels: The number of channels of input and output.
kernel_size: The kernel size of dilated convolution.
dilation: The dilation rate of dilated convolution.
d_context: The dimension of content encoder output, None if don't use context.
"""
def __init__(
self,
channels: int = 256,
kernel_size: int = 3,
dilation: int = 1,
d_context: int = None,
):
super().__init__()
self.context = d_context
| # Copyright (c) 2023 Amphion.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
class ResidualBlock(nn.Module):
r"""Residual block with dilated convolution, main portion of ``BiDilConv``.
Args:
channels: The number of channels of input and output.
kernel_size: The kernel size of dilated convolution.
dilation: The dilation rate of dilated convolution.
d_context: The dimension of content encoder output, None if don't use context.
"""
def __init__(
self,
channels: int = 256,
kernel_size: int = 3,
dilation: int = 1,
d_context: int = None,
):
super().__init__()
self.context = d_context
| self.gau = GaU( | 0 | 2023-11-15 09:19:27+00:00 | 2k |
ise-uiuc/magicoder | src/magicoder/decontamination/find_substrings.py | [
{
"identifier": "FILTER_OUT",
"path": "src/magicoder/decontamination/benchmark_data.py",
"snippet": "FILTER_OUT = {k: v() for k, v in LAZY_FILTER_OUT.items()}"
},
{
"identifier": "add_dict",
"path": "src/magicoder/decontamination/utils.py",
"snippet": "def add_dict(dict1: dict, dict2: di... | import argparse
import json
import os
import shutil
from copy import deepcopy
from glob import glob
from pathlib import Path
from datasets import load_dataset
from magicoder.utils import write_jsonl
from .benchmark_data import FILTER_OUT
from .utils import add_dict, shard_dataset | 1,404 | # type: ignore
"""Migrated from: https://github.com/bigcode-project/bigcode-dataset. License: Apache 2.0"""
SHARD_SIZE = 1000 << 20 # 1GB
LANGUAGE_COL = "lang"
# LANGUAGES = ["Python", "Java", "JavaScript"]
def dump_benchmarks(file_path: str):
"""
Dump the dictionary of benchmark samples that are filtered out
"""
with open(file_path, "w") as f:
json.dump(FILTER_OUT, f, indent=2)
def filter_reason_to_benchmark_name(filter_reason: str):
assert filter_reason.endswith("_match")
return filter_reason[:-6]
def benchmark_name_to_filter_reason(benchmark_name: str):
return f"{benchmark_name}_match"
def update_benchmark_dict(
filter_out: dict, benchmark_cache: str, excluded_data_cache: str
):
"""
Iterates on current benchmark-samples. If a sample is found in the cached benchmark-samples, it is removed (it does not need to be searched),
and the corresponding data-samples from the cache are added to `exclude_data`
Returns:
- `updated`: an updated benchmark dict where samples from the cache are removed (they do not need to be searched anymore)
- `exclude_data`: a list of files to remove from the dataset
"""
updated = deepcopy(filter_out)
exclude_data = []
with open(benchmark_cache) as f:
benchmark_cache = json.load(f)
with open(excluded_data_cache) as f:
excluded_data_cache = json.load(f)
for bench, samples in filter_out.items():
for bench_sample in samples:
# Benchmark-sample was found in cache
if bench in benchmark_cache and bench_sample in benchmark_cache[bench]:
# No need to search for this sample in the dataset
updated[bench].remove(bench_sample)
# Corresponding data-samples will be excluded from the dataset.
exclude_data += [
data_sample
for data_sample in excluded_data_cache
if data_sample["filter_reason"]
== benchmark_name_to_filter_reason(bench)
and data_sample["matched_substring"] == bench_sample
]
print("After loading cache, will search for:")
for benchmark, values in updated.items():
print(f" num strings from {benchmark}: {len(values)}")
# Remove empty benchmarks
updated = {key: value for key, value in updated.items() if len(value) > 0}
return updated, exclude_data
def find_substrings(data, columns, filter_out, return_matched=False):
"""
filter_out: Dict[str, List[str]] mapping from benchmark name to list of strings that need to be
filtered-out.
Return True, None if the file should be included in the dataset.
Otherwise return False and some metadata about the file excluded
"""
content = "\n\n".join([data[col].lower() for col in columns])
# For each substring, try to find it in the file (case insensitive)
for benchmark, substrings in filter_out.items():
for substring in substrings:
if substring.lower() in content:
if return_matched:
return False, benchmark_name_to_filter_reason(benchmark), substring
else:
return False, benchmark_name_to_filter_reason(benchmark)
# Return True, None if none of the substrings was found
if return_matched:
return True, None, None
else:
return True, None
def aggregate_meta(tmp_meta_dir: str):
res = {}
for file in glob(f"{tmp_meta_dir}/*-meta.json"):
with open(file, "r") as f:
meta = json.load(f)
| # type: ignore
"""Migrated from: https://github.com/bigcode-project/bigcode-dataset. License: Apache 2.0"""
SHARD_SIZE = 1000 << 20 # 1GB
LANGUAGE_COL = "lang"
# LANGUAGES = ["Python", "Java", "JavaScript"]
def dump_benchmarks(file_path: str):
"""
Dump the dictionary of benchmark samples that are filtered out
"""
with open(file_path, "w") as f:
json.dump(FILTER_OUT, f, indent=2)
def filter_reason_to_benchmark_name(filter_reason: str):
assert filter_reason.endswith("_match")
return filter_reason[:-6]
def benchmark_name_to_filter_reason(benchmark_name: str):
return f"{benchmark_name}_match"
def update_benchmark_dict(
filter_out: dict, benchmark_cache: str, excluded_data_cache: str
):
"""
Iterates on current benchmark-samples. If a sample is found in the cached benchmark-samples, it is removed (it does not need to be searched),
and the corresponding data-samples from the cache are added to `exclude_data`
Returns:
- `updated`: an updated benchmark dict where samples from the cache are removed (they do not need to be searched anymore)
- `exclude_data`: a list of files to remove from the dataset
"""
updated = deepcopy(filter_out)
exclude_data = []
with open(benchmark_cache) as f:
benchmark_cache = json.load(f)
with open(excluded_data_cache) as f:
excluded_data_cache = json.load(f)
for bench, samples in filter_out.items():
for bench_sample in samples:
# Benchmark-sample was found in cache
if bench in benchmark_cache and bench_sample in benchmark_cache[bench]:
# No need to search for this sample in the dataset
updated[bench].remove(bench_sample)
# Corresponding data-samples will be excluded from the dataset.
exclude_data += [
data_sample
for data_sample in excluded_data_cache
if data_sample["filter_reason"]
== benchmark_name_to_filter_reason(bench)
and data_sample["matched_substring"] == bench_sample
]
print("After loading cache, will search for:")
for benchmark, values in updated.items():
print(f" num strings from {benchmark}: {len(values)}")
# Remove empty benchmarks
updated = {key: value for key, value in updated.items() if len(value) > 0}
return updated, exclude_data
def find_substrings(data, columns, filter_out, return_matched=False):
"""
filter_out: Dict[str, List[str]] mapping from benchmark name to list of strings that need to be
filtered-out.
Return True, None if the file should be included in the dataset.
Otherwise return False and some metadata about the file excluded
"""
content = "\n\n".join([data[col].lower() for col in columns])
# For each substring, try to find it in the file (case insensitive)
for benchmark, substrings in filter_out.items():
for substring in substrings:
if substring.lower() in content:
if return_matched:
return False, benchmark_name_to_filter_reason(benchmark), substring
else:
return False, benchmark_name_to_filter_reason(benchmark)
# Return True, None if none of the substrings was found
if return_matched:
return True, None, None
else:
return True, None
def aggregate_meta(tmp_meta_dir: str):
res = {}
for file in glob(f"{tmp_meta_dir}/*-meta.json"):
with open(file, "r") as f:
meta = json.load(f) | add_dict(res, meta) | 1 | 2023-11-10 07:35:29+00:00 | 2k |
KwaiKEG/KwaiAgents | kwaiagents/tools/timedelta.py | [
{
"identifier": "Config",
"path": "kwaiagents/config.py",
"snippet": "class Config(object):\n def __init__(self) -> None:\n \"\"\"Initialize the Config class\"\"\"\n self.fast_llm_model = \"gpt-3.5-turbo\"\n self.smart_llm_model = \"gpt-4\"\n self.use_local_llm = False\n ... | from datetime import datetime
from dateutil.relativedelta import relativedelta
from kwaiagents.config import Config
from kwaiagents.tools.base import BaseResult, BaseTool | 643 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: PAN Leyi
# Email: panleyi@kuaishou.com
class TimeDeltaResult(BaseResult):
@property
def answer(self):
item = self.json_data
rst = ""
for key in item.keys():
rst += f'{key}: {item[key]}\n'
return rst
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: PAN Leyi
# Email: panleyi@kuaishou.com
class TimeDeltaResult(BaseResult):
@property
def answer(self):
item = self.json_data
rst = ""
for key in item.keys():
rst += f'{key}: {item[key]}\n'
return rst
| class TimeDeltaTool(BaseTool): | 2 | 2023-11-13 03:37:02+00:00 | 2k |
EnVision-Research/LucidDreamer | scene/dataset_readers.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 sys
import torch
import random
import torch.nn.functional as F
import numpy as np
import json
from PIL import Image
from typing import NamedTuple
from utils.graphics_utils import getWorld2View2, focal2fov, fov2focal
from pathlib import Path
from utils.pointe_utils import init_from_pointe
from plyfile import PlyData, PlyElement
from utils.sh_utils import SH2RGB
from utils.general_utils import inverse_sigmoid_np
from scene.gaussian_model import BasicPointCloud | 1,413 | #
# 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 RandCameraInfo(NamedTuple):
uid: int
R: np.array
T: np.array
FovY: np.array
FovX: np.array
width: int
height: int
delta_polar : np.array
delta_azimuth : np.array
delta_radius : np.array
class SceneInfo(NamedTuple):
| #
# 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 RandCameraInfo(NamedTuple):
uid: int
R: np.array
T: np.array
FovY: np.array
FovX: np.array
width: int
height: int
delta_polar : np.array
delta_azimuth : np.array
delta_radius : np.array
class SceneInfo(NamedTuple): | point_cloud: BasicPointCloud | 6 | 2023-11-18 08:05:50+00:00 | 2k |
VRSEN/agency-swarm | agency_swarm/tools/browsing/GoBack.py | [
{
"identifier": "BaseTool",
"path": "agency_swarm/tools/base_tool.py",
"snippet": "class BaseTool(OpenAISchema, ABC):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n # # Exclude 'run' method from Pydantic model fields\n # self.model_fields.pop(\"run\", None)\n\n ... | import time
from agency_swarm.tools import BaseTool
from agency_swarm.tools.browsing.util.selenium import get_web_driver, set_web_driver | 982 |
class GoBack(BaseTool):
"""
This tool allows you to go back 1 page in the browser history. Use it in case of a mistake or if a page shows you unexpected content.
"""
def run(self):
|
class GoBack(BaseTool):
"""
This tool allows you to go back 1 page in the browser history. Use it in case of a mistake or if a page shows you unexpected content.
"""
def run(self): | wd = get_web_driver() | 1 | 2023-11-16 02:29:26+00:00 | 2k |
resemble-ai/resemble-enhance | resemble_enhance/denoiser/denoiser.py | [
{
"identifier": "MelSpectrogram",
"path": "resemble_enhance/melspec.py",
"snippet": "class MelSpectrogram(nn.Module):\n def __init__(self, hp: HParams):\n \"\"\"\n Torch implementation of Resemble's mel extraction.\n Note that the values are NOT identical to librosa's implementat... | import logging
import torch
import torch.nn.functional as F
from torch import Tensor, nn
from ..melspec import MelSpectrogram
from .hparams import HParams
from .unet import UNet | 1,595 |
logger = logging.getLogger(__name__)
def _normalize(x: Tensor) -> Tensor:
return x / (x.abs().max(dim=-1, keepdim=True).values + 1e-7)
class Denoiser(nn.Module):
@property
def stft_cfg(self) -> dict:
hop_size = self.hp.hop_size
return dict(hop_length=hop_size, n_fft=hop_size * 4, win_length=hop_size * 4)
@property
def n_fft(self):
return self.stft_cfg["n_fft"]
@property
def eps(self):
return 1e-7
def __init__(self, hp: HParams):
super().__init__()
self.hp = hp
self.net = UNet(input_dim=3, output_dim=3)
|
logger = logging.getLogger(__name__)
def _normalize(x: Tensor) -> Tensor:
return x / (x.abs().max(dim=-1, keepdim=True).values + 1e-7)
class Denoiser(nn.Module):
@property
def stft_cfg(self) -> dict:
hop_size = self.hp.hop_size
return dict(hop_length=hop_size, n_fft=hop_size * 4, win_length=hop_size * 4)
@property
def n_fft(self):
return self.stft_cfg["n_fft"]
@property
def eps(self):
return 1e-7
def __init__(self, hp: HParams):
super().__init__()
self.hp = hp
self.net = UNet(input_dim=3, output_dim=3) | self.mel_fn = MelSpectrogram(hp) | 0 | 2023-11-15 08:15:51+00:00 | 2k |
PKU-YuanGroup/Chat-UniVi | ChatUniVi/model/builder.py | [
{
"identifier": "DEFAULT_IMAGE_PATCH_TOKEN",
"path": "ChatUniVi/constants.py",
"snippet": "DEFAULT_IMAGE_PATCH_TOKEN = \"<im_patch>\""
},
{
"identifier": "DEFAULT_IM_START_TOKEN",
"path": "ChatUniVi/constants.py",
"snippet": "DEFAULT_IM_START_TOKEN = \"<im_start>\""
},
{
"identif... | import os
import shutil
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig, BitsAndBytesConfig
from ChatUniVi.model import *
from ChatUniVi.constants import DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
from accelerate import init_empty_weights, load_checkpoint_and_dispatch
from transformers import AutoConfig, AutoModelForCausalLM
from huggingface_hub import hf_hub_download
from peft import PeftModel
from peft import PeftModel | 1,265 |
def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, load_4bit=False, device_map="auto"):
kwargs = {"device_map": device_map}
if load_8bit:
kwargs['load_in_8bit'] = True
elif load_4bit:
kwargs['load_in_4bit'] = True
kwargs['quantization_config'] = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_compute_dtype=torch.float16,
bnb_4bit_use_double_quant=True,
bnb_4bit_quant_type='nf4'
)
else:
kwargs['torch_dtype'] = torch.float16
if 'chatunivi' in model_name.lower():
# Load ChatUniVi model
if 'lora' in model_name.lower() and model_base is not None:
lora_cfg_pretrained = AutoConfig.from_pretrained(model_path)
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
print('Loading ChatUniVi from base model...')
model = ChatUniViLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, **kwargs)
token_num, tokem_dim = model.lm_head.out_features, model.lm_head.in_features
if model.lm_head.weight.shape[0] != token_num:
model.lm_head.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
model.model.embed_tokens.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
print('Loading additional ChatUniVi weights...')
if os.path.exists(os.path.join(model_path, 'non_lora_trainables.bin')):
non_lora_trainables = torch.load(os.path.join(model_path, 'non_lora_trainables.bin'), map_location='cpu')
else:
# this is probably from HF Hub
def load_from_hf(repo_id, filename, subfolder=None):
cache_file = hf_hub_download(
repo_id=repo_id,
filename=filename,
subfolder=subfolder)
return torch.load(cache_file, map_location='cpu')
non_lora_trainables = load_from_hf(model_path, 'non_lora_trainables.bin')
non_lora_trainables = {(k[11:] if k.startswith('base_model.') else k): v for k, v in non_lora_trainables.items()}
if any(k.startswith('model.model.') for k in non_lora_trainables):
non_lora_trainables = {(k[6:] if k.startswith('model.') else k): v for k, v in non_lora_trainables.items()}
model.load_state_dict(non_lora_trainables, strict=False)
print('Loading LoRA weights...')
model = PeftModel.from_pretrained(model, model_path)
print('Merging LoRA weights...')
model = model.merge_and_unload()
print('Model is loaded...')
elif model_base is not None:
# this may be mm projector only
print('Loading ChatUniVi from base model...')
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
cfg_pretrained = AutoConfig.from_pretrained(model_path)
model = ChatUniViLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs)
mm_projector_weights = torch.load(os.path.join(model_path, 'mm_projector.bin'), map_location='cpu')
mm_projector_weights = {k: v.to(torch.float16) for k, v in mm_projector_weights.items()}
model.load_state_dict(mm_projector_weights, strict=False)
else:
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
else:
# Load language model
if model_base is not None:
# PEFT model
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
model = AutoModelForCausalLM.from_pretrained(model_base, torch_dtype=torch.float16, low_cpu_mem_usage=True, device_map="auto")
print(f"Loading LoRA weights from {model_path}")
model = PeftModel.from_pretrained(model, model_path)
print(f"Merging weights")
model = model.merge_and_unload()
print('Convert to FP16...')
model.to(torch.float16)
else:
use_fast = False
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
image_processor = None
if 'chatunivi' in model_name.lower():
mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False)
mm_use_im_patch_token = getattr(model.config, "mm_use_im_patch_token", True)
if mm_use_im_patch_token:
|
def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, load_4bit=False, device_map="auto"):
kwargs = {"device_map": device_map}
if load_8bit:
kwargs['load_in_8bit'] = True
elif load_4bit:
kwargs['load_in_4bit'] = True
kwargs['quantization_config'] = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_compute_dtype=torch.float16,
bnb_4bit_use_double_quant=True,
bnb_4bit_quant_type='nf4'
)
else:
kwargs['torch_dtype'] = torch.float16
if 'chatunivi' in model_name.lower():
# Load ChatUniVi model
if 'lora' in model_name.lower() and model_base is not None:
lora_cfg_pretrained = AutoConfig.from_pretrained(model_path)
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
print('Loading ChatUniVi from base model...')
model = ChatUniViLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, **kwargs)
token_num, tokem_dim = model.lm_head.out_features, model.lm_head.in_features
if model.lm_head.weight.shape[0] != token_num:
model.lm_head.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
model.model.embed_tokens.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
print('Loading additional ChatUniVi weights...')
if os.path.exists(os.path.join(model_path, 'non_lora_trainables.bin')):
non_lora_trainables = torch.load(os.path.join(model_path, 'non_lora_trainables.bin'), map_location='cpu')
else:
# this is probably from HF Hub
def load_from_hf(repo_id, filename, subfolder=None):
cache_file = hf_hub_download(
repo_id=repo_id,
filename=filename,
subfolder=subfolder)
return torch.load(cache_file, map_location='cpu')
non_lora_trainables = load_from_hf(model_path, 'non_lora_trainables.bin')
non_lora_trainables = {(k[11:] if k.startswith('base_model.') else k): v for k, v in non_lora_trainables.items()}
if any(k.startswith('model.model.') for k in non_lora_trainables):
non_lora_trainables = {(k[6:] if k.startswith('model.') else k): v for k, v in non_lora_trainables.items()}
model.load_state_dict(non_lora_trainables, strict=False)
print('Loading LoRA weights...')
model = PeftModel.from_pretrained(model, model_path)
print('Merging LoRA weights...')
model = model.merge_and_unload()
print('Model is loaded...')
elif model_base is not None:
# this may be mm projector only
print('Loading ChatUniVi from base model...')
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
cfg_pretrained = AutoConfig.from_pretrained(model_path)
model = ChatUniViLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs)
mm_projector_weights = torch.load(os.path.join(model_path, 'mm_projector.bin'), map_location='cpu')
mm_projector_weights = {k: v.to(torch.float16) for k, v in mm_projector_weights.items()}
model.load_state_dict(mm_projector_weights, strict=False)
else:
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
else:
# Load language model
if model_base is not None:
# PEFT model
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
model = AutoModelForCausalLM.from_pretrained(model_base, torch_dtype=torch.float16, low_cpu_mem_usage=True, device_map="auto")
print(f"Loading LoRA weights from {model_path}")
model = PeftModel.from_pretrained(model, model_path)
print(f"Merging weights")
model = model.merge_and_unload()
print('Convert to FP16...')
model.to(torch.float16)
else:
use_fast = False
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
image_processor = None
if 'chatunivi' in model_name.lower():
mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False)
mm_use_im_patch_token = getattr(model.config, "mm_use_im_patch_token", True)
if mm_use_im_patch_token: | tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True) | 0 | 2023-11-13 11:52:56+00:00 | 2k |
tatsu-lab/gpt_paper_assistant | filter_papers.py | [
{
"identifier": "Paper",
"path": "arxiv_scraper.py",
"snippet": "class Paper:\n # paper class should track the list of authors, paper title, abstract, arxiv id\n authors: List[str]\n title: str\n abstract: str\n arxiv_id: str\n\n # add a hash function using arxiv_id\n def __hash__(s... | import configparser
import dataclasses
import json
import os
import re
import retry
from collections import defaultdict
from typing import List
from openai import OpenAI
from tqdm import tqdm
from arxiv_scraper import Paper
from arxiv_scraper import EnhancedJSONEncoder | 1,210 |
def filter_by_author(all_authors, papers, author_targets, config):
# filter and parse the papers
selected_papers = {} # pass to output
all_papers = {} # dict for later filtering
sort_dict = {} # dict storing key and score
# author based selection
for paper in papers:
all_papers[paper.arxiv_id] = paper
if config["FILTERING"].getboolean("author_match"):
for author in paper.authors:
if author in all_authors:
for alias in all_authors[author]:
if alias["authorId"] in author_targets:
selected_papers[paper.arxiv_id] = {
**dataclasses.asdict(paper),
**{"COMMENT": "Author match"},
}
sort_dict[paper.arxiv_id] = float(
config["SELECTION"]["author_match_score"]
)
break
return selected_papers, all_papers, sort_dict
def filter_papers_by_hindex(all_authors, papers, config):
# filters papers by checking to see if there's at least one author with > hcutoff hindex
paper_list = []
for paper in papers:
max_h = 0
for author in paper.authors:
if author in all_authors:
max_h = max(
max_h, max([alias["hIndex"] for alias in all_authors[author]])
)
if max_h >= float(config["FILTERING"]["hcutoff"]):
paper_list.append(paper)
return paper_list
def calc_price(model, usage):
if model == "gpt-4-1106-preview":
return (0.01 * usage.prompt_tokens + 0.03 * usage.completion_tokens) / 1000.0
if model == "gpt-4":
return (0.03 * usage.prompt_tokens + 0.06 * usage.completion_tokens) / 1000.0
if (model == "gpt-3.5-turbo") or (model == "gpt-3.5-turbo-1106"):
return (0.0015 * usage.prompt_tokens + 0.002 * usage.completion_tokens) / 1000.0
@retry.retry(tries=3, delay=2)
def call_chatgpt(full_prompt, openai_client, model, num_samples):
return openai_client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": full_prompt}],
temperature=0.0,
n=int(num_samples),
seed=0,
)
def run_and_parse_chatgpt(full_prompt, openai_client, config):
# just runs the chatgpt prompt, tries to parse the resulting JSON
completion = call_chatgpt(
full_prompt,
openai_client,
config["SELECTION"]["model"],
config["FILTERING"]["num_samples"],
)
json_dicts = defaultdict(list)
for choice in completion.choices:
out_text = choice.message.content
out_text = re.sub("```jsonl\n", "", out_text)
out_text = re.sub("```", "", out_text)
out_text = re.sub(r"\n+", "\n", out_text)
out_text = re.sub("},", "}", out_text).strip()
# split out_text line by line and parse each as a json.
for line in out_text.split("\n"):
# try catch block to attempt to parse json
try:
loaded_output = json.loads(line)
json_dicts[loaded_output["ARXIVID"]].append(loaded_output)
except Exception as ex:
if config["OUTPUT"].getboolean("debug_messages"):
print("Exception happened " + str(ex))
print("Failed to parse LM output as json")
print(out_text)
print("RAW output")
print(completion.choices[0].message.content)
continue
all_dict = []
for id, json_list in json_dicts.items():
rel_score = sum([float(jdict["RELEVANCE"]) for jdict in json_list]) / float(
len(json_list)
)
nov_score = sum([float(jdict["NOVELTY"]) for jdict in json_list]) / float(
len(json_list)
)
new_dict = {
"ARXIVID": json_list[0]["ARXIVID"],
"COMMENT": json_list[0]["COMMENT"],
"RELEVANCE": rel_score,
"NOVELTY": nov_score,
}
all_dict.append(new_dict)
return all_dict, calc_price(config["SELECTION"]["model"], completion.usage)
|
def filter_by_author(all_authors, papers, author_targets, config):
# filter and parse the papers
selected_papers = {} # pass to output
all_papers = {} # dict for later filtering
sort_dict = {} # dict storing key and score
# author based selection
for paper in papers:
all_papers[paper.arxiv_id] = paper
if config["FILTERING"].getboolean("author_match"):
for author in paper.authors:
if author in all_authors:
for alias in all_authors[author]:
if alias["authorId"] in author_targets:
selected_papers[paper.arxiv_id] = {
**dataclasses.asdict(paper),
**{"COMMENT": "Author match"},
}
sort_dict[paper.arxiv_id] = float(
config["SELECTION"]["author_match_score"]
)
break
return selected_papers, all_papers, sort_dict
def filter_papers_by_hindex(all_authors, papers, config):
# filters papers by checking to see if there's at least one author with > hcutoff hindex
paper_list = []
for paper in papers:
max_h = 0
for author in paper.authors:
if author in all_authors:
max_h = max(
max_h, max([alias["hIndex"] for alias in all_authors[author]])
)
if max_h >= float(config["FILTERING"]["hcutoff"]):
paper_list.append(paper)
return paper_list
def calc_price(model, usage):
if model == "gpt-4-1106-preview":
return (0.01 * usage.prompt_tokens + 0.03 * usage.completion_tokens) / 1000.0
if model == "gpt-4":
return (0.03 * usage.prompt_tokens + 0.06 * usage.completion_tokens) / 1000.0
if (model == "gpt-3.5-turbo") or (model == "gpt-3.5-turbo-1106"):
return (0.0015 * usage.prompt_tokens + 0.002 * usage.completion_tokens) / 1000.0
@retry.retry(tries=3, delay=2)
def call_chatgpt(full_prompt, openai_client, model, num_samples):
return openai_client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": full_prompt}],
temperature=0.0,
n=int(num_samples),
seed=0,
)
def run_and_parse_chatgpt(full_prompt, openai_client, config):
# just runs the chatgpt prompt, tries to parse the resulting JSON
completion = call_chatgpt(
full_prompt,
openai_client,
config["SELECTION"]["model"],
config["FILTERING"]["num_samples"],
)
json_dicts = defaultdict(list)
for choice in completion.choices:
out_text = choice.message.content
out_text = re.sub("```jsonl\n", "", out_text)
out_text = re.sub("```", "", out_text)
out_text = re.sub(r"\n+", "\n", out_text)
out_text = re.sub("},", "}", out_text).strip()
# split out_text line by line and parse each as a json.
for line in out_text.split("\n"):
# try catch block to attempt to parse json
try:
loaded_output = json.loads(line)
json_dicts[loaded_output["ARXIVID"]].append(loaded_output)
except Exception as ex:
if config["OUTPUT"].getboolean("debug_messages"):
print("Exception happened " + str(ex))
print("Failed to parse LM output as json")
print(out_text)
print("RAW output")
print(completion.choices[0].message.content)
continue
all_dict = []
for id, json_list in json_dicts.items():
rel_score = sum([float(jdict["RELEVANCE"]) for jdict in json_list]) / float(
len(json_list)
)
nov_score = sum([float(jdict["NOVELTY"]) for jdict in json_list]) / float(
len(json_list)
)
new_dict = {
"ARXIVID": json_list[0]["ARXIVID"],
"COMMENT": json_list[0]["COMMENT"],
"RELEVANCE": rel_score,
"NOVELTY": nov_score,
}
all_dict.append(new_dict)
return all_dict, calc_price(config["SELECTION"]["model"], completion.usage)
| def paper_to_string(paper_entry: Paper) -> str: | 0 | 2023-11-13 15:19:38+00:00 | 2k |
BobaZooba/xllm | tests/unit/datasets/test_registry.py | [
{
"identifier": "enums",
"path": "src/xllm/enums.py",
"snippet": "class General:\nclass Transformers:\nclass Registry:\nclass Datasets:\nclass Collators:\nclass Trainers:\nclass Experiments:\nclass EnvironmentVariables:\nclass LogLevel:"
},
{
"identifier": "datasets_registry",
"path": "src/x... | from src.xllm import enums
from src.xllm.datasets.registry import datasets_registry
from src.xllm.datasets.soda import SodaDataset
from tests.helpers.dummy_data import DATA | 967 | # Copyright 2023 Boris Zubarev. 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def test_get_soda_dataset() -> None:
dataset_cls = datasets_registry.get(key=enums.Datasets.soda)
dataset = dataset_cls(data=DATA)
| # Copyright 2023 Boris Zubarev. 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def test_get_soda_dataset() -> None:
dataset_cls = datasets_registry.get(key=enums.Datasets.soda)
dataset = dataset_cls(data=DATA) | assert isinstance(dataset, SodaDataset) | 2 | 2023-11-10 17:55:03+00:00 | 2k |
banodoco/Steerable-Motion | imports/AdvancedControlNet/latent_keyframe_nodes.py | [
{
"identifier": "LatentKeyframeImport",
"path": "imports/AdvancedControlNet/control.py",
"snippet": "class LatentKeyframeImport:\n def __init__(self, batch_index: int, strength: float) -> None:\n self.batch_index = batch_index\n self.strength = strength"
},
{
"identifier": "Late... | from typing import Union
from collections.abc import Iterable
from .control import LatentKeyframeImport, LatentKeyframeGroupImport
from .control import StrengthInterpolationImport as SI
from .logger import logger
import numpy as np | 934 |
class LatentKeyframeNodeImport:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"batch_index": ("INT", {"default": 0, "min": -1000, "max": 1000, "step": 1}),
"strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
},
"optional": {
"prev_latent_kf": ("LATENT_KEYFRAME", ),
}
}
RETURN_NAMES = ("LATENT_KF", )
RETURN_TYPES = ("LATENT_KEYFRAME", )
FUNCTION = "load_keyframe"
CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
def load_keyframe(self,
batch_index: int,
strength: float,
prev_latent_kf: LatentKeyframeGroupImport=None,
prev_latent_keyframe: LatentKeyframeGroupImport=None, # old name
):
prev_latent_keyframe = prev_latent_keyframe if prev_latent_keyframe else prev_latent_kf
if not prev_latent_keyframe:
prev_latent_keyframe = LatentKeyframeGroupImport()
else:
prev_latent_keyframe = prev_latent_keyframe.clone()
|
class LatentKeyframeNodeImport:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"batch_index": ("INT", {"default": 0, "min": -1000, "max": 1000, "step": 1}),
"strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
},
"optional": {
"prev_latent_kf": ("LATENT_KEYFRAME", ),
}
}
RETURN_NAMES = ("LATENT_KF", )
RETURN_TYPES = ("LATENT_KEYFRAME", )
FUNCTION = "load_keyframe"
CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
def load_keyframe(self,
batch_index: int,
strength: float,
prev_latent_kf: LatentKeyframeGroupImport=None,
prev_latent_keyframe: LatentKeyframeGroupImport=None, # old name
):
prev_latent_keyframe = prev_latent_keyframe if prev_latent_keyframe else prev_latent_kf
if not prev_latent_keyframe:
prev_latent_keyframe = LatentKeyframeGroupImport()
else:
prev_latent_keyframe = prev_latent_keyframe.clone() | keyframe = LatentKeyframeImport(batch_index, strength) | 0 | 2023-11-11 01:26:26+00:00 | 2k |
innovatorved/subtitle | app/core/app.py | [
{
"identifier": "model_names",
"path": "app/models/models.py",
"snippet": "def download_model(model_name):\ndef download_file(url, filepath):"
},
{
"identifier": "check_models_exist",
"path": "app/utils/checks.py",
"snippet": "def check_models_exist(name: str):\n try:\n if mode... | import logging
from app.models import download_model, model_names
from app.utils.checks import check_models_exist
from app.utils import generate_vtt_file, merge_video_and_vtt | 675 |
# Configure logging
logger = logging.getLogger(__name__)
def process_video(file, model="base"):
"""
add_subtitle_in_video
@param file: video file path
@param model: model name
@return: [vtt_file_path , output_file]
"""
try:
if not check_models_exist(model):
download_model(model)
output_file = f"{file.split('.')[0]}_subtitled.{file.split('.')[1]}"
|
# Configure logging
logger = logging.getLogger(__name__)
def process_video(file, model="base"):
"""
add_subtitle_in_video
@param file: video file path
@param model: model name
@return: [vtt_file_path , output_file]
"""
try:
if not check_models_exist(model):
download_model(model)
output_file = f"{file.split('.')[0]}_subtitled.{file.split('.')[1]}" | process_id, output_audio_path, vtt_file_path = generate_vtt_file( | 2 | 2023-11-17 10:12:33+00:00 | 2k |
x0rzavi/github-readme-terminal | gifos/utils/upload_imgbb.py | [
{
"identifier": "gifos_settings",
"path": "gifos/utils/load_config.py",
"snippet": "def load_toml(file_name: str) -> dict:\n def __update_config_with_env_vars(config, prefix=\"GIFOS\"):"
},
{
"identifier": "ImgbbImage",
"path": "gifos/utils/schemas/imagebb_image.py",
"snippet": "class... | from base64 import b64encode
from dotenv import load_dotenv
from gifos.utils.load_config import gifos_settings
from gifos.utils.schemas.imagebb_image import ImgbbImage
import os
import requests
import sys | 723 |
"""This module contains a function for uploading an image to ImgBB."""
load_dotenv()
IMGBB_API_KEY = os.getenv("IMGBB_API_KEY")
ENDPOINT = "https://api.imgbb.com/1/upload"
def upload_imgbb(file_name: str, expiration: int = None) -> ImgbbImage:
"""Upload an image to ImgBB.
This function uploads an image to ImgBB using the ImgBB API. The function reads the
image file, encodes it in base64, and sends a POST request to the ImgBB API. The
function uses the `IMGBB_API_KEY` environment variable for authentication and the
`ENDPOINT` constant for the API endpoint. If the `debug` configuration value is
True, the function sets the image expiration time to 10 minutes.
:param file_name: The name of the image file to upload.
:type file_name: str
:param expiration: The expiration time for the image in seconds. If the `debug`
configuration value is True, this parameter is ignored and the expiration time
is set to 10 minutes. The value must be between 60 and 15552000 (6 months) if
provided.
:type expiration: int, optional
:return: An `ImgbbImage` object containing the uploaded image's information if the
upload is successful, otherwise None.
:rtype: ImgbbImage or None
"""
if not IMGBB_API_KEY:
print("ERROR: Please provide IMGBB_API_KEY")
sys.exit(1)
|
"""This module contains a function for uploading an image to ImgBB."""
load_dotenv()
IMGBB_API_KEY = os.getenv("IMGBB_API_KEY")
ENDPOINT = "https://api.imgbb.com/1/upload"
def upload_imgbb(file_name: str, expiration: int = None) -> ImgbbImage:
"""Upload an image to ImgBB.
This function uploads an image to ImgBB using the ImgBB API. The function reads the
image file, encodes it in base64, and sends a POST request to the ImgBB API. The
function uses the `IMGBB_API_KEY` environment variable for authentication and the
`ENDPOINT` constant for the API endpoint. If the `debug` configuration value is
True, the function sets the image expiration time to 10 minutes.
:param file_name: The name of the image file to upload.
:type file_name: str
:param expiration: The expiration time for the image in seconds. If the `debug`
configuration value is True, this parameter is ignored and the expiration time
is set to 10 minutes. The value must be between 60 and 15552000 (6 months) if
provided.
:type expiration: int, optional
:return: An `ImgbbImage` object containing the uploaded image's information if the
upload is successful, otherwise None.
:rtype: ImgbbImage or None
"""
if not IMGBB_API_KEY:
print("ERROR: Please provide IMGBB_API_KEY")
sys.exit(1)
| if gifos_settings.get("general", {}).get("debug"): | 0 | 2023-11-17 06:21:18+00:00 | 2k |
Zaloog/kanban-python | src/kanban_python/interface.py | [
{
"identifier": "cfg",
"path": "src/kanban_python/config.py",
"snippet": "class KanbanConfig:\n def __init__(self, path=CONFIG_FILE_PATH) -> None:\n def __repr__(self) -> str:\n def save(self):\n def config(self) -> configparser.ConfigParser:\n def active_board(self) -> str:\n def acti... | import calendar
from datetime import datetime
from itertools import zip_longest
from rich.prompt import Confirm, IntPrompt, Prompt
from rich.table import Table
from .config import cfg
from .constants import (
BOARD_CAPTION_STRING,
COLOR_DICT,
CONFIG_FILE_PATH,
FOOTER,
REPORT_COLORS,
)
from .utils import (
calculate_days_left_till_due,
calculate_time_delta_str,
check_due_date_format,
console,
create_color_mapping,
create_dict_for_report_view,
create_status_dict_for_rows,
current_time_to_str,
due_date_date_to_datetime,
due_date_datetime_to_date,
) | 1,429 |
# Board
#####################################################################################
def create_table(data: dict) -> Table:
status_dict = create_status_dict_for_rows(data=data, vis_cols=cfg.vis_cols)
table_name = cfg.active_board
table = Table(
title=f"[blue]Active Board: {table_name}[/]",
highlight=True,
show_header=True,
show_footer=True if cfg.show_footer == "True" else False,
caption=BOARD_CAPTION_STRING,
)
for i, category in enumerate([COLOR_DICT.get(col, col) for col in cfg.vis_cols]):
table.add_column(
header=category + f"\t({len(status_dict[cfg.vis_cols[i]])} Task/s)",
header_style="bold",
justify="left",
overflow="fold",
footer=FOOTER[0]
if i == 0
else FOOTER[1]
if i == len(cfg.vis_cols) - 1
else "",
min_width=cfg.col_min_width,
)
for row_tasks in zip_longest(*status_dict.values()):
table.add_row(*row_tasks)
return table
# Board Action selection
def input_ask_for_action():
|
# Board
#####################################################################################
def create_table(data: dict) -> Table:
status_dict = create_status_dict_for_rows(data=data, vis_cols=cfg.vis_cols)
table_name = cfg.active_board
table = Table(
title=f"[blue]Active Board: {table_name}[/]",
highlight=True,
show_header=True,
show_footer=True if cfg.show_footer == "True" else False,
caption=BOARD_CAPTION_STRING,
)
for i, category in enumerate([COLOR_DICT.get(col, col) for col in cfg.vis_cols]):
table.add_column(
header=category + f"\t({len(status_dict[cfg.vis_cols[i]])} Task/s)",
header_style="bold",
justify="left",
overflow="fold",
footer=FOOTER[0]
if i == 0
else FOOTER[1]
if i == len(cfg.vis_cols) - 1
else "",
min_width=cfg.col_min_width,
)
for row_tasks in zip_longest(*status_dict.values()):
table.add_row(*row_tasks)
return table
# Board Action selection
def input_ask_for_action(): | console.print( | 6 | 2023-11-11 14:43:55+00:00 | 2k |
AMAAI-Lab/mustango | audioldm/latent_diffusion/ddim.py | [
{
"identifier": "make_ddim_sampling_parameters",
"path": "audioldm/latent_diffusion/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 = n... | import torch
import numpy as np
from tqdm import tqdm
from audioldm.latent_diffusion.util import (
make_ddim_sampling_parameters,
make_ddim_timesteps,
noise_like,
extract_into_tensor,
) | 1,266 | """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) == torch.Tensor:
if attr.device != torch.device("cuda"):
attr = attr.to(torch.device("cuda"))
setattr(self, name, attr)
def make_schedule(
self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0.0, verbose=True
):
self.ddim_timesteps = make_ddim_timesteps(
ddim_discr_method=ddim_discretize,
num_ddim_timesteps=ddim_num_steps,
num_ddpm_timesteps=self.ddpm_num_timesteps,
verbose=verbose,
)
alphas_cumprod = self.model.alphas_cumprod
assert (
alphas_cumprod.shape[0] == self.ddpm_num_timesteps
), "alphas have to be defined for each timestep"
to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
self.register_buffer("betas", to_torch(self.model.betas))
self.register_buffer("alphas_cumprod", to_torch(alphas_cumprod))
self.register_buffer(
"alphas_cumprod_prev", to_torch(self.model.alphas_cumprod_prev)
)
# calculations for diffusion q(x_t | x_{t-1}) and others
self.register_buffer(
"sqrt_alphas_cumprod", to_torch(np.sqrt(alphas_cumprod.cpu()))
)
self.register_buffer(
"sqrt_one_minus_alphas_cumprod",
to_torch(np.sqrt(1.0 - alphas_cumprod.cpu())),
)
self.register_buffer(
"log_one_minus_alphas_cumprod", to_torch(np.log(1.0 - alphas_cumprod.cpu()))
)
self.register_buffer(
"sqrt_recip_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod.cpu()))
)
self.register_buffer(
"sqrt_recipm1_alphas_cumprod",
to_torch(np.sqrt(1.0 / alphas_cumprod.cpu() - 1)),
)
# ddim sampling parameters
| """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) == torch.Tensor:
if attr.device != torch.device("cuda"):
attr = attr.to(torch.device("cuda"))
setattr(self, name, attr)
def make_schedule(
self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0.0, verbose=True
):
self.ddim_timesteps = make_ddim_timesteps(
ddim_discr_method=ddim_discretize,
num_ddim_timesteps=ddim_num_steps,
num_ddpm_timesteps=self.ddpm_num_timesteps,
verbose=verbose,
)
alphas_cumprod = self.model.alphas_cumprod
assert (
alphas_cumprod.shape[0] == self.ddpm_num_timesteps
), "alphas have to be defined for each timestep"
to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
self.register_buffer("betas", to_torch(self.model.betas))
self.register_buffer("alphas_cumprod", to_torch(alphas_cumprod))
self.register_buffer(
"alphas_cumprod_prev", to_torch(self.model.alphas_cumprod_prev)
)
# calculations for diffusion q(x_t | x_{t-1}) and others
self.register_buffer(
"sqrt_alphas_cumprod", to_torch(np.sqrt(alphas_cumprod.cpu()))
)
self.register_buffer(
"sqrt_one_minus_alphas_cumprod",
to_torch(np.sqrt(1.0 - alphas_cumprod.cpu())),
)
self.register_buffer(
"log_one_minus_alphas_cumprod", to_torch(np.log(1.0 - alphas_cumprod.cpu()))
)
self.register_buffer(
"sqrt_recip_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod.cpu()))
)
self.register_buffer(
"sqrt_recipm1_alphas_cumprod",
to_torch(np.sqrt(1.0 / alphas_cumprod.cpu() - 1)),
)
# ddim sampling parameters | ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters( | 0 | 2023-11-14 23:29:31+00:00 | 2k |
lxmusics/lx-music-api-server-python | modules/kg/search.py | [
{
"identifier": "Httpx",
"path": "common/Httpx.py",
"snippet": "def is_valid_utf8(text):\ndef is_plain_text(text):\ndef convert_dict_to_form_string(dic):\ndef log_plaintext(text):\ndef request(url, options = {}):\n def _json():\ndef checkcn():\n def __init__(self, status, content, headers):\n d... | from common import Httpx
from common import utils
from common.exceptions import FailedException
from .utils import buildRequestParams | 1,189 | # ----------------------------------------
# - mode: python -
# - author: helloplhm-qwq -
# - name: search.py -
# - project: lx-music-api-server -
# - license: MIT -
# ----------------------------------------
# This file is part of the "lx-music-api-server" project.
def formatSubResult(l):
res = []
for songinfo in l:
fileinfo = {}
if (songinfo['FileSize'] != 0):
fileinfo['128k'] = {
'hash': songinfo['FileHash'],
'size': utils.sizeFormat(songinfo['FileSize']),
}
if (songinfo['HQFileSize'] != 0):
fileinfo['320k'] = {
'hash': songinfo['HQFileHash'],
'size': utils.sizeFormat(songinfo['HQFileSize']),
}
if (songinfo['SQFileSize'] != 0):
fileinfo['flac'] = {
'hash': songinfo['SQFileHash'],
'size': utils.sizeFormat(songinfo['SQFileSize']),
}
if (songinfo['ResFileSize'] != 0):
fileinfo['flac24bit'] = {
'hash': songinfo['ResFileHash'],
'size': utils.sizeFormat(songinfo['ResFileSize']),
}
res.append({
'name': songinfo['SongName'],
'name_ori': songinfo['OriSongName'],
'name_extra': songinfo['SongName'].replace(songinfo['OriSongName'], ''),
'singer': songinfo['SingerName'],
'singer_list': [{'name': i['name'], 'id': i['id']} for i in songinfo['Singers']],
'isoriginal': True if (songinfo['IsOriginal'] == 1) else False,
'tag': songinfo.get('TagContent') if songinfo.get('TagContent') else '',
'format_length': utils.timeLengthFormat(songinfo['Duration']),
'length': songinfo['Duration'],
'hash': songinfo['FileHash'],
'file_info': fileinfo,
'songmid': songinfo['Audioid'],
'album_id': songinfo['AlbumID'],
'album': songinfo['AlbumName'],
'language': songinfo['trans_param'].get('language') if songinfo['trans_param'] else '',
'cover': songinfo['Image'].format(size = 1080),
'sizable_cover': songinfo['Image'],
'mvid': songinfo['MvHash'],
})
return res
async def getSongSearchResult(query, page, size):
req = await Httpx.AsyncRequest(utils.encodeURI(f'https://songsearch.kugou.com/song_search_v2?' + buildRequestParams({
"keyword": query,
"page": page,
"pagesize": size,
"userid": 0,
"clientver": "",
"platform": "WebFilter",
"filter": 2,
"iscorrection": 1,
"privilege_filter": 0
})), {
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.142.86 Safari/537.36",
"Referer": "https://www.kugou.com",
}
})
body = req.json()
if (body['status'] != 1):
| # ----------------------------------------
# - mode: python -
# - author: helloplhm-qwq -
# - name: search.py -
# - project: lx-music-api-server -
# - license: MIT -
# ----------------------------------------
# This file is part of the "lx-music-api-server" project.
def formatSubResult(l):
res = []
for songinfo in l:
fileinfo = {}
if (songinfo['FileSize'] != 0):
fileinfo['128k'] = {
'hash': songinfo['FileHash'],
'size': utils.sizeFormat(songinfo['FileSize']),
}
if (songinfo['HQFileSize'] != 0):
fileinfo['320k'] = {
'hash': songinfo['HQFileHash'],
'size': utils.sizeFormat(songinfo['HQFileSize']),
}
if (songinfo['SQFileSize'] != 0):
fileinfo['flac'] = {
'hash': songinfo['SQFileHash'],
'size': utils.sizeFormat(songinfo['SQFileSize']),
}
if (songinfo['ResFileSize'] != 0):
fileinfo['flac24bit'] = {
'hash': songinfo['ResFileHash'],
'size': utils.sizeFormat(songinfo['ResFileSize']),
}
res.append({
'name': songinfo['SongName'],
'name_ori': songinfo['OriSongName'],
'name_extra': songinfo['SongName'].replace(songinfo['OriSongName'], ''),
'singer': songinfo['SingerName'],
'singer_list': [{'name': i['name'], 'id': i['id']} for i in songinfo['Singers']],
'isoriginal': True if (songinfo['IsOriginal'] == 1) else False,
'tag': songinfo.get('TagContent') if songinfo.get('TagContent') else '',
'format_length': utils.timeLengthFormat(songinfo['Duration']),
'length': songinfo['Duration'],
'hash': songinfo['FileHash'],
'file_info': fileinfo,
'songmid': songinfo['Audioid'],
'album_id': songinfo['AlbumID'],
'album': songinfo['AlbumName'],
'language': songinfo['trans_param'].get('language') if songinfo['trans_param'] else '',
'cover': songinfo['Image'].format(size = 1080),
'sizable_cover': songinfo['Image'],
'mvid': songinfo['MvHash'],
})
return res
async def getSongSearchResult(query, page, size):
req = await Httpx.AsyncRequest(utils.encodeURI(f'https://songsearch.kugou.com/song_search_v2?' + buildRequestParams({
"keyword": query,
"page": page,
"pagesize": size,
"userid": 0,
"clientver": "",
"platform": "WebFilter",
"filter": 2,
"iscorrection": 1,
"privilege_filter": 0
})), {
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.142.86 Safari/537.36",
"Referer": "https://www.kugou.com",
}
})
body = req.json()
if (body['status'] != 1): | raise FailedException('歌曲搜索失败') | 2 | 2023-11-10 13:16:30+00:00 | 2k |
ai-forever/Kandinsky-3 | kandinsky3/model/nn.py | [
{
"identifier": "exist",
"path": "kandinsky3/model/utils.py",
"snippet": "def exist(item):\n return item is not None"
},
{
"identifier": "set_default_layer",
"path": "kandinsky3/model/utils.py",
"snippet": "def set_default_layer(condition, layer_1, args_1=[], kwargs_1={}, layer_2=Iden... | import math
import torch
from torch import nn, einsum
from einops import rearrange, repeat
from .utils import exist, set_default_layer | 757 |
class Identity(nn.Module):
def __init__(self, *args, **kwargs):
super().__init__()
@staticmethod
def forward(x, *args, **kwargs):
return x
class SinusoidalPosEmb(nn.Module):
def __init__(self, dim):
super().__init__()
self.dim = dim
def forward(self, x):
half_dim = self.dim // 2
emb = math.log(10000) / (half_dim - 1)
emb = torch.exp(torch.arange(half_dim, device=x.device) * -emb)
emb = rearrange(x, 'i -> i 1') * rearrange(emb, 'j -> 1 j')
return torch.cat((emb.sin(), emb.cos()), dim=-1)
class ConditionalGroupNorm(nn.Module):
def __init__(self, groups, normalized_shape, context_dim):
super().__init__()
self.norm = nn.GroupNorm(groups, normalized_shape, affine=False)
self.context_mlp = nn.Sequential(
nn.SiLU(),
nn.Linear(context_dim, 2 * normalized_shape)
)
self.context_mlp[1].weight.data.zero_()
self.context_mlp[1].bias.data.zero_()
def forward(self, x, context):
context = self.context_mlp(context)
ndims = ' 1' * len(x.shape[2:])
context = rearrange(context, f'b c -> b c{ndims}')
scale, shift = context.chunk(2, dim=1)
x = self.norm(x) * (scale + 1.) + shift
return x
class Attention(nn.Module):
def __init__(self, in_channels, out_channels, context_dim, head_dim=64):
super().__init__()
assert out_channels % head_dim == 0
self.num_heads = out_channels // head_dim
self.scale = head_dim ** -0.5
self.to_query = nn.Linear(in_channels, out_channels, bias=False)
self.to_key = nn.Linear(context_dim, out_channels, bias=False)
self.to_value = nn.Linear(context_dim, out_channels, bias=False)
self.output_layer = nn.Linear(out_channels, out_channels, bias=False)
def forward(self, x, context, context_mask=None):
query = rearrange(self.to_query(x), 'b n (h d) -> b h n d', h=self.num_heads)
key = rearrange(self.to_key(context), 'b n (h d) -> b h n d', h=self.num_heads)
value = rearrange(self.to_value(context), 'b n (h d) -> b h n d', h=self.num_heads)
attention_matrix = einsum('b h i d, b h j d -> b h i j', query, key) * self.scale
|
class Identity(nn.Module):
def __init__(self, *args, **kwargs):
super().__init__()
@staticmethod
def forward(x, *args, **kwargs):
return x
class SinusoidalPosEmb(nn.Module):
def __init__(self, dim):
super().__init__()
self.dim = dim
def forward(self, x):
half_dim = self.dim // 2
emb = math.log(10000) / (half_dim - 1)
emb = torch.exp(torch.arange(half_dim, device=x.device) * -emb)
emb = rearrange(x, 'i -> i 1') * rearrange(emb, 'j -> 1 j')
return torch.cat((emb.sin(), emb.cos()), dim=-1)
class ConditionalGroupNorm(nn.Module):
def __init__(self, groups, normalized_shape, context_dim):
super().__init__()
self.norm = nn.GroupNorm(groups, normalized_shape, affine=False)
self.context_mlp = nn.Sequential(
nn.SiLU(),
nn.Linear(context_dim, 2 * normalized_shape)
)
self.context_mlp[1].weight.data.zero_()
self.context_mlp[1].bias.data.zero_()
def forward(self, x, context):
context = self.context_mlp(context)
ndims = ' 1' * len(x.shape[2:])
context = rearrange(context, f'b c -> b c{ndims}')
scale, shift = context.chunk(2, dim=1)
x = self.norm(x) * (scale + 1.) + shift
return x
class Attention(nn.Module):
def __init__(self, in_channels, out_channels, context_dim, head_dim=64):
super().__init__()
assert out_channels % head_dim == 0
self.num_heads = out_channels // head_dim
self.scale = head_dim ** -0.5
self.to_query = nn.Linear(in_channels, out_channels, bias=False)
self.to_key = nn.Linear(context_dim, out_channels, bias=False)
self.to_value = nn.Linear(context_dim, out_channels, bias=False)
self.output_layer = nn.Linear(out_channels, out_channels, bias=False)
def forward(self, x, context, context_mask=None):
query = rearrange(self.to_query(x), 'b n (h d) -> b h n d', h=self.num_heads)
key = rearrange(self.to_key(context), 'b n (h d) -> b h n d', h=self.num_heads)
value = rearrange(self.to_value(context), 'b n (h d) -> b h n d', h=self.num_heads)
attention_matrix = einsum('b h i d, b h j d -> b h i j', query, key) * self.scale | if exist(context_mask): | 0 | 2023-11-13 10:16:04+00:00 | 2k |
spfrommer/torchexplorer | torchexplorer/render/structs.py | [
{
"identifier": "Tooltip",
"path": "torchexplorer/components/tooltip.py",
"snippet": "class Tooltip:\n \"\"\"The tooltip that pops up next to a Module.\"\"\"\n\n def __init__(self, title: str, keys: list[str], vals: list[str]):\n self.title = title\n self.keys = keys\n self.va... | from typing import Optional
from dataclasses import dataclass, field
from torchexplorer.components.tooltip import Tooltip
from torchexplorer.core import (
ModuleInvocationHistograms, ModuleSharedHistograms
) | 1,250 | from __future__ import annotations
@dataclass
class EdgeLayout:
path_points: list[list[float]]
arrowhead_points: list[list[float]]
downstream_input_index: Optional[int]
upstream_output_index: Optional[int]
@dataclass
class TooltipLayout:
tooltip: Tooltip
# Coordinates in parent of the layout this tooltip belongs to
bottom_left_corner: list[float] = field(default_factory=lambda: [0, 0])
top_right_corner: list[float] = field(default_factory=lambda: [0, 0])
# Either a specific module invocation or for IO
@dataclass
class NodeLayout:
display_name: Optional[str] = None
tooltip: Optional[TooltipLayout] = None
invocation_hists: Optional[ModuleInvocationHistograms] = None
invocation_grad_hists: Optional[ModuleInvocationHistograms] = None
| from __future__ import annotations
@dataclass
class EdgeLayout:
path_points: list[list[float]]
arrowhead_points: list[list[float]]
downstream_input_index: Optional[int]
upstream_output_index: Optional[int]
@dataclass
class TooltipLayout:
tooltip: Tooltip
# Coordinates in parent of the layout this tooltip belongs to
bottom_left_corner: list[float] = field(default_factory=lambda: [0, 0])
top_right_corner: list[float] = field(default_factory=lambda: [0, 0])
# Either a specific module invocation or for IO
@dataclass
class NodeLayout:
display_name: Optional[str] = None
tooltip: Optional[TooltipLayout] = None
invocation_hists: Optional[ModuleInvocationHistograms] = None
invocation_grad_hists: Optional[ModuleInvocationHistograms] = None | shared_hists: Optional[ModuleSharedHistograms] = None | 2 | 2023-11-13 05:56:04+00:00 | 2k |
namin/llm-verified-with-monte-carlo-tree-search | huggingface_generate.py | [
{
"identifier": "STOP_WORD",
"path": "lang_config.py",
"snippet": "STOP_WORD = \"\\n\""
},
{
"identifier": "BASE_MODEL_NAME",
"path": "model_config.py",
"snippet": "BASE_MODEL_NAME = args.base_model_name"
},
{
"identifier": "PEFT_MODEL_PATH",
"path": "model_config.py",
"s... | import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig, AutoTokenizer
from trl import AutoModelForCausalLMWithValueHead
from peft import PeftModel
from lang_config import STOP_WORD
from model_config import BASE_MODEL_NAME, PEFT_MODEL_PATH, PPO_MODEL_PATH, CUSTOM_STOP, SAME_FOR_MANY_SAMPLES, BEAM_SEARCH, MODEL_ARG_TOP_K, MODEL_ARG_TOP_P, MODEL_ARG_TEMP
from typing import List | 812 |
def load_model(
base_model_name: str = BASE_MODEL_NAME,
ppo_model_path: str = PPO_MODEL_PATH,
peft_model_path: str = PEFT_MODEL_PATH,
) -> (AutoModelForCausalLM, PeftModel, AutoTokenizer):
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.float16,
)
if ppo_model_path is None:
base_model = AutoModelForCausalLM.from_pretrained(
base_model_name,
quantization_config=bnb_config,
device_map="auto",
trust_remote_code=True,
use_auth_token=True,
)
tokenizer = AutoTokenizer.from_pretrained(
base_model_name, trust_remote_code=True
)
else:
base_model = AutoModelForCausalLMWithValueHead.from_pretrained(
ppo_model_path, quantization_config=bnb_config
)
tokenizer = AutoTokenizer.from_pretrained(ppo_model_path)
tokenizer.pad_token = tokenizer.eos_token
model = (
PeftModel.from_pretrained(base_model, peft_model_path)
if peft_model_path
else base_model
)
return (base_model, model, tokenizer)
def stop_words_ids(tokenizer: AutoTokenizer) -> List[int]:
# Hack: we want the stop word as it is encoded glued to another word.
stop_word_id = tokenizer.encode("hello" + STOP_WORD, add_special_tokens=False)[-1]
quote_word_id = tokenizer.encode("```", add_special_tokens=False)[-1]
return [stop_word_id, quote_word_id]
def get_model_generation_token_args(
tokenizer: AutoTokenizer, custom_stop: bool = CUSTOM_STOP
):
return dict(
min_length=5,
max_new_tokens=100,
eos_token_id=stop_words_ids(tokenizer)
if custom_stop
else tokenizer.eos_token_id,
pad_token_id=tokenizer.eos_token_id,
)
def get_model_generation_search_args(
num: int,
beam_search: bool = BEAM_SEARCH
):
if beam_search:
return dict(
num_beams=num,
num_beam_groups=num,
diversity_penalty=0.9,
)
else:
return dict(
top_k=MODEL_ARG_TOP_K if MODEL_ARG_TOP_K is not None else 50 if num>1 and not SAME_FOR_MANY_SAMPLES else 7,
|
def load_model(
base_model_name: str = BASE_MODEL_NAME,
ppo_model_path: str = PPO_MODEL_PATH,
peft_model_path: str = PEFT_MODEL_PATH,
) -> (AutoModelForCausalLM, PeftModel, AutoTokenizer):
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.float16,
)
if ppo_model_path is None:
base_model = AutoModelForCausalLM.from_pretrained(
base_model_name,
quantization_config=bnb_config,
device_map="auto",
trust_remote_code=True,
use_auth_token=True,
)
tokenizer = AutoTokenizer.from_pretrained(
base_model_name, trust_remote_code=True
)
else:
base_model = AutoModelForCausalLMWithValueHead.from_pretrained(
ppo_model_path, quantization_config=bnb_config
)
tokenizer = AutoTokenizer.from_pretrained(ppo_model_path)
tokenizer.pad_token = tokenizer.eos_token
model = (
PeftModel.from_pretrained(base_model, peft_model_path)
if peft_model_path
else base_model
)
return (base_model, model, tokenizer)
def stop_words_ids(tokenizer: AutoTokenizer) -> List[int]:
# Hack: we want the stop word as it is encoded glued to another word.
stop_word_id = tokenizer.encode("hello" + STOP_WORD, add_special_tokens=False)[-1]
quote_word_id = tokenizer.encode("```", add_special_tokens=False)[-1]
return [stop_word_id, quote_word_id]
def get_model_generation_token_args(
tokenizer: AutoTokenizer, custom_stop: bool = CUSTOM_STOP
):
return dict(
min_length=5,
max_new_tokens=100,
eos_token_id=stop_words_ids(tokenizer)
if custom_stop
else tokenizer.eos_token_id,
pad_token_id=tokenizer.eos_token_id,
)
def get_model_generation_search_args(
num: int,
beam_search: bool = BEAM_SEARCH
):
if beam_search:
return dict(
num_beams=num,
num_beam_groups=num,
diversity_penalty=0.9,
)
else:
return dict(
top_k=MODEL_ARG_TOP_K if MODEL_ARG_TOP_K is not None else 50 if num>1 and not SAME_FOR_MANY_SAMPLES else 7, | top_p=MODEL_ARG_TOP_P if MODEL_ARG_TOP_P is not None else 0.9, | 8 | 2023-11-11 19:56:04+00:00 | 2k |
BraveGroup/Drive-WM | src/diffusers/utils/constants.py | [
{
"identifier": "dep_version_check",
"path": "src/diffusers/dependency_versions_check.py",
"snippet": "def dep_version_check(pkg, hint=None):\n require_version(deps[pkg], hint)"
},
{
"identifier": "ENV_VARS_TRUE_VALUES",
"path": "src/diffusers/utils/import_utils.py",
"snippet": "ENV_V... | import importlib
import os
from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home
from packaging import version
from ..dependency_versions_check import dep_version_check
from .import_utils import ENV_VARS_TRUE_VALUES, is_peft_available, is_transformers_available | 670 | # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
default_cache_path = HUGGINGFACE_HUB_CACHE
MIN_PEFT_VERSION = "0.6.0"
MIN_TRANSFORMERS_VERSION = "4.34.0"
_CHECK_PEFT = os.environ.get("_CHECK_PEFT", "1") in ENV_VARS_TRUE_VALUES
CONFIG_NAME = "config.json"
WEIGHTS_NAME = "diffusion_pytorch_model.bin"
FLAX_WEIGHTS_NAME = "diffusion_flax_model.msgpack"
ONNX_WEIGHTS_NAME = "model.onnx"
SAFETENSORS_WEIGHTS_NAME = "diffusion_pytorch_model.safetensors"
ONNX_EXTERNAL_WEIGHTS_NAME = "weights.pb"
HUGGINGFACE_CO_RESOLVE_ENDPOINT = os.environ.get("HF_ENDPOINT", "https://huggingface.co")
DIFFUSERS_CACHE = default_cache_path
DIFFUSERS_DYNAMIC_MODULE_NAME = "diffusers_modules"
HF_MODULES_CACHE = os.getenv("HF_MODULES_CACHE", os.path.join(hf_cache_home, "modules"))
DEPRECATED_REVISION_ARGS = ["fp16", "non-ema"]
# Below should be `True` if the current version of `peft` and `transformers` are compatible with
# PEFT backend. Will automatically fall back to PEFT backend if the correct versions of the libraries are
# available.
# For PEFT it is has to be greater than or equal to 0.6.0 and for transformers it has to be greater than or equal to 4.34.0.
_required_peft_version = is_peft_available() and version.parse(
version.parse(importlib.metadata.version("peft")).base_version
) >= version.parse(MIN_PEFT_VERSION)
| # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
default_cache_path = HUGGINGFACE_HUB_CACHE
MIN_PEFT_VERSION = "0.6.0"
MIN_TRANSFORMERS_VERSION = "4.34.0"
_CHECK_PEFT = os.environ.get("_CHECK_PEFT", "1") in ENV_VARS_TRUE_VALUES
CONFIG_NAME = "config.json"
WEIGHTS_NAME = "diffusion_pytorch_model.bin"
FLAX_WEIGHTS_NAME = "diffusion_flax_model.msgpack"
ONNX_WEIGHTS_NAME = "model.onnx"
SAFETENSORS_WEIGHTS_NAME = "diffusion_pytorch_model.safetensors"
ONNX_EXTERNAL_WEIGHTS_NAME = "weights.pb"
HUGGINGFACE_CO_RESOLVE_ENDPOINT = os.environ.get("HF_ENDPOINT", "https://huggingface.co")
DIFFUSERS_CACHE = default_cache_path
DIFFUSERS_DYNAMIC_MODULE_NAME = "diffusers_modules"
HF_MODULES_CACHE = os.getenv("HF_MODULES_CACHE", os.path.join(hf_cache_home, "modules"))
DEPRECATED_REVISION_ARGS = ["fp16", "non-ema"]
# Below should be `True` if the current version of `peft` and `transformers` are compatible with
# PEFT backend. Will automatically fall back to PEFT backend if the correct versions of the libraries are
# available.
# For PEFT it is has to be greater than or equal to 0.6.0 and for transformers it has to be greater than or equal to 4.34.0.
_required_peft_version = is_peft_available() and version.parse(
version.parse(importlib.metadata.version("peft")).base_version
) >= version.parse(MIN_PEFT_VERSION) | _required_transformers_version = is_transformers_available() and version.parse( | 3 | 2023-11-18 01:40:55+00:00 | 2k |
basnijholt/unidep | unidep/_pytest_plugin.py | [
{
"identifier": "find_requirements_files",
"path": "unidep/_dependencies_parsing.py",
"snippet": "def find_requirements_files(\n base_dir: str | Path = \".\",\n depth: int = 1,\n *,\n verbose: bool = False,\n) -> list[Path]:\n \"\"\"Scan a directory for `requirements.yaml` and `pyproject.... | import os
import sys
import pytest
from pathlib import Path
from typing import TYPE_CHECKING
from unidep._dependencies_parsing import (
find_requirements_files,
parse_local_dependencies,
)
from git import Repo | 937 | """unidep - Unified Conda and Pip requirements management.
Pytest plugin for running only tests of changed files.
WARNING: Still experimental and not documented.
"""
from __future__ import annotations
if TYPE_CHECKING:
def pytest_addoption(parser: pytest.Parser) -> None: # pragma: no cover
"""Add options to the pytest command line."""
parser.addoption(
"--run-affected",
action="store_true",
default=False,
help="Run only tests from affected packages",
)
parser.addoption(
"--branch",
action="store",
default="origin/main",
help="Branch to compare with for finding affected tests",
)
parser.addoption(
"--repo-root",
action="store",
default=".",
type=Path,
help="Root of the repository",
)
def pytest_collection_modifyitems(
config: pytest.Config,
items: list[pytest.Item],
) -> None: # pragma: no cover
"""Filter tests based on the --run-affected option."""
if not config.getoption("--run-affected"):
return
try:
except ImportError:
print(
"🛑 You need to install `gitpython` to use the `--run-affected` option."
"run `pip install gitpython` to install it.",
)
sys.exit(1)
compare_branch = config.getoption("--branch")
repo_root = Path(config.getoption("--repo-root")).absolute()
repo = Repo(repo_root)
| """unidep - Unified Conda and Pip requirements management.
Pytest plugin for running only tests of changed files.
WARNING: Still experimental and not documented.
"""
from __future__ import annotations
if TYPE_CHECKING:
def pytest_addoption(parser: pytest.Parser) -> None: # pragma: no cover
"""Add options to the pytest command line."""
parser.addoption(
"--run-affected",
action="store_true",
default=False,
help="Run only tests from affected packages",
)
parser.addoption(
"--branch",
action="store",
default="origin/main",
help="Branch to compare with for finding affected tests",
)
parser.addoption(
"--repo-root",
action="store",
default=".",
type=Path,
help="Root of the repository",
)
def pytest_collection_modifyitems(
config: pytest.Config,
items: list[pytest.Item],
) -> None: # pragma: no cover
"""Filter tests based on the --run-affected option."""
if not config.getoption("--run-affected"):
return
try:
except ImportError:
print(
"🛑 You need to install `gitpython` to use the `--run-affected` option."
"run `pip install gitpython` to install it.",
)
sys.exit(1)
compare_branch = config.getoption("--branch")
repo_root = Path(config.getoption("--repo-root")).absolute()
repo = Repo(repo_root) | found_files = find_requirements_files(repo_root) | 0 | 2023-11-16 04:23:01+00:00 | 2k |
BAAI-DCAI/SegVol | segment_anything_volumetric/modeling/image_encoder.py | [
{
"identifier": "LayerNorm2d",
"path": "segment_anything_volumetric/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 sel... | import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Optional, Tuple, Type
from .common import LayerNorm2d, MLPBlock
from monai.networks.blocks import PatchEmbed | 1,205 | # 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.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa
class ImageEncoderViT(nn.Module):
def __init__(
self,
img_size: int = 1024,
patch_size: int = 16,
in_chans: int = 1,
embed_dim: int = 768,
depth: int = 12,
num_heads: int = 12,
mlp_ratio: float = 4.0,
out_chans: int = 256,
qkv_bias: bool = True,
norm_layer: Type[nn.Module] = nn.LayerNorm,
act_layer: Type[nn.Module] = nn.GELU,
use_abs_pos: bool = True,
use_rel_pos: bool = False,
rel_pos_zero_init: bool = True,
window_size: int = 0,
global_attn_indexes: Tuple[int, ...] = (),
) -> None:
"""
Args:
img_size (int): Input image size.
patch_size (int): Patch size.
in_chans (int): Number of input image channels.
embed_dim (int): Patch embedding dimension.
depth (int): Depth of ViT.
num_heads (int): Number of attention heads in each ViT block.
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
qkv_bias (bool): If True, add a learnable bias to query, key, value.
norm_layer (nn.Module): Normalization layer.
act_layer (nn.Module): Activation layer.
use_abs_pos (bool): If True, use absolute positional embeddings.
use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
window_size (int): Window size for window attention blocks.
global_attn_indexes (list): Indexes for blocks using global attention.
"""
super().__init__()
self.img_size = img_size
# self.patch_embed = PatchEmbed(
# kernel_size=(patch_size, patch_size),
# stride=(patch_size, patch_size),
# in_chans=in_chans,
# embed_dim=embed_dim,
# )
self.patch_embed = PatchEmbed(
patch_size=patch_size,
in_chans=in_chans,
embed_dim=embed_dim,
spatial_dims=3,
)
self.pos_embed: Optional[nn.Parameter] = None
if use_abs_pos:
# Initialize absolute positional embedding with pretrain image size.
self.pos_embed = nn.Parameter(
torch.zeros(1, img_size // patch_size, img_size // patch_size, img_size // patch_size, embed_dim)
)
self.blocks = nn.ModuleList()
for i in range(depth):
block = Block(
dim=embed_dim,
num_heads=num_heads,
mlp_ratio=mlp_ratio,
qkv_bias=qkv_bias,
norm_layer=norm_layer,
act_layer=act_layer,
use_rel_pos=use_rel_pos,
rel_pos_zero_init=rel_pos_zero_init,
window_size=window_size if i not in global_attn_indexes else 0,
input_size=(img_size // patch_size, img_size // patch_size),
)
self.blocks.append(block)
self.neck = nn.Sequential(
nn.Conv2d(
embed_dim,
out_chans,
kernel_size=1,
bias=False,
),
| # 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.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa
class ImageEncoderViT(nn.Module):
def __init__(
self,
img_size: int = 1024,
patch_size: int = 16,
in_chans: int = 1,
embed_dim: int = 768,
depth: int = 12,
num_heads: int = 12,
mlp_ratio: float = 4.0,
out_chans: int = 256,
qkv_bias: bool = True,
norm_layer: Type[nn.Module] = nn.LayerNorm,
act_layer: Type[nn.Module] = nn.GELU,
use_abs_pos: bool = True,
use_rel_pos: bool = False,
rel_pos_zero_init: bool = True,
window_size: int = 0,
global_attn_indexes: Tuple[int, ...] = (),
) -> None:
"""
Args:
img_size (int): Input image size.
patch_size (int): Patch size.
in_chans (int): Number of input image channels.
embed_dim (int): Patch embedding dimension.
depth (int): Depth of ViT.
num_heads (int): Number of attention heads in each ViT block.
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
qkv_bias (bool): If True, add a learnable bias to query, key, value.
norm_layer (nn.Module): Normalization layer.
act_layer (nn.Module): Activation layer.
use_abs_pos (bool): If True, use absolute positional embeddings.
use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
window_size (int): Window size for window attention blocks.
global_attn_indexes (list): Indexes for blocks using global attention.
"""
super().__init__()
self.img_size = img_size
# self.patch_embed = PatchEmbed(
# kernel_size=(patch_size, patch_size),
# stride=(patch_size, patch_size),
# in_chans=in_chans,
# embed_dim=embed_dim,
# )
self.patch_embed = PatchEmbed(
patch_size=patch_size,
in_chans=in_chans,
embed_dim=embed_dim,
spatial_dims=3,
)
self.pos_embed: Optional[nn.Parameter] = None
if use_abs_pos:
# Initialize absolute positional embedding with pretrain image size.
self.pos_embed = nn.Parameter(
torch.zeros(1, img_size // patch_size, img_size // patch_size, img_size // patch_size, embed_dim)
)
self.blocks = nn.ModuleList()
for i in range(depth):
block = Block(
dim=embed_dim,
num_heads=num_heads,
mlp_ratio=mlp_ratio,
qkv_bias=qkv_bias,
norm_layer=norm_layer,
act_layer=act_layer,
use_rel_pos=use_rel_pos,
rel_pos_zero_init=rel_pos_zero_init,
window_size=window_size if i not in global_attn_indexes else 0,
input_size=(img_size // patch_size, img_size // patch_size),
)
self.blocks.append(block)
self.neck = nn.Sequential(
nn.Conv2d(
embed_dim,
out_chans,
kernel_size=1,
bias=False,
), | LayerNorm2d(out_chans), | 0 | 2023-11-10 08:25:37+00:00 | 2k |
xk-huang/segment-caption-anything | scripts/tools/utils/git_utils/tsv_io.py | [
{
"identifier": "qd_tqdm",
"path": "scripts/tools/utils/git_utils/common.py",
"snippet": "def qd_tqdm(*args, **kwargs):\n desc = kwargs.get(\"desc\", \"\")\n import inspect\n\n frame = inspect.currentframe()\n frames = inspect.getouterframes(frame)\n frame = frames[1].frame\n line_numb... | import numpy as np
import shutil
import mmap
import time
import logging
import types
import os
import os.path as op
import subprocess
import tempfile
import hashlib
import logging
import struct
from .common import qd_tqdm as tqdm
from .common import (
dict_update_path_value,
dict_get_path_value,
get_all_path,
load_from_yaml_str,
)
from azfuse import File
from contextlib import contextmanager
from datasets.utils.filelock import FileLock
from urllib.parse import urlparse, urlunparse
from pathos.multiprocessing import ProcessingPool as Pool | 1,305 |
# NOTE(xiaoke): Modified. Try to use azfuse.File if possible.
try:
except ImportError:
File = types.SimpleNamespace()
File.open = open
File.get_file_size = lambda x: os.stat(x).st_size
logger = logging.getLogger(__name__)
def concat_files(ins, out):
File.prepare(ins)
with File.open(out, "wb") as fp_out:
for i, f in enumerate(ins):
logging.info("concating {}/{} - {}".format(i, len(ins), f))
with File.open(f, "rb") as fp_in:
shutil.copyfileobj(fp_in, fp_out, 1024 * 1024 * 10)
def concat_tsv_files(tsvs, out_tsv):
if len(tsvs) == 1 and tsvs[0] == out_tsv:
return
File.prepare(tsvs)
concat_files(tsvs, out_tsv)
sizes = [File.get_file_size(t) for t in tsvs]
sizes = np.cumsum(sizes)
sizes = [0] + sizes[:-1].tolist()
concate_lineidx_8b(sizes, tsvs, out_tsv)
def get_tmp_folder():
folder = os.environ.get("GIT_TMP_FOLDER", "/tmp")
return folder
def parallel_map(func, all_task, num_worker=16):
if num_worker > 0:
with Pool(num_worker) as m:
result = m.map(func, all_task)
return result
else:
result = []
for t in all_task:
result.append(func(t))
return result
def ensure_remove_file(d):
if op.isfile(d) or op.islink(d):
try:
os.remove(d)
except:
pass
def concate_lineidx_8b(sizes, tsvs, out_tsv):
File.prepare(tsvs)
folder = get_tmp_folder()
def row_processor_8b(row):
offset, in_tsv, out_tsv = row
|
# NOTE(xiaoke): Modified. Try to use azfuse.File if possible.
try:
except ImportError:
File = types.SimpleNamespace()
File.open = open
File.get_file_size = lambda x: os.stat(x).st_size
logger = logging.getLogger(__name__)
def concat_files(ins, out):
File.prepare(ins)
with File.open(out, "wb") as fp_out:
for i, f in enumerate(ins):
logging.info("concating {}/{} - {}".format(i, len(ins), f))
with File.open(f, "rb") as fp_in:
shutil.copyfileobj(fp_in, fp_out, 1024 * 1024 * 10)
def concat_tsv_files(tsvs, out_tsv):
if len(tsvs) == 1 and tsvs[0] == out_tsv:
return
File.prepare(tsvs)
concat_files(tsvs, out_tsv)
sizes = [File.get_file_size(t) for t in tsvs]
sizes = np.cumsum(sizes)
sizes = [0] + sizes[:-1].tolist()
concate_lineidx_8b(sizes, tsvs, out_tsv)
def get_tmp_folder():
folder = os.environ.get("GIT_TMP_FOLDER", "/tmp")
return folder
def parallel_map(func, all_task, num_worker=16):
if num_worker > 0:
with Pool(num_worker) as m:
result = m.map(func, all_task)
return result
else:
result = []
for t in all_task:
result.append(func(t))
return result
def ensure_remove_file(d):
if op.isfile(d) or op.islink(d):
try:
os.remove(d)
except:
pass
def concate_lineidx_8b(sizes, tsvs, out_tsv):
File.prepare(tsvs)
folder = get_tmp_folder()
def row_processor_8b(row):
offset, in_tsv, out_tsv = row | fbar = tqdm(unit_scale=True) | 1 | 2023-11-17 14:10:41+00:00 | 2k |
fjzzq2002/is-my-problem-new | src/scrapper/codeforces.py | [
{
"identifier": "read_problems",
"path": "src/utils.py",
"snippet": "def read_problems(filename):\n # read as a json\n with open(filename) as f:\n problems = json.load(f)\n return [x for x in problems if len(x[\"statement\"].strip()) >= 5]"
},
{
"identifier": "dump_json_safe"... | from ..utils import read_problems, dump_json_safe, get_text
from bs4 import BeautifulSoup
from tqdm.auto import tqdm
import json
import os
import requests
import time
import random | 992 |
scrapped_problems = []
try:
scrapped_problems = read_problems("problems/codeforces.json")
print(f"Recalled {len(scrapped_problems)} scrapped problems")
except:
print("Cannot find scrapped problems")
scrapped_uids = set(p["uid"] for p in scrapped_problems)
codeforces_endpoint = "https://codeforces.com/api/problemset.problems"
# get list of problems
list_problems = requests.get(codeforces_endpoint).json()["result"]["problems"]
# the website is down, read problems.txt instead
# with open('problems.txt') as f:
# list_problems = json.load(f)['result']['problems']
print("# problems:", len(list_problems))
# a scrapper for codeforces
def scrap_problem(contestId, index, rating, tags, uid):
url = f"https://codeforces.com/contest/{contestId}/problem/{index}"
response = requests.get(url, timeout=30)
soup = BeautifulSoup(response.content, "html.parser")
statement = soup.find(class_="problem-statement")
try:
statement.find(class_="header").decompose()
except:
pass
statement_body = statement.find("div")
statement_body = get_text(statement_body)
# \r -> \n, remove duplicate \n, strip
statement_body = (
statement_body.replace("\r", "\n")
.replace("\n\n", "\n")
.replace("$$$", "$")
.strip()
)
problem = {
"uid": uid,
"url": url,
"tags": tags,
# 'raw': str(response.content),
"statement": statement_body,
"contestId": contestId,
"index": index,
"rating": rating,
}
return problem
for problem in tqdm(list_problems):
contestId, index, rating, tags = (
problem["contestId"],
problem["index"],
problem.get("rating", -1),
problem["tags"],
)
uid = f"Codeforces{contestId}{index}"
if uid in scrapped_uids:
continue
print(f"Scrapping {uid}")
result = None
try:
result = scrap_problem(contestId, index, rating, tags, uid)
except Exception as e:
print("Error while scrapping:", e)
if result is not None:
scrapped_problems.append(result)
time.sleep(0.1)
# save to file every 10 problems
if random.random() < 0.1:
|
scrapped_problems = []
try:
scrapped_problems = read_problems("problems/codeforces.json")
print(f"Recalled {len(scrapped_problems)} scrapped problems")
except:
print("Cannot find scrapped problems")
scrapped_uids = set(p["uid"] for p in scrapped_problems)
codeforces_endpoint = "https://codeforces.com/api/problemset.problems"
# get list of problems
list_problems = requests.get(codeforces_endpoint).json()["result"]["problems"]
# the website is down, read problems.txt instead
# with open('problems.txt') as f:
# list_problems = json.load(f)['result']['problems']
print("# problems:", len(list_problems))
# a scrapper for codeforces
def scrap_problem(contestId, index, rating, tags, uid):
url = f"https://codeforces.com/contest/{contestId}/problem/{index}"
response = requests.get(url, timeout=30)
soup = BeautifulSoup(response.content, "html.parser")
statement = soup.find(class_="problem-statement")
try:
statement.find(class_="header").decompose()
except:
pass
statement_body = statement.find("div")
statement_body = get_text(statement_body)
# \r -> \n, remove duplicate \n, strip
statement_body = (
statement_body.replace("\r", "\n")
.replace("\n\n", "\n")
.replace("$$$", "$")
.strip()
)
problem = {
"uid": uid,
"url": url,
"tags": tags,
# 'raw': str(response.content),
"statement": statement_body,
"contestId": contestId,
"index": index,
"rating": rating,
}
return problem
for problem in tqdm(list_problems):
contestId, index, rating, tags = (
problem["contestId"],
problem["index"],
problem.get("rating", -1),
problem["tags"],
)
uid = f"Codeforces{contestId}{index}"
if uid in scrapped_uids:
continue
print(f"Scrapping {uid}")
result = None
try:
result = scrap_problem(contestId, index, rating, tags, uid)
except Exception as e:
print("Error while scrapping:", e)
if result is not None:
scrapped_problems.append(result)
time.sleep(0.1)
# save to file every 10 problems
if random.random() < 0.1: | dump_json_safe(scrapped_problems, "problems/codeforces.json") | 1 | 2023-11-15 07:58:49+00:00 | 2k |
p0p4k/pflowtts_pytorch | pflow/utils/generate_data_statistics.py | [
{
"identifier": "TextMelDataModule",
"path": "pflow/data/text_mel_datamodule.py",
"snippet": "class TextMelDataModule(LightningDataModule):\n def __init__( # pylint: disable=unused-argument\n self,\n name,\n train_filelist_path,\n valid_filelist_path,\n batch_size,... | import os
import sys
import argparse
import json
import sys
import rootutils
import torch
from pathlib import Path
from hydra import compose, initialize
from omegaconf import open_dict
from tqdm.auto import tqdm
from pflow.data.text_mel_datamodule import TextMelDataModule
from pflow.utils.logging_utils import pylogger | 992 | r"""
The file creates a pickle file where the values needed for loading of dataset is stored and the model can load it
when needed.
Parameters from hparam.py will be used
"""
sys.path.append(os.path.join(os.path.dirname(__file__), "../.."))
| r"""
The file creates a pickle file where the values needed for loading of dataset is stored and the model can load it
when needed.
Parameters from hparam.py will be used
"""
sys.path.append(os.path.join(os.path.dirname(__file__), "../.."))
| log = pylogger.get_pylogger(__name__) | 1 | 2023-11-11 16:08:17+00:00 | 2k |
theroyallab/tabbyAPI | start.py | [
{
"identifier": "convert_args_to_dict",
"path": "args.py",
"snippet": "def convert_args_to_dict(args: argparse.Namespace, parser: argparse.ArgumentParser):\n \"\"\"Broad conversion of surface level arg groups to dictionaries\"\"\"\n\n arg_groups = {}\n for group in parser._action_groups:\n ... | import argparse
import os
import pathlib
import subprocess
from args import convert_args_to_dict, init_argparser
from main import entrypoint | 698 | """Utility to automatically upgrade and start the API"""
def get_requirements_file():
"""Fetches the appropriate requirements file depending on the GPU"""
requirements_name = "requirements-nowheel"
ROCM_PATH = os.environ.get("ROCM_PATH")
CUDA_PATH = os.environ.get("CUDA_PATH")
# TODO: Check if the user has an AMD gpu on windows
if ROCM_PATH:
requirements_name = "requirements-amd"
# Also override env vars for ROCm support on non-supported GPUs
os.environ["ROCM_PATH"] = "/opt/rocm"
os.environ["HSA_OVERRIDE_GFX_VERSION"] = "10.3.0"
os.environ["HCC_AMDGPU_TARGET"] = "gfx1030"
elif CUDA_PATH:
cuda_version = pathlib.Path(CUDA_PATH).name
if "12" in cuda_version:
requirements_name = "requirements"
elif "11" in cuda_version:
requirements_name = "requirements-cu118"
return requirements_name
def add_start_args(parser: argparse.ArgumentParser):
"""Add start script args to the provided parser"""
start_group = parser.add_argument_group("start")
start_group.add_argument(
"-iu",
"--ignore-upgrade",
action="store_true",
help="Ignore requirements upgrade",
)
start_group.add_argument(
"-nw",
"--nowheel",
action="store_true",
help="Don't upgrade wheel dependencies (exllamav2, torch)",
)
if __name__ == "__main__":
subprocess.run(["pip", "-V"])
# Create an argparser and add extra startup script args
parser = init_argparser()
add_start_args(parser)
args = parser.parse_args()
if args.ignore_upgrade:
print("Ignoring pip dependency upgrade due to user request.")
else:
requirements_file = (
"requirements-nowheel" if args.nowheel else get_requirements_file()
)
subprocess.run(["pip", "install", "-U", "-r", f"{requirements_file}.txt"])
# Import entrypoint after installing all requirements
| """Utility to automatically upgrade and start the API"""
def get_requirements_file():
"""Fetches the appropriate requirements file depending on the GPU"""
requirements_name = "requirements-nowheel"
ROCM_PATH = os.environ.get("ROCM_PATH")
CUDA_PATH = os.environ.get("CUDA_PATH")
# TODO: Check if the user has an AMD gpu on windows
if ROCM_PATH:
requirements_name = "requirements-amd"
# Also override env vars for ROCm support on non-supported GPUs
os.environ["ROCM_PATH"] = "/opt/rocm"
os.environ["HSA_OVERRIDE_GFX_VERSION"] = "10.3.0"
os.environ["HCC_AMDGPU_TARGET"] = "gfx1030"
elif CUDA_PATH:
cuda_version = pathlib.Path(CUDA_PATH).name
if "12" in cuda_version:
requirements_name = "requirements"
elif "11" in cuda_version:
requirements_name = "requirements-cu118"
return requirements_name
def add_start_args(parser: argparse.ArgumentParser):
"""Add start script args to the provided parser"""
start_group = parser.add_argument_group("start")
start_group.add_argument(
"-iu",
"--ignore-upgrade",
action="store_true",
help="Ignore requirements upgrade",
)
start_group.add_argument(
"-nw",
"--nowheel",
action="store_true",
help="Don't upgrade wheel dependencies (exllamav2, torch)",
)
if __name__ == "__main__":
subprocess.run(["pip", "-V"])
# Create an argparser and add extra startup script args
parser = init_argparser()
add_start_args(parser)
args = parser.parse_args()
if args.ignore_upgrade:
print("Ignoring pip dependency upgrade due to user request.")
else:
requirements_file = (
"requirements-nowheel" if args.nowheel else get_requirements_file()
)
subprocess.run(["pip", "install", "-U", "-r", f"{requirements_file}.txt"])
# Import entrypoint after installing all requirements
| entrypoint(convert_args_to_dict(args, parser)) | 0 | 2023-11-10 05:54:02+00:00 | 2k |
zorazrw/filco | measure_ctxs.py | [
{
"identifier": "calc_cxmi_score",
"path": "cxmi.py",
"snippet": "def calc_cxmi_score(\n model: AutoModelForSeq2SeqLM,\n tokenizer: AutoTokenizer,\n answer: str,\n base_input: str,\n ctx_input: str,\n apply_sigmoid: bool = False,\n) -> float:\n \"\"\"Compute the CXMI score.\"\"\"\n ... | import argparse
import torch
from nltk.tokenize import sent_tokenize
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
from cxmi import calc_cxmi_score, get_example_inputs
from eval import calc_unigram_f1, has_answer
from utils import load_dataset, write_dataset | 1,119 | """Calculate Scores of Individual Sentences in Retrieved Passages."""
def calc_cxmi(
text: str,
question: str,
answers: list[str],
tokenizer: AutoTokenizer,
model: AutoModelForSeq2SeqLM,
) -> float:
"""Calculate CXMI score for a context text."""
proc_inputs = get_example_inputs(
question=args.prefix + question,
context=text,
answers=answers,
)
cxmi_score = calc_cxmi_score(
model=model,
tokenizer=tokenizer,
answer=proc_inputs["answers"][0],
base_input=proc_inputs["base_input"],
ctx_input=proc_inputs["ctx_input"],
apply_sigmoid=True,
)
return cxmi_score
def main():
"""Run the main context measuring function."""
# load dataset
| """Calculate Scores of Individual Sentences in Retrieved Passages."""
def calc_cxmi(
text: str,
question: str,
answers: list[str],
tokenizer: AutoTokenizer,
model: AutoModelForSeq2SeqLM,
) -> float:
"""Calculate CXMI score for a context text."""
proc_inputs = get_example_inputs(
question=args.prefix + question,
context=text,
answers=answers,
)
cxmi_score = calc_cxmi_score(
model=model,
tokenizer=tokenizer,
answer=proc_inputs["answers"][0],
base_input=proc_inputs["base_input"],
ctx_input=proc_inputs["ctx_input"],
apply_sigmoid=True,
)
return cxmi_score
def main():
"""Run the main context measuring function."""
# load dataset | dataset = load_dataset(args.dataset_path) | 4 | 2023-11-14 21:18:30+00:00 | 2k |
ShipBit/wingman-ai | gui/views/context_view.py | [
{
"identifier": "ContextSwitcher",
"path": "gui/sections/context_switcher.py",
"snippet": "class ContextSwitcher(ctk.CTkFrame):\n# class ContextSwitcher(ctk.CTkScrollableFrame):\n def __init__(self, master, **kwargs):\n super().__init__(master, **kwargs)\n self.grid_columnconfigure(0, w... | import customtkinter as ctk
from gui.sections.context_switcher import ContextSwitcher
from gui.sections.context_runner import ContextRunner | 1,580 |
class ContextView(ctk.CTkFrame):
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.core = master.core
self.grid_columnconfigure(1, weight=1)
self.grid_rowconfigure(0, weight=1)
|
class ContextView(ctk.CTkFrame):
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.core = master.core
self.grid_columnconfigure(1, weight=1)
self.grid_rowconfigure(0, weight=1)
| self.context_switcher = ContextSwitcher(self, width=88, corner_radius=0) | 0 | 2023-11-15 09:36:06+00:00 | 2k |
OliverMao/FlaskAutoApiBuilder | demo/app.py | [
{
"identifier": "Faab",
"path": "Faab/Faab.py",
"snippet": "class Faab(Flask):\n _startup_message_printed = False\n models = []\n db_config = object()\n need_register_bp = []\n\n def __init__(self, **options):\n # 初始化函数,接收一个字符串类型的参数import_name\n super().__init__(**options)\n... | from Faab import Faab
from Faab.FaabJWT import jwt_authentication
from blueprints.test import test_bp
from blueprints.test.model import Users
import factory as fac | 1,300 | # Faab Project Demo
class DBConfig(object):
# 基础配置
user = 'faab'
host = 'localhost'
password = 'faab'
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://%s:%s@%s:3306/%s' % (user, password, host, 'faab')
SQLALCHEMY_BINDS = {
'test': 'mysql+pymysql://%s:%s@%s:3306/%s' % (user, password, host, 'test')
}
SECRET_KEY = 'session_key'
models = [
[
{
"model": Users,
"bp": test_bp,
"url_prefix": "Users"
}
]
]
app = Faab(import_name=__name__, static_url_path='/s')
app.add_models(models)
app.add_db_config(DBConfig)
fac.register(app)
app.faab_ready()
application = app # uWSGI启动必须有application
@app.before_request
def auth():
| # Faab Project Demo
class DBConfig(object):
# 基础配置
user = 'faab'
host = 'localhost'
password = 'faab'
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://%s:%s@%s:3306/%s' % (user, password, host, 'faab')
SQLALCHEMY_BINDS = {
'test': 'mysql+pymysql://%s:%s@%s:3306/%s' % (user, password, host, 'test')
}
SECRET_KEY = 'session_key'
models = [
[
{
"model": Users,
"bp": test_bp,
"url_prefix": "Users"
}
]
]
app = Faab(import_name=__name__, static_url_path='/s')
app.add_models(models)
app.add_db_config(DBConfig)
fac.register(app)
app.faab_ready()
application = app # uWSGI启动必须有application
@app.before_request
def auth(): | jwt_authentication() | 1 | 2023-11-10 09:25:44+00:00 | 2k |
leeyuentuen/polestar_api | custom_components/polestar_api/pypolestar/polestar.py | [
{
"identifier": "PolestarAuth",
"path": "custom_components/polestar_api/pypolestar/auth.py",
"snippet": "class PolestarAuth:\n \"\"\"base class for Polestar authentication.\"\"\"\n\n def __init__(self, username: str, password: str) -> None:\n \"\"\"Initialize the Polestar authentication.\"\... | from datetime import datetime, timedelta
from .auth import PolestarAuth
from .const import BATTERY_DATA, CACHE_TIME, CAR_INFO_DATA, ODO_METER_DATA
from .exception import (
PolestarApiException,
PolestarAuthException,
PolestarNoDataException,
PolestarNotAuthorizedException,
)
import logging
import httpx | 1,584 | """Asynchronous Python client for the Polestar API."""""
_LOGGER = logging.getLogger(__name__)
class PolestarApi:
"""Main class for handling connections with the Polestar API."""
def __init__(self, username: str, password: str) -> None:
"""Initialize the Polestar API."""
| """Asynchronous Python client for the Polestar API."""""
_LOGGER = logging.getLogger(__name__)
class PolestarApi:
"""Main class for handling connections with the Polestar API."""
def __init__(self, username: str, password: str) -> None:
"""Initialize the Polestar API.""" | self.auth = PolestarAuth(username, password) | 0 | 2023-11-17 21:24:36+00:00 | 2k |
dubverse-ai/MahaTTS | maha_tts/models/autoregressive.py | [
{
"identifier": "config",
"path": "maha_tts/config.py",
"snippet": "class config:\n \n semantic_model_centroids = 10000 + 1\n seed_value = 3407\n\n # Text to Semantic\n t2s_position = 4096\n langs = ['english','tamil', 'telugu', 'punjabi', 'marathi', 'hindi', 'gujarati', 'bengali', 'assa... | import os,sys
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import functools
from typing import Any
from torch.utils.data import Dataset,DataLoader
from transformers import GPT2Tokenizer,GPT2Config, GPT2Model, GPT2LMHeadModel
from tqdm import tqdm
from maha_tts.config import config
from maha_tts.text.symbols import labels,code_labels,text_labels,text_labels_en
from maha_tts.models.modules import GST | 919 | '''
Inspiration taken from https://github.com/neonbjb/tortoise-tts/blob/main/tortoise/models/autoregressive.py
'''
def null_position_embeddings(range, dim):
return torch.zeros((range.shape[0], range.shape[1], dim), device=range.device)
class TS_model(nn.Module):
def __init__(self,n_embed = 512, n_layer = 16, n_head = 8, n_positions = 2048, name='Smolie-in'):
super(TS_model,self).__init__()
self.vocab_size=len(labels)
self.n_positions=n_positions
self.n_embed=n_embed
self.n_layer=n_layer
self.n_head=n_head
self.name=name
self.config = GPT2Config(vocab_size=self.vocab_size,n_positions=self.n_positions,n_embd=self.n_embed,n_layer=self.n_layer,n_head=self.n_head)
self.gpt = GPT2Model(self.config)
del self.gpt.wpe
self.gpt.wpe = functools.partial(null_position_embeddings, dim=self.n_embed)
# Built-in token embeddings are unused.
del self.gpt.wte
self.GST = GST(model_channels=self.n_embed,num_heads=self.n_head,in_channels=config.n_mel_channels,k=1)
if self.name == 'Smolie-en':
self.text_head = nn.Linear(self.n_embed,len(text_labels_en))
else:
| '''
Inspiration taken from https://github.com/neonbjb/tortoise-tts/blob/main/tortoise/models/autoregressive.py
'''
def null_position_embeddings(range, dim):
return torch.zeros((range.shape[0], range.shape[1], dim), device=range.device)
class TS_model(nn.Module):
def __init__(self,n_embed = 512, n_layer = 16, n_head = 8, n_positions = 2048, name='Smolie-in'):
super(TS_model,self).__init__()
self.vocab_size=len(labels)
self.n_positions=n_positions
self.n_embed=n_embed
self.n_layer=n_layer
self.n_head=n_head
self.name=name
self.config = GPT2Config(vocab_size=self.vocab_size,n_positions=self.n_positions,n_embd=self.n_embed,n_layer=self.n_layer,n_head=self.n_head)
self.gpt = GPT2Model(self.config)
del self.gpt.wpe
self.gpt.wpe = functools.partial(null_position_embeddings, dim=self.n_embed)
# Built-in token embeddings are unused.
del self.gpt.wte
self.GST = GST(model_channels=self.n_embed,num_heads=self.n_head,in_channels=config.n_mel_channels,k=1)
if self.name == 'Smolie-en':
self.text_head = nn.Linear(self.n_embed,len(text_labels_en))
else: | self.text_head = nn.Linear(self.n_embed,len(text_labels)) | 1 | 2023-11-16 09:44:54+00:00 | 2k |
WCGKING/KINGUSERBOT | Branded/plugins/gdelete.py | [
{
"identifier": "is_gdel_user",
"path": "Branded/modules/data.py",
"snippet": "async def is_gdel_user(user_id: int) -> bool:\n user = await gdeldb.find_one({\"user_id\": user_id})\n if not user:\n return False\n return True"
},
{
"identifier": "get_gdel_user",
"path": "Brande... | import asyncio
from pyrogram import *
from pyrogram.types import Message
from .. import *
from ..modules.data import (is_gdel_user,
get_gdel_user, get_gdel_count,
add_gdel_user, del_gdel_user) | 643 |
@app.on_message(commandx(["gdl", "gdel", "gdelete"]) & SUPUSER)
async def add_gdelete_user(client, message: Message):
if not message.reply_to_message:
if len(message.command) != 2:
return await message.reply_text("Reply to a user's message or give username/user_id.")
user = message.text.split(None, 1)[1]
user = await app.get_users(user)
user_id = user.id
mention = user.mention
else:
user_id = message.reply_to_message.from_user.id
mention = message.reply_to_message.from_user.mention
if user_id == message.from_user.id:
return await message.reply_text("You want to add Global Delete yourself? How Fool!")
elif user_id == SUPUSER:
return await message.reply_text("Should i activate Global Delete on myself? Lol")
elif user_id in SUDOERS:
return await message.reply_text("You want add Global Delete on sudo user?")
is_gdel = await is_gdel_user(user_id)
if is_gdel:
return await message.reply_text("{0} is already affected by **Global Delete**".format(mention))
if user_id not in GDELSUB:
GDELSUB.add(user_id)
|
@app.on_message(commandx(["gdl", "gdel", "gdelete"]) & SUPUSER)
async def add_gdelete_user(client, message: Message):
if not message.reply_to_message:
if len(message.command) != 2:
return await message.reply_text("Reply to a user's message or give username/user_id.")
user = message.text.split(None, 1)[1]
user = await app.get_users(user)
user_id = user.id
mention = user.mention
else:
user_id = message.reply_to_message.from_user.id
mention = message.reply_to_message.from_user.mention
if user_id == message.from_user.id:
return await message.reply_text("You want to add Global Delete yourself? How Fool!")
elif user_id == SUPUSER:
return await message.reply_text("Should i activate Global Delete on myself? Lol")
elif user_id in SUDOERS:
return await message.reply_text("You want add Global Delete on sudo user?")
is_gdel = await is_gdel_user(user_id)
if is_gdel:
return await message.reply_text("{0} is already affected by **Global Delete**".format(mention))
if user_id not in GDELSUB:
GDELSUB.add(user_id) | await add_gdel_user(user_id) | 3 | 2023-11-14 13:24:26+00:00 | 2k |
kudelskisecurity/fuzzomatic | fuzzomatic/docparse.py | [
{
"identifier": "score_functions",
"path": "fuzzomatic/approaches/functions.py",
"snippet": "def score_functions(functions):\n interesting_function_names = [\"parse\", \"load\", \"read\", \"str\", \"eval\"]\n # order functions by most interesting first\n ordered_functions = []\n for f in fun... | import argparse
from fuzzomatic.approaches.functions import score_functions
from fuzzomatic.tools.cargo_doc import parse_cargo_doc_json | 906 | #!/usr/bin/env python3
def get_parser():
prog_name = "docparse"
parser = argparse.ArgumentParser(
prog=prog_name,
description="Parse cargo doc json and print public functions",
)
parser.add_argument(
"json_path",
help="Path to cargo doc json file",
)
return parser
def main():
parser = get_parser()
args = parser.parse_args()
functions = parse_cargo_doc_json(args.json_path)
| #!/usr/bin/env python3
def get_parser():
prog_name = "docparse"
parser = argparse.ArgumentParser(
prog=prog_name,
description="Parse cargo doc json and print public functions",
)
parser.add_argument(
"json_path",
help="Path to cargo doc json file",
)
return parser
def main():
parser = get_parser()
args = parser.parse_args()
functions = parse_cargo_doc_json(args.json_path) | ordered_functions = score_functions(functions) | 0 | 2023-11-14 09:52:59+00:00 | 2k |
muyuworks/myla | myla/vectorstores/lancedb_vectorstore.py | [
{
"identifier": "Record",
"path": "myla/vectorstores/_base.py",
"snippet": "class Record(Dict):\n @staticmethod\n def values_to_text(record: Dict, props: List[str] = None, separator: str = '\\001'):\n if props and not isinstance(props, list):\n raise ValueError(\"props should be ... | from typing import Any, List, Optional, Dict
from ._base import Record, VectorStore
from ._embeddings import Embeddings
import pyarrow as pa
import lancedb as lancedb
import pyarrow as pa | 1,142 |
VECTOR_COLUMN_NAME = "_vector"
class LanceDB(VectorStore):
def __init__(self, db_uri, embeddings: Embeddings = None) -> None:
super().__init__()
try:
pa.__version__
except ImportError as exc:
raise ImportError(
"Could not import pyarrow python package. "
"Please install it with `pip install pyarrow`."
) from exc
try:
# disable diagnostics
lancedb.utils.CONFIG['diagnostics'] = False
except ImportError as exc:
raise ImportError(
"Could not import lancedb python package. "
"Please install it with `pip install lancedb`."
) from exc
self._db_uri = db_uri
self._embeddings = embeddings
self._db = lancedb.connect(self._db_uri)
self._tables = {}
def create_collection(self, collection: str, schema: Dict[str, type] = None, mode="create"):
if schema is None:
raise ValueError("Invalid schema to create LanceDB table.")
s = self._convert_schema(schema=schema)
self._db.create_table(collection, schema=s, mode=mode)
def add(
self,
collection: str,
|
VECTOR_COLUMN_NAME = "_vector"
class LanceDB(VectorStore):
def __init__(self, db_uri, embeddings: Embeddings = None) -> None:
super().__init__()
try:
pa.__version__
except ImportError as exc:
raise ImportError(
"Could not import pyarrow python package. "
"Please install it with `pip install pyarrow`."
) from exc
try:
# disable diagnostics
lancedb.utils.CONFIG['diagnostics'] = False
except ImportError as exc:
raise ImportError(
"Could not import lancedb python package. "
"Please install it with `pip install lancedb`."
) from exc
self._db_uri = db_uri
self._embeddings = embeddings
self._db = lancedb.connect(self._db_uri)
self._tables = {}
def create_collection(self, collection: str, schema: Dict[str, type] = None, mode="create"):
if schema is None:
raise ValueError("Invalid schema to create LanceDB table.")
s = self._convert_schema(schema=schema)
self._db.create_table(collection, schema=s, mode=mode)
def add(
self,
collection: str, | records: List[Record], | 0 | 2023-11-15 01:05:03+00:00 | 2k |
OSU-NLP-Group/TableLlama | inference_row_pop.py | [
{
"identifier": "replace_llama_attn",
"path": "llama_attn_replace.py",
"snippet": "def replace_llama_attn(use_flash_attn=True, use_full=False):\n if use_flash_attn:\n cuda_major, cuda_minor = torch.cuda.get_device_capability()\n if cuda_major < 8:\n warnings.warn(\n ... | import os
import json
import sys
import math
import torch
import argparse
import transformers
from peft import PeftModel
from transformers import GenerationConfig
from llama_attn_replace import replace_llama_attn
from supervised_fine_tune import PROMPT_DICT
from tqdm import tqdm | 670 | # import textwrap
# from queue import Queue
# from threading import Thread
# import gradio as gr
def parse_config():
parser = argparse.ArgumentParser(description='arg parser')
parser.add_argument('--base_model', type=str, default="/data1/pretrained-models/llama-7b-hf")
parser.add_argument('--cache_dir', type=str, default="./cache")
parser.add_argument('--context_size', type=int, default=-1, help='context size during fine-tuning')
parser.add_argument('--flash_attn', type=bool, default=False, help='')
parser.add_argument('--temperature', type=float, default=0.6, help='')
parser.add_argument('--top_p', type=float, default=0.9, help='')
parser.add_argument('--max_gen_len', type=int, default=512, help='')
parser.add_argument('--input_data_file', type=str, default='input_data/', help='')
parser.add_argument('--output_data_file', type=str, default='output_data/', help='')
args = parser.parse_args()
return args
def generate_prompt(instruction, question, input_seg=None):
if input:
| # import textwrap
# from queue import Queue
# from threading import Thread
# import gradio as gr
def parse_config():
parser = argparse.ArgumentParser(description='arg parser')
parser.add_argument('--base_model', type=str, default="/data1/pretrained-models/llama-7b-hf")
parser.add_argument('--cache_dir', type=str, default="./cache")
parser.add_argument('--context_size', type=int, default=-1, help='context size during fine-tuning')
parser.add_argument('--flash_attn', type=bool, default=False, help='')
parser.add_argument('--temperature', type=float, default=0.6, help='')
parser.add_argument('--top_p', type=float, default=0.9, help='')
parser.add_argument('--max_gen_len', type=int, default=512, help='')
parser.add_argument('--input_data_file', type=str, default='input_data/', help='')
parser.add_argument('--output_data_file', type=str, default='output_data/', help='')
args = parser.parse_args()
return args
def generate_prompt(instruction, question, input_seg=None):
if input: | return PROMPT_DICT["prompt_input"].format(instruction=instruction, input_seg=input_seg, question=question) | 1 | 2023-11-16 02:54:08+00:00 | 2k |
pytorch-labs/torchfix | tests/test_torchfix.py | [
{
"identifier": "TorchChecker",
"path": "torchfix/torchfix.py",
"snippet": "class TorchChecker:\n name = \"TorchFix\"\n version = __version__\n\n # The parameters need to have these exact names.\n # See https://flake8.pycqa.org/en/latest/plugin-development/plugin-parameters.html\n # `tree... | from pathlib import Path
from torchfix.torchfix import (
TorchChecker,
TorchCodemod,
TorchCodemodConfig,
GET_ALL_VISITORS,
)
import logging
import libcst.codemod as codemod | 1,175 |
FIXTURES_PATH = Path(__file__).absolute().parent / "fixtures"
LOGGER = logging.getLogger(__name__)
def _checker_results(s):
checker = TorchChecker(None, s)
return [f"{line}:{col} {msg}" for line, col, msg, _ in checker.run()]
def _codemod_results(source_path):
with open(source_path) as source:
code = source.read()
|
FIXTURES_PATH = Path(__file__).absolute().parent / "fixtures"
LOGGER = logging.getLogger(__name__)
def _checker_results(s):
checker = TorchChecker(None, s)
return [f"{line}:{col} {msg}" for line, col, msg, _ in checker.run()]
def _codemod_results(source_path):
with open(source_path) as source:
code = source.read() | config = TorchCodemodConfig(select="ALL") | 2 | 2023-11-15 01:21:07+00:00 | 2k |
FISHers6/CodeLearn-Agent | codelearn/tools/file_content_view.py | [
{
"identifier": "Project",
"path": "codelearn/project/project.py",
"snippet": "class Project:\n\n def __init__(self, id: str, local_dir: str, source_content: FileTree, repo_url: str = None, last_updated_time = None):\n \"\"\"\n :param name: 项目名称\n :param contents: 一个字典,其中键是文件路径,值... | import json
from typing import List, Optional
from langchain.callbacks.manager import CallbackManagerForToolRun
from langchain.tools import BaseTool
from codelearn.project.project import Project
from codelearn.utils.file_util import process_file_paths | 649 |
class FileContentViewTool(BaseTool):
"""Tool to fetch and display detailed content of project files."""
name: str = "get_file_content"
description: str = (
"The 'get_file_content' tool fetches and displays detailed content of specified files within the project, including both source code and documentation. It's an important tool for users who need detailed from code source."
"Input a comma-separated list of file names (without folder or path names) to view. Incomplete paths are not accepted. For example swim-main/src/example.txt is a full path file, but 'src/example' is incomplete directory folder not allowed"
"Output is a dictionary with 'files' key containing a list of dictionaries for each file, "
"**Ensure you've requested the repository structure before asking for file contents.The requested file must exist in the project**"
"Useful for users diving deep into a project's codebase or documentation to understand its intricacies."
)
|
class FileContentViewTool(BaseTool):
"""Tool to fetch and display detailed content of project files."""
name: str = "get_file_content"
description: str = (
"The 'get_file_content' tool fetches and displays detailed content of specified files within the project, including both source code and documentation. It's an important tool for users who need detailed from code source."
"Input a comma-separated list of file names (without folder or path names) to view. Incomplete paths are not accepted. For example swim-main/src/example.txt is a full path file, but 'src/example' is incomplete directory folder not allowed"
"Output is a dictionary with 'files' key containing a list of dictionaries for each file, "
"**Ensure you've requested the repository structure before asking for file contents.The requested file must exist in the project**"
"Useful for users diving deep into a project's codebase or documentation to understand its intricacies."
) | project: Project | 0 | 2023-11-12 13:13:30+00:00 | 2k |
kaixinol/twitter_user_tweet_crawler | twitter_user_tweet_crawler/__main__.py | [
{
"identifier": "get_browser",
"path": "twitter_user_tweet_crawler/browser.py",
"snippet": "def get_browser(headless: bool = False) -> WebDriver:\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument('--blink-settings=imagesEnabled=false')\n chrome_options.add_argument('--d... | import concurrent.futures
import json
from pathlib import Path
from time import sleep
from urllib.parse import urlparse
from loguru import logger
from rich.prompt import Confirm
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.by import By
from .browser import get_browser, get_multiple_browsers
from .pool import ThreadPool
from .util.config import config, work_directory, set_work_directory
from .tweet import Tweet | 807 |
def main():
cookie: list[dict]
work_list: list[WebDriver]
driver: WebDriver
def read_config() -> list[dict]:
with open(work_directory / 'cookie.json', 'r') as f:
return json.load(f)
def write_config(data: list[dict]):
with open(work_directory / 'cookie.json', 'w') as f:
json.dump(data, f)
def set_cookie(browser: WebDriver):
for i in cookie:
browser.add_cookie(i)
def get_executor(count: int | None = None):
return concurrent.futures.ThreadPoolExecutor(max_workers=count)
def get_items_need_handle():
return driver.find_elements(*selector)
selector = (By.XPATH, '//*/div[2]/div/div[3]/a[@role="link"]')
|
def main():
cookie: list[dict]
work_list: list[WebDriver]
driver: WebDriver
def read_config() -> list[dict]:
with open(work_directory / 'cookie.json', 'r') as f:
return json.load(f)
def write_config(data: list[dict]):
with open(work_directory / 'cookie.json', 'w') as f:
json.dump(data, f)
def set_cookie(browser: WebDriver):
for i in cookie:
browser.add_cookie(i)
def get_executor(count: int | None = None):
return concurrent.futures.ThreadPoolExecutor(max_workers=count)
def get_items_need_handle():
return driver.find_elements(*selector)
selector = (By.XPATH, '//*/div[2]/div/div[3]/a[@role="link"]') | (Path(config.save) / 'res').mkdir(exist_ok=True, parents=True) | 3 | 2023-11-12 11:40:26+00:00 | 2k |
kirill-vish/Beyond-INet | inference/modelvshuman/model_evaluator.py | [
{
"identifier": "load_model_transform",
"path": "utils/misc.py",
"snippet": "def load_model_transform(model_name, pretrained_dir, img_size=224):\n print(f\"Loading {model_name}\")\n checkpoint_path = None\n transform_val = None\n if model_name == \"deit3_21k\":\n model = models_deit.d... | import copy
import datetime
import logging
import os
import matplotlib as mpl
import torch
from torch.nn.functional import softmax
from tqdm import tqdm
from utils.misc import load_model_transform
from .evaluation import evaluate as e
from .utils import load_dataset, load_model | 1,409 |
logger = logging.getLogger(__name__)
MAX_NUM_MODELS_IN_CACHE = 3
mpl.rcParams['font.size'] = 22
def device():
return torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class ModelEvaluator:
def _pytorch_evaluator(self, model_name, model, dataset, *args, **kwargs):
"""
Evaluate Model on the given dataset and return the accuracy.
Args:
model_name:
model:
dataset:
*args:
**kwargs:
"""
logging_info = f"Evaluating model {model_name} on dataset {dataset.name} using Pytorch Evaluator"
logger.info(logging_info)
print(logging_info)
for metric in dataset.metrics:
metric.reset()
with torch.no_grad():
result_writer = e.ResultPrinter(model_name=model_name,
dataset=dataset)
for images, target, paths in tqdm(dataset.loader):
images = images.to(device())
if "forward_batch" in dir(model):
logits = model.forward_batch(images)
softmax_output = model.softmax(logits)
else:
logits = model(images)
softmax_output = softmax(logits,
dim=1).detach().cpu().numpy()
if isinstance(target, torch.Tensor):
batch_targets = model.to_numpy(target)
else:
batch_targets = target
predictions = dataset.decision_mapping(softmax_output)
for metric in dataset.metrics:
metric.update(predictions, batch_targets, paths)
if kwargs["print_predictions"]:
result_writer.print_batch_to_csv(
object_response=predictions,
batch_targets=batch_targets,
paths=paths)
def _get_datasets(self, dataset_names, *args, **kwargs):
dataset_list = []
for dataset in dataset_names:
|
logger = logging.getLogger(__name__)
MAX_NUM_MODELS_IN_CACHE = 3
mpl.rcParams['font.size'] = 22
def device():
return torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class ModelEvaluator:
def _pytorch_evaluator(self, model_name, model, dataset, *args, **kwargs):
"""
Evaluate Model on the given dataset and return the accuracy.
Args:
model_name:
model:
dataset:
*args:
**kwargs:
"""
logging_info = f"Evaluating model {model_name} on dataset {dataset.name} using Pytorch Evaluator"
logger.info(logging_info)
print(logging_info)
for metric in dataset.metrics:
metric.reset()
with torch.no_grad():
result_writer = e.ResultPrinter(model_name=model_name,
dataset=dataset)
for images, target, paths in tqdm(dataset.loader):
images = images.to(device())
if "forward_batch" in dir(model):
logits = model.forward_batch(images)
softmax_output = model.softmax(logits)
else:
logits = model(images)
softmax_output = softmax(logits,
dim=1).detach().cpu().numpy()
if isinstance(target, torch.Tensor):
batch_targets = model.to_numpy(target)
else:
batch_targets = target
predictions = dataset.decision_mapping(softmax_output)
for metric in dataset.metrics:
metric.update(predictions, batch_targets, paths)
if kwargs["print_predictions"]:
result_writer.print_batch_to_csv(
object_response=predictions,
batch_targets=batch_targets,
paths=paths)
def _get_datasets(self, dataset_names, *args, **kwargs):
dataset_list = []
for dataset in dataset_names: | dataset = load_dataset(dataset, *args, **kwargs) | 2 | 2023-11-15 22:22:06+00:00 | 2k |
shengliu66/ICV | utils/context_manager.py | [
{
"identifier": "ForwardTracer",
"path": "utils/forward_tracer.py",
"snippet": "class ForwardTracer:\n def __init__(self, model: PreTrainedModel, forward_trace: ForwardTrace, with_submodules: bool = False):\n self._model = model\n self._forward_trace = forward_trace\n self._with_... | import os
from contextlib import AbstractContextManager, ExitStack
from typing import Iterable
from utils.forward_tracer import ForwardTracer, ForwardTrace | 1,209 |
class CombinedContextManager(AbstractContextManager):
def __init__(self, context_managers):
self.context_managers = context_managers
self.stack = None
def __enter__(self):
self.stack = ExitStack()
for cm in self.context_managers:
self.stack.enter_context(cm)
return self.stack
def __exit__(self, exc_type, exc_val, exc_tb):
if self.stack is not None:
self.stack.__exit__(exc_type, exc_val, exc_tb)
def modified_forward_context_manager(model, forward_modifiers=()):
context_manager = CombinedContextManager([*forward_modifiers])
return context_manager
def traced_forward_context_manager(model, with_submodules=False):
|
class CombinedContextManager(AbstractContextManager):
def __init__(self, context_managers):
self.context_managers = context_managers
self.stack = None
def __enter__(self):
self.stack = ExitStack()
for cm in self.context_managers:
self.stack.enter_context(cm)
return self.stack
def __exit__(self, exc_type, exc_val, exc_tb):
if self.stack is not None:
self.stack.__exit__(exc_type, exc_val, exc_tb)
def modified_forward_context_manager(model, forward_modifiers=()):
context_manager = CombinedContextManager([*forward_modifiers])
return context_manager
def traced_forward_context_manager(model, with_submodules=False): | forward_trace = ForwardTrace() | 1 | 2023-11-11 18:20:45+00:00 | 2k |
Mohamad-Hussein/speech-assistant | src/model_inference.py | [
{
"identifier": "find_gpu_config",
"path": "src/funcs.py",
"snippet": "def find_gpu_config(logger):\n \"\"\"\n Finds the GPU config and returns the device, device name and torch_dtype\n based on GPU platform and availability.\n\n Args:\n logger (logging.Logger): Logger instance to log... | from sys import exit
from os.path import join
from time import sleep, time
from src.funcs import find_gpu_config, process_text
from src.funcs import type_writing, copy_writing
from transformers.pipelines import pipeline
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor
from optimum.bettertransformer import BetterTransformer
import logging | 1,341 |
# from optimum.onnxruntime import ORTModelForSpeechSeq2Seq
# from optimum.nvidia.pipelines import pipeline
# MODEL_ID = "openai/whisper-tiny.en" # ~400 MiB of GPU memory
MODEL_ID = "distil-whisper/distil-small.en" # ~500-700 MiB of GPU memory
# MODEL_ID = "distil-whisper/distil-medium.en" # ~900-1500 MiB of GPU memory
# MODEL_ID = "distil-whisper/distil-large-v2" # ~1700-2000 MiB of GPU memory
# MODEL_ID = "openai/whisper-large-v3" # ~4000 MiB of GPU memory
# MODEL_ID = "optimum/whisper-tiny.en" # ~400 MiB of GPU memory
# Choosing which way to write text.
WRITE = type_writing
def service(queue, event):
# Configure the logging settings
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s - %(levelname)s - %(message)s",
filename=join("logs", "model.log"),
filemode="w",
)
logger = logging.getLogger(__name__)
# Checking for GPU
|
# from optimum.onnxruntime import ORTModelForSpeechSeq2Seq
# from optimum.nvidia.pipelines import pipeline
# MODEL_ID = "openai/whisper-tiny.en" # ~400 MiB of GPU memory
MODEL_ID = "distil-whisper/distil-small.en" # ~500-700 MiB of GPU memory
# MODEL_ID = "distil-whisper/distil-medium.en" # ~900-1500 MiB of GPU memory
# MODEL_ID = "distil-whisper/distil-large-v2" # ~1700-2000 MiB of GPU memory
# MODEL_ID = "openai/whisper-large-v3" # ~4000 MiB of GPU memory
# MODEL_ID = "optimum/whisper-tiny.en" # ~400 MiB of GPU memory
# Choosing which way to write text.
WRITE = type_writing
def service(queue, event):
# Configure the logging settings
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s - %(levelname)s - %(message)s",
filename=join("logs", "model.log"),
filemode="w",
)
logger = logging.getLogger(__name__)
# Checking for GPU | device, device_name, torch_dtype = find_gpu_config(logger) | 0 | 2023-11-12 01:20:50+00:00 | 2k |
Fraunhofer-SCAI/corr_shap | corr_shap/CorrExplainer.py | [
{
"identifier": "SamplingStrategy",
"path": "corr_shap/sampling/SamplingStrategy.py",
"snippet": "class SamplingStrategy:\n def __init__(self, explainer, **kwargs):\n \"\"\" Construct all necessary attributes for the SamplingStrategy object.\"\"\"\n self.data = explainer.data.data\n ... | from scipy.special import binom
from scipy import sparse
from shap.utils._legacy import convert_to_instance, match_instance_to_data, IdentityLink
from shap.explainers._explainer import Explainer
from shap.explainers._kernel import KernelExplainer
from shap.explainers._kernel import Kernel as KernelExplainer
from corr_shap.sampling.SamplingStrategy import SamplingStrategy
from corr_shap.sampling.sampling_factory import get_sampling_strategy
import numpy as np
import pandas as pd
import logging
import copy
import itertools
import typing
import warnings | 986 |
try:
except ImportError:
log = logging.getLogger('corr_shap')
class CorrExplainer(KernelExplainer):
"""Uses the modified Kernel SHAP method to explain the output of any function.
The modifications (based on the paper 'Explaining individual predictions when features are dependent:
More accurate approximations to Shapley values' by Kjersti Aas, Martin Jullum and Anders Løland)
offer the possibility to include dependencies between features.
There are 3 different approaches, which are described in the following sampling strategies.
"""
|
try:
except ImportError:
log = logging.getLogger('corr_shap')
class CorrExplainer(KernelExplainer):
"""Uses the modified Kernel SHAP method to explain the output of any function.
The modifications (based on the paper 'Explaining individual predictions when features are dependent:
More accurate approximations to Shapley values' by Kjersti Aas, Martin Jullum and Anders Løland)
offer the possibility to include dependencies between features.
There are 3 different approaches, which are described in the following sampling strategies.
"""
| def __init__(self, model, data, link=IdentityLink(), sampling: typing.Union[str, SamplingStrategy]="default", sampling_kwargs={}, **kwargs): | 0 | 2023-11-14 08:56:18+00:00 | 2k |
codereport/jello | jello.py | [
{
"identifier": "Grid",
"path": "grid.py",
"snippet": "class Grid:\n def __init__(self, n):\n self.n = n * 2\n self.grid = [[\" \"] * self.n, [\" \"] * self.n]\n\n def add_level(self):\n self.grid.append([\" \"] * self.n)\n self.grid.append([\" \"] * self.n)\n\n def ... | import subprocess
import algorithm
import arity_notation
import draw
import tokens
import utils
from colorama import Fore, init
from prompt_toolkit import prompt
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.history import FileHistory
from prompt_toolkit.shortcuts import CompleteStyle
from grid import Grid
from utils import Chain, Quick, Separator | 1,201 | #!/usr/bin/env python3
def clear_screen():
subprocess.call("clear", shell=True)
def run_jelly(expr: str, args: list[str]):
try:
command = ["jelly", "eun", expr, *args]
result = subprocess.run(command, text=True, capture_output=True, check=True)
output_text = result.stdout.strip()
draw.cprint(output_text, Fore.GREEN, True)
except subprocess.CalledProcessError as e:
# Print the stderr output for more information about the error
print(Fore.RED + f"Error: {e}")
print(Fore.RED + "stderr:", e.stderr)
completer = WordCompleter(
[k for k in sorted(
list(tokens.niladic.keys()) +
list(tokens.monadic.keys()) +
list(tokens.dyadic.keys()) +
list(tokens.quick.keys()) +
list(tokens.separators.keys())) if len(k) > 1])
history = FileHistory("jello_history.txt")
def is_nilad_array(s: str) -> bool:
return set(list(s)).issubset(list("0123456789,[]"))
def to_jelly(token: str) -> str:
if token in tokens.monadic: return tokens.monadic[token]
if token in tokens.dyadic: return tokens.dyadic[token]
if token in tokens.niladic: return tokens.niladic[token]
if token in tokens.quick: return tokens.quick[token]
if token in tokens.separators: return tokens.separators[token]
if is_nilad_array(token): return token
raise Exception(f"{token} is not a valid Jello keyword.")
def convert(expr: list[str]) -> str:
return "".join([to_jelly(t) for t in expr])
def keyword_arity(k: str) -> int:
if k in tokens.niladic: return 0
if k in tokens.monadic: return 1
if k in tokens.dyadic: return 2
if k == "each": return Quick.EACH
if k == "c": return Quick.FLIP
if k in tokens.quick: return Quick.QUICK
| #!/usr/bin/env python3
def clear_screen():
subprocess.call("clear", shell=True)
def run_jelly(expr: str, args: list[str]):
try:
command = ["jelly", "eun", expr, *args]
result = subprocess.run(command, text=True, capture_output=True, check=True)
output_text = result.stdout.strip()
draw.cprint(output_text, Fore.GREEN, True)
except subprocess.CalledProcessError as e:
# Print the stderr output for more information about the error
print(Fore.RED + f"Error: {e}")
print(Fore.RED + "stderr:", e.stderr)
completer = WordCompleter(
[k for k in sorted(
list(tokens.niladic.keys()) +
list(tokens.monadic.keys()) +
list(tokens.dyadic.keys()) +
list(tokens.quick.keys()) +
list(tokens.separators.keys())) if len(k) > 1])
history = FileHistory("jello_history.txt")
def is_nilad_array(s: str) -> bool:
return set(list(s)).issubset(list("0123456789,[]"))
def to_jelly(token: str) -> str:
if token in tokens.monadic: return tokens.monadic[token]
if token in tokens.dyadic: return tokens.dyadic[token]
if token in tokens.niladic: return tokens.niladic[token]
if token in tokens.quick: return tokens.quick[token]
if token in tokens.separators: return tokens.separators[token]
if is_nilad_array(token): return token
raise Exception(f"{token} is not a valid Jello keyword.")
def convert(expr: list[str]) -> str:
return "".join([to_jelly(t) for t in expr])
def keyword_arity(k: str) -> int:
if k in tokens.niladic: return 0
if k in tokens.monadic: return 1
if k in tokens.dyadic: return 2
if k == "each": return Quick.EACH
if k == "c": return Quick.FLIP
if k in tokens.quick: return Quick.QUICK | if k == ".": return Separator.MONADIC | 3 | 2023-11-18 17:34:06+00:00 | 2k |
mMrBun/Chat2BI | llms/chatglm3/code_interpreter.py | [
{
"identifier": "preprocess_text",
"path": "llms/chatglm3/conversation.py",
"snippet": "def preprocess_text(\n system: str | None,\n tools: list[dict] | None,\n history: list[Conversation],\n) -> str:\n if tools:\n tools = json.dumps(tools, indent=4, ensure_ascii=False)\n\... | from llms.chatglm3.conversation import preprocess_text, Conversation, Role
from core.build_tools.utils import extract_code | 822 |
SYSTEM_PROMPT = ('你是一位智能AI助手,你叫ChatGLM,你连接着一台电脑,但请注意不能联网。在使用Python'
'解决任务时,你可以运行代码并得到结果,如果运行结果有错误,你需要尽可能对代码进行改进。你可以处理用户上传到电脑上的文件,文件默认存储路径是/mnt/data/。')
MAX_LENGTH = 8192
TRUNCATE_LENGTH = 1024
def is_valid_python(code: str) -> bool:
try:
|
SYSTEM_PROMPT = ('你是一位智能AI助手,你叫ChatGLM,你连接着一台电脑,但请注意不能联网。在使用Python'
'解决任务时,你可以运行代码并得到结果,如果运行结果有错误,你需要尽可能对代码进行改进。你可以处理用户上传到电脑上的文件,文件默认存储路径是/mnt/data/。')
MAX_LENGTH = 8192
TRUNCATE_LENGTH = 1024
def is_valid_python(code: str) -> bool:
try: | code = extract_code(code) | 3 | 2023-11-15 11:49:50+00:00 | 2k |
compphoto/Intrinsic | intrinsic/pipeline.py | [
{
"identifier": "base_resize",
"path": "intrinsic/ordinal_util.py",
"snippet": "def base_resize(img, base_size=384):\n \"\"\"TODO DESCRIPTION\n\n params:\n img (TODO): TODO\n base_size (int) optional: TODO (default 384)\n\n returns:\n net_input (TODO): TODO\n \"\"\"\n ... | import torch
import numpy as np
from skimage.transform import resize
from chrislib.resolution_util import optimal_resize
from chrislib.general import round_32, uninvert
from intrinsic.ordinal_util import base_resize, equalize_predictions | 1,440 |
def run_pipeline(
models,
img_arr,
output_ordinal=False,
resize_conf=0.0,
base_size=384,
maintain_size=False,
linear=False,
device='cuda',
lstsq_p=0.0,
inputs='all'):
"""Runs the complete pipeline for shading and albedo prediction
params:
models (dict): models dictionary returned by model_util.load_models()
img_arr (np.array): RGB input image as numpy array between 0-1
output_ordinal (bool) optional: whether or not to output intermediate ordinal estimations
(default False)
resize_conf (float) optional: confidence to use for resizing (between 0-1) if None maintain
original size (default None)
base_size (int) optional: size of the base resolution estimation (default 384)
maintain_size (bool) optional: whether or not the results match the input image size
(default False)
linear (bool) optional: whether or not the input image is already linear (default False)
device (str) optional: string representing device to use for pipeline (default "cuda")
lstsq_p (float) optional: subsampling factor for computing least-squares fit
when matching the scale of base and full estimations (default 0.0)
inputs (str) optional: network inputs ("full", "base", "rgb", "all") the rgb image is
always included (default "all")
returns:
results (dict): a result dictionary with albedo, shading and potentiall ordinal estimations
"""
results = {}
orig_h, orig_w, _ = img_arr.shape
# if no confidence value set, just round original size to 32 for model input
if resize_conf is None:
img_arr = resize(img_arr, (round_32(orig_h), round_32(orig_w)), anti_aliasing=True)
# if a the confidence is an int, just rescale image so that the large side
# of the image matches the specified integer value
elif isinstance(resize_conf, int):
scale = resize_conf / max(orig_h, orig_w)
img_arr = resize(
img_arr,
(round_32(orig_h * scale), round_32(orig_w * scale)),
anti_aliasing=True)
# if the confidence is a float use the optimal resize code from Miangoleh et al.
elif isinstance(resize_conf, float):
img_arr = optimal_resize(img_arr, conf=resize_conf)
fh, fw, _ = img_arr.shape
# if the image is in sRGB we do simple linearization using gamma=2.2
if not linear:
lin_img = img_arr ** 2.2
else:
lin_img = img_arr
with torch.no_grad():
# ordinal shading estimation --------------------------
# resize image for base and full estimations and send through ordinal net
base_input = base_resize(lin_img, base_size)
full_input = lin_img
base_input = torch.from_numpy(base_input).permute(2, 0, 1).to(device).float()
full_input = torch.from_numpy(full_input).permute(2, 0, 1).to(device).float()
base_out = models['ordinal_model'](base_input.unsqueeze(0)).squeeze(0)
full_out = models['ordinal_model'](full_input.unsqueeze(0)).squeeze(0)
# the ordinal estimations come out of the model with a channel dim
base_out = base_out.permute(1, 2, 0).cpu().numpy()
full_out = full_out.permute(1, 2, 0).cpu().numpy()
base_out = resize(base_out, (fh, fw))
# if we are using all inputs, we scale the input estimations using the base estimate
if inputs == 'all':
|
def run_pipeline(
models,
img_arr,
output_ordinal=False,
resize_conf=0.0,
base_size=384,
maintain_size=False,
linear=False,
device='cuda',
lstsq_p=0.0,
inputs='all'):
"""Runs the complete pipeline for shading and albedo prediction
params:
models (dict): models dictionary returned by model_util.load_models()
img_arr (np.array): RGB input image as numpy array between 0-1
output_ordinal (bool) optional: whether or not to output intermediate ordinal estimations
(default False)
resize_conf (float) optional: confidence to use for resizing (between 0-1) if None maintain
original size (default None)
base_size (int) optional: size of the base resolution estimation (default 384)
maintain_size (bool) optional: whether or not the results match the input image size
(default False)
linear (bool) optional: whether or not the input image is already linear (default False)
device (str) optional: string representing device to use for pipeline (default "cuda")
lstsq_p (float) optional: subsampling factor for computing least-squares fit
when matching the scale of base and full estimations (default 0.0)
inputs (str) optional: network inputs ("full", "base", "rgb", "all") the rgb image is
always included (default "all")
returns:
results (dict): a result dictionary with albedo, shading and potentiall ordinal estimations
"""
results = {}
orig_h, orig_w, _ = img_arr.shape
# if no confidence value set, just round original size to 32 for model input
if resize_conf is None:
img_arr = resize(img_arr, (round_32(orig_h), round_32(orig_w)), anti_aliasing=True)
# if a the confidence is an int, just rescale image so that the large side
# of the image matches the specified integer value
elif isinstance(resize_conf, int):
scale = resize_conf / max(orig_h, orig_w)
img_arr = resize(
img_arr,
(round_32(orig_h * scale), round_32(orig_w * scale)),
anti_aliasing=True)
# if the confidence is a float use the optimal resize code from Miangoleh et al.
elif isinstance(resize_conf, float):
img_arr = optimal_resize(img_arr, conf=resize_conf)
fh, fw, _ = img_arr.shape
# if the image is in sRGB we do simple linearization using gamma=2.2
if not linear:
lin_img = img_arr ** 2.2
else:
lin_img = img_arr
with torch.no_grad():
# ordinal shading estimation --------------------------
# resize image for base and full estimations and send through ordinal net
base_input = base_resize(lin_img, base_size)
full_input = lin_img
base_input = torch.from_numpy(base_input).permute(2, 0, 1).to(device).float()
full_input = torch.from_numpy(full_input).permute(2, 0, 1).to(device).float()
base_out = models['ordinal_model'](base_input.unsqueeze(0)).squeeze(0)
full_out = models['ordinal_model'](full_input.unsqueeze(0)).squeeze(0)
# the ordinal estimations come out of the model with a channel dim
base_out = base_out.permute(1, 2, 0).cpu().numpy()
full_out = full_out.permute(1, 2, 0).cpu().numpy()
base_out = resize(base_out, (fh, fw))
# if we are using all inputs, we scale the input estimations using the base estimate
if inputs == 'all': | ord_base, ord_full = equalize_predictions(lin_img, base_out, full_out, p=lstsq_p) | 1 | 2023-11-13 19:24:09+00:00 | 2k |
davep/tinboard | tinboard/widgets/tags.py | [
{
"identifier": "ClearTags",
"path": "tinboard/messages/tags.py",
"snippet": "class ClearTags(Message):\n \"\"\"Clear any tags being used to filter.\"\"\""
},
{
"identifier": "ShowAlsoTaggedWith",
"path": "tinboard/messages/tags.py",
"snippet": "class ShowAlsoTaggedWith(TagMessage):\n... | from typing_extensions import Final, Self
from textual import on
from textual.binding import Binding
from textual.events import Focus
from textual.reactive import var
from textual.widgets.option_list import Option, OptionDoesNotExist
from rich.console import RenderableType
from rich.emoji import Emoji
from rich.table import Table
from ..messages import ClearTags, ShowAlsoTaggedWith, ShowTaggedWith
from .extended_option_list import OptionListEx | 992 | """Defines a widget for picking tags."""
##############################################################################
# Backward compatibility.
from __future__ import annotations
##############################################################################
# Python imports.
##############################################################################
# Textual imports.
##############################################################################
# Rich imports.
##############################################################################
# Local imports.
##############################################################################
class Tags(OptionListEx):
"""A menu of tags."""
CONTEXT_HELP = """
## Tag list keys
The following keys are available in the list of tags:
| Key | Description |
| - | - |
| <kbd>Enter</kbd> | Show bookmarks with this tag in the bookmark list. |
| <kbd>+</kbd> | Add this tag to any tag filter active in the bookmark list. |
"""
DEFAULT_CSS = """
Tags {
&:focus {
border: blank;
}
&> .option-list--option {
padding: 0 1;
}
}
"""
BINDINGS = [
Binding("enter", "select", "Show tagged", show=True),
Binding("+", "also_tagged", "Show also tagged"),
]
def _prompt(self, tag: str, count: int) -> RenderableType:
"""A prompt for the given tag.
Args:
tag: The tag to build a prompt for.
count: The count for that tag.
Returns:
The prompt for the tag.
"""
prompt = Table.grid(expand=True)
prompt.add_column(ratio=1)
prompt.add_column(justify="right")
prompt.add_row(tag, f"[dim i]{count}[/]")
return prompt
def _sorted(self, tags: list[tuple[str, int]]) -> list[tuple[str, int]]:
"""Sort the tags.
Args:
tags: The tags to sort.
Returns:
The tags in the desired sort order.
"""
return tags
def show(self, tags: list[tuple[str, int]]) -> Self:
"""Show the given list of tags.
Args:
tags: The tags to show in the widget.
Returns:
Self.
"""
self.can_focus = bool(tags)
highlighted_tag = (
self.get_option_at_index(self.highlighted).id
if self.highlighted is not None
else None
)
try:
return self.clear_options().add_options(
[
Option(self._prompt(tag, count), id=tag)
for tag, count in self._sorted(tags)
]
)
finally:
if tags:
try:
self.highlighted = self.get_option_index(highlighted_tag or "")
except OptionDoesNotExist:
self.highlighted = 0
def _on_focus(self, _: Focus) -> None:
"""Highlight the first item on focus, if none highlighted."""
if self.option_count and self.highlighted is None:
self.highlighted = 0
@on(OptionListEx.OptionSelected)
def _show_tagged(self, event: OptionListEx.OptionSelected) -> None:
"""Request that bookmarks of a given tag are shown.
Args:
event: The event to handle.
"""
if event.option.id is not None:
| """Defines a widget for picking tags."""
##############################################################################
# Backward compatibility.
from __future__ import annotations
##############################################################################
# Python imports.
##############################################################################
# Textual imports.
##############################################################################
# Rich imports.
##############################################################################
# Local imports.
##############################################################################
class Tags(OptionListEx):
"""A menu of tags."""
CONTEXT_HELP = """
## Tag list keys
The following keys are available in the list of tags:
| Key | Description |
| - | - |
| <kbd>Enter</kbd> | Show bookmarks with this tag in the bookmark list. |
| <kbd>+</kbd> | Add this tag to any tag filter active in the bookmark list. |
"""
DEFAULT_CSS = """
Tags {
&:focus {
border: blank;
}
&> .option-list--option {
padding: 0 1;
}
}
"""
BINDINGS = [
Binding("enter", "select", "Show tagged", show=True),
Binding("+", "also_tagged", "Show also tagged"),
]
def _prompt(self, tag: str, count: int) -> RenderableType:
"""A prompt for the given tag.
Args:
tag: The tag to build a prompt for.
count: The count for that tag.
Returns:
The prompt for the tag.
"""
prompt = Table.grid(expand=True)
prompt.add_column(ratio=1)
prompt.add_column(justify="right")
prompt.add_row(tag, f"[dim i]{count}[/]")
return prompt
def _sorted(self, tags: list[tuple[str, int]]) -> list[tuple[str, int]]:
"""Sort the tags.
Args:
tags: The tags to sort.
Returns:
The tags in the desired sort order.
"""
return tags
def show(self, tags: list[tuple[str, int]]) -> Self:
"""Show the given list of tags.
Args:
tags: The tags to show in the widget.
Returns:
Self.
"""
self.can_focus = bool(tags)
highlighted_tag = (
self.get_option_at_index(self.highlighted).id
if self.highlighted is not None
else None
)
try:
return self.clear_options().add_options(
[
Option(self._prompt(tag, count), id=tag)
for tag, count in self._sorted(tags)
]
)
finally:
if tags:
try:
self.highlighted = self.get_option_index(highlighted_tag or "")
except OptionDoesNotExist:
self.highlighted = 0
def _on_focus(self, _: Focus) -> None:
"""Highlight the first item on focus, if none highlighted."""
if self.option_count and self.highlighted is None:
self.highlighted = 0
@on(OptionListEx.OptionSelected)
def _show_tagged(self, event: OptionListEx.OptionSelected) -> None:
"""Request that bookmarks of a given tag are shown.
Args:
event: The event to handle.
"""
if event.option.id is not None: | self.post_message(ShowTaggedWith(event.option.id)) | 2 | 2023-11-13 08:19:41+00:00 | 2k |
buptlihang/CVLM | evaluation/MME/evaluate.py | [
{
"identifier": "IMAGE_TOKEN_INDEX",
"path": "model/utils.py",
"snippet": "IMAGE_TOKEN_INDEX = -200"
},
{
"identifier": "DEFAULT_IMAGE_TOKEN",
"path": "model/utils.py",
"snippet": "DEFAULT_IMAGE_TOKEN = \"<image>\""
},
{
"identifier": "DEFAULT_IM_START_TOKEN",
"path": "model/... | import argparse
import torch
import os
import json
import math
from tqdm import tqdm
from model.utils import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
from model.utils import build_conversation, load_pretrained_model, disable_torch_init, get_model_name_from_path
from model.utils import tokenizer_image_token, process_images
from torch.utils.data import Dataset, DataLoader
from PIL import Image
from collections import defaultdict | 1,490 |
def split_list(lst, n):
"""Split a list into n (roughly) equal-sized chunks"""
chunk_size = math.ceil(len(lst) / n) # integer division
return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)]
def get_chunk(lst, n, k):
chunks = split_list(lst, n)
return chunks[k]
def get_gt(data_path):
GT = {}
for category in os.listdir(data_path):
category_dir = os.path.join(data_path, category)
if not os.path.isdir(category_dir):
continue
if os.path.exists(os.path.join(category_dir, 'images')):
image_path = os.path.join(category_dir, 'images')
qa_path = os.path.join(category_dir, 'questions_answers_YN')
else:
image_path = qa_path = category_dir
assert os.path.isdir(image_path), image_path
assert os.path.isdir(qa_path), qa_path
for file in os.listdir(qa_path):
if not file.endswith('.txt'):
continue
for line in open(os.path.join(qa_path, file)):
question, answer = line.strip().split('\t')
GT[(category, file, question)] = answer
return GT
# Custom dataset class
class CustomDataset(Dataset):
def __init__(self, questions, image_folder, tokenizer, image_processor,
model_config):
self.questions = questions
self.image_folder = image_folder
self.tokenizer = tokenizer
self.image_processor = image_processor
self.model_config = model_config
def __getitem__(self, index):
line = self.questions[index]
image_file = line["image"]
qs = line["text"]
|
def split_list(lst, n):
"""Split a list into n (roughly) equal-sized chunks"""
chunk_size = math.ceil(len(lst) / n) # integer division
return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)]
def get_chunk(lst, n, k):
chunks = split_list(lst, n)
return chunks[k]
def get_gt(data_path):
GT = {}
for category in os.listdir(data_path):
category_dir = os.path.join(data_path, category)
if not os.path.isdir(category_dir):
continue
if os.path.exists(os.path.join(category_dir, 'images')):
image_path = os.path.join(category_dir, 'images')
qa_path = os.path.join(category_dir, 'questions_answers_YN')
else:
image_path = qa_path = category_dir
assert os.path.isdir(image_path), image_path
assert os.path.isdir(qa_path), qa_path
for file in os.listdir(qa_path):
if not file.endswith('.txt'):
continue
for line in open(os.path.join(qa_path, file)):
question, answer = line.strip().split('\t')
GT[(category, file, question)] = answer
return GT
# Custom dataset class
class CustomDataset(Dataset):
def __init__(self, questions, image_folder, tokenizer, image_processor,
model_config):
self.questions = questions
self.image_folder = image_folder
self.tokenizer = tokenizer
self.image_processor = image_processor
self.model_config = model_config
def __getitem__(self, index):
line = self.questions[index]
image_file = line["image"]
qs = line["text"] | qs = DEFAULT_IMAGE_TOKEN + '\n' + qs | 1 | 2023-11-10 03:52:46+00:00 | 2k |
vvvm23/TchAIkovsky | generate.py | [
{
"identifier": "get_pretrained_tokenizer",
"path": "data/tokenizer.py",
"snippet": "def get_pretrained_tokenizer(path: str = \"tokenizer.json\"):\n return miditok.REMI.from_pretrained(path)"
},
{
"identifier": "TchAIkovskyModel",
"path": "model/model.py",
"snippet": "class TchAIkovsk... | import json
import equinox as eqx
import jax
import jax.numpy as jnp
import numpy as np
import orbax.checkpoint as ocp
import tqdm
from argparse import ArgumentParser
from datetime import datetime
from pathlib import Path
from types import SimpleNamespace
from typing import Optional
from loguru import logger
from miditoolkit import MidiFile
from data.tokenizer import get_pretrained_tokenizer
from model import TchAIkovskyModel
from utils import seed_others | 1,331 |
def load_config(config_path):
with open(config_path, mode="r") as f:
data = f.read()
json_dict = json.loads(data)
return SimpleNamespace(**json_dict)
@eqx.filter_jit
@eqx.debug.assert_max_traces(max_traces=1)
def generate_step(model, inputs, length, key, temperature):
logits = model(**inputs)
logits = jnp.take(logits, length - 1, axis=0)
if temperature == 0.0:
# argmax sampling
return jnp.argmax(logits, axis=-1)
logits = logits / temperature
return jax.random.categorical(key, logits, axis=-1)
def generate_loop(
model,
initial_input,
temperature,
key,
max_to_generate: Optional[int] = None,
model_max_positions: int = 1024,
output_generated_only: bool = False,
) -> np.array:
sample_idx = initial_input.shape[0]
if output_generated_only:
output = []
else:
output = initial_input.tolist()
if max_to_generate is None:
DEFAULT_MAX = 1000
max_to_generate = DEFAULT_MAX
input_length = sample_idx + max_to_generate
if input_length > model_max_positions - 1:
input_length = model_max_positions - 1
position_ids = np.arange(input_length)
mask = np.concatenate(
[
np.ones((sample_idx,), dtype=bool),
np.zeros((input_length - sample_idx,), dtype=bool),
],
axis=-1,
dtype=bool,
)
input_ids = np.pad(initial_input, ((0, input_length - sample_idx),))
# TODO: maybe replace with jax.lax.scan loop for faster generation
for _ in tqdm.trange(max_to_generate):
key, subkey = jax.random.split(key)
inputs = dict(input_ids=input_ids, position_ids=position_ids, mask=mask)
token = generate_step(model, inputs, np.array(sample_idx), subkey, temperature).item()
output.append(token)
if sample_idx < input_length:
input_ids[sample_idx] = token
mask[sample_idx] = True
else:
input_ids = np.concatenate([input_ids[1:], np.array([token])], axis=-1)
sample_idx = min(input_length - 1, sample_idx + 1)
return np.array(output)
# tokenizes initial prompt
def tokenize_prompt(midi, tokenizer):
return tokenizer(midi)
# loads prompt MIDI file
def file_prompt(path):
midi = MidiFile(path)
return midi
def main(args):
logger.info("Beginning generation script.")
key = jax.random.PRNGKey(args.seed)
logger.info(f"Using PRNG key {args.seed}")
seed_others(args.seed)
logger.info("Loading config.")
config = load_config(args.config)
logger.info(f"Loading tokenizer from '{args.tokenizer}'")
|
def load_config(config_path):
with open(config_path, mode="r") as f:
data = f.read()
json_dict = json.loads(data)
return SimpleNamespace(**json_dict)
@eqx.filter_jit
@eqx.debug.assert_max_traces(max_traces=1)
def generate_step(model, inputs, length, key, temperature):
logits = model(**inputs)
logits = jnp.take(logits, length - 1, axis=0)
if temperature == 0.0:
# argmax sampling
return jnp.argmax(logits, axis=-1)
logits = logits / temperature
return jax.random.categorical(key, logits, axis=-1)
def generate_loop(
model,
initial_input,
temperature,
key,
max_to_generate: Optional[int] = None,
model_max_positions: int = 1024,
output_generated_only: bool = False,
) -> np.array:
sample_idx = initial_input.shape[0]
if output_generated_only:
output = []
else:
output = initial_input.tolist()
if max_to_generate is None:
DEFAULT_MAX = 1000
max_to_generate = DEFAULT_MAX
input_length = sample_idx + max_to_generate
if input_length > model_max_positions - 1:
input_length = model_max_positions - 1
position_ids = np.arange(input_length)
mask = np.concatenate(
[
np.ones((sample_idx,), dtype=bool),
np.zeros((input_length - sample_idx,), dtype=bool),
],
axis=-1,
dtype=bool,
)
input_ids = np.pad(initial_input, ((0, input_length - sample_idx),))
# TODO: maybe replace with jax.lax.scan loop for faster generation
for _ in tqdm.trange(max_to_generate):
key, subkey = jax.random.split(key)
inputs = dict(input_ids=input_ids, position_ids=position_ids, mask=mask)
token = generate_step(model, inputs, np.array(sample_idx), subkey, temperature).item()
output.append(token)
if sample_idx < input_length:
input_ids[sample_idx] = token
mask[sample_idx] = True
else:
input_ids = np.concatenate([input_ids[1:], np.array([token])], axis=-1)
sample_idx = min(input_length - 1, sample_idx + 1)
return np.array(output)
# tokenizes initial prompt
def tokenize_prompt(midi, tokenizer):
return tokenizer(midi)
# loads prompt MIDI file
def file_prompt(path):
midi = MidiFile(path)
return midi
def main(args):
logger.info("Beginning generation script.")
key = jax.random.PRNGKey(args.seed)
logger.info(f"Using PRNG key {args.seed}")
seed_others(args.seed)
logger.info("Loading config.")
config = load_config(args.config)
logger.info(f"Loading tokenizer from '{args.tokenizer}'") | tokenizer = get_pretrained_tokenizer(args.tokenizer) | 0 | 2023-11-13 07:31:30+00:00 | 2k |
dazhangyu123/ACMIL | architecture/ibmil.py | [
{
"identifier": "Classifier_1fc",
"path": "architecture/network.py",
"snippet": "class Classifier_1fc(nn.Module):\n def __init__(self, n_channels, n_classes, droprate=0.0):\n super(Classifier_1fc, self).__init__()\n self.fc = nn.Linear(n_channels, n_classes)\n self.droprate = dro... | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from architecture.network import Classifier_1fc, DimReduction
| 694 |
class Attention_Gated(nn.Module):
def __init__(self, L=512, D=128, K=1):
super(Attention_Gated, self).__init__()
self.L = L
self.D = D
self.K = K
self.attention_V = nn.Sequential(
nn.Linear(self.L, self.D),
nn.Tanh()
)
self.attention_U = nn.Sequential(
nn.Linear(self.L, self.D),
nn.Sigmoid()
)
self.attention_weights = nn.Linear(self.D, self.K)
def forward(self, x):
## x: N x L
A_V = self.attention_V(x) # NxD
A_U = self.attention_U(x) # NxD
A = self.attention_weights(A_V * A_U) # NxK
A = torch.transpose(A, 1, 0) # KxN
return A ### K x N
class IBMIL(nn.Module):
def __init__(self, conf, confounder_dim=128, confounder_merge='cat'):
super(IBMIL, self).__init__()
self.confounder_merge = confounder_merge
assert confounder_merge in ['cat', 'add', 'sub']
self.dimreduction = DimReduction(conf.D_feat, conf.D_inner)
self.attention = Attention_Gated(conf.D_inner, 128, 1)
|
class Attention_Gated(nn.Module):
def __init__(self, L=512, D=128, K=1):
super(Attention_Gated, self).__init__()
self.L = L
self.D = D
self.K = K
self.attention_V = nn.Sequential(
nn.Linear(self.L, self.D),
nn.Tanh()
)
self.attention_U = nn.Sequential(
nn.Linear(self.L, self.D),
nn.Sigmoid()
)
self.attention_weights = nn.Linear(self.D, self.K)
def forward(self, x):
## x: N x L
A_V = self.attention_V(x) # NxD
A_U = self.attention_U(x) # NxD
A = self.attention_weights(A_V * A_U) # NxK
A = torch.transpose(A, 1, 0) # KxN
return A ### K x N
class IBMIL(nn.Module):
def __init__(self, conf, confounder_dim=128, confounder_merge='cat'):
super(IBMIL, self).__init__()
self.confounder_merge = confounder_merge
assert confounder_merge in ['cat', 'add', 'sub']
self.dimreduction = DimReduction(conf.D_feat, conf.D_inner)
self.attention = Attention_Gated(conf.D_inner, 128, 1)
| self.classifier = Classifier_1fc(conf.D_inner, conf.n_class, 0)
| 0 | 2023-11-12 14:07:34+00:00 | 2k |
Kav-K/Described | services/openai_service.py | [
{
"identifier": "EnvService",
"path": "services/environment_service.py",
"snippet": "class EnvService:\n # To be expanded upon later!\n def __init__(self):\n self.env = {}\n\n @staticmethod\n def environment_path_with_fallback(env_name, relative_fallback=None):\n directory = os... | import traceback
import aiohttp
import backoff
from services.environment_service import EnvService
from services.prompts.image_analysis_prompt import IMAGE_ANALYSIS_PROMPT | 1,461 |
def backoff_handler_request(details):
print(
f"Backing off {details['wait']:0.1f} seconds after {details['tries']} tries calling function {details['target']} | "
f"{details['exception'].args[0]}"
)
class OpenAIExecutor:
def __init__(self):
self.openai_api_key = EnvService.get_openai_api_key()
try:
|
def backoff_handler_request(details):
print(
f"Backing off {details['wait']:0.1f} seconds after {details['tries']} tries calling function {details['target']} | "
f"{details['exception'].args[0]}"
)
class OpenAIExecutor:
def __init__(self):
self.openai_api_key = EnvService.get_openai_api_key()
try: | self.ANALYSIS_PRETEXT = IMAGE_ANALYSIS_PROMPT | 1 | 2023-11-14 02:22:13+00:00 | 2k |
juftin/hatch-pip-compile | tests/test_installer.py | [
{
"identifier": "HatchPipCompileError",
"path": "hatch_pip_compile/exceptions.py",
"snippet": "class HatchPipCompileError(Exception):\n \"\"\"\n Base exception for hatch-pip-compile\n \"\"\""
},
{
"identifier": "PluginInstaller",
"path": "hatch_pip_compile/installer.py",
"snippe... | from typing import Dict, Type
from unittest.mock import Mock
from hatch_pip_compile.exceptions import HatchPipCompileError
from hatch_pip_compile.installer import PluginInstaller
from tests.conftest import PipCompileFixture
import pytest | 1,134 | """
Installation Tests
"""
def test_pip_install_dependencies(mock_check_command: Mock, pip_compile: PipCompileFixture) -> None:
"""
Assert the `pip` installation command is called with the expected arguments
"""
pip_compile.default_environment.create()
pip_compile.default_environment.installer.install_dependencies()
expected_call = [
"python",
"-u",
"-m",
"pip",
"install",
"--disable-pip-version-check",
"--no-python-version-warning",
"-q",
"--requirement",
]
call_args = list(mock_check_command.call_args)[0][0][:-1]
assert call_args == expected_call
@pytest.mark.parametrize("installer", ["pip", "pip-sync"])
def test_installer_type(
installer: str, installer_dict: Dict[str, Type[PluginInstaller]], pip_compile: PipCompileFixture
) -> None:
"""
Test the `pip-compile-installer` configuration option
"""
pip_compile.toml_doc["tool"]["hatch"]["envs"]["default"]["pip-compile-installer"] = installer
pip_compile.update_pyproject()
updated_environment = pip_compile.reload_environment("default")
assert isinstance(updated_environment.installer, installer_dict[installer])
def test_installer_unknown(pip_compile: PipCompileFixture) -> None:
"""
Test that an exception is raised when an unknown installer is configured
"""
pip_compile.toml_doc["tool"]["hatch"]["envs"]["default"]["pip-compile-installer"] = "unknown"
pip_compile.update_pyproject()
| """
Installation Tests
"""
def test_pip_install_dependencies(mock_check_command: Mock, pip_compile: PipCompileFixture) -> None:
"""
Assert the `pip` installation command is called with the expected arguments
"""
pip_compile.default_environment.create()
pip_compile.default_environment.installer.install_dependencies()
expected_call = [
"python",
"-u",
"-m",
"pip",
"install",
"--disable-pip-version-check",
"--no-python-version-warning",
"-q",
"--requirement",
]
call_args = list(mock_check_command.call_args)[0][0][:-1]
assert call_args == expected_call
@pytest.mark.parametrize("installer", ["pip", "pip-sync"])
def test_installer_type(
installer: str, installer_dict: Dict[str, Type[PluginInstaller]], pip_compile: PipCompileFixture
) -> None:
"""
Test the `pip-compile-installer` configuration option
"""
pip_compile.toml_doc["tool"]["hatch"]["envs"]["default"]["pip-compile-installer"] = installer
pip_compile.update_pyproject()
updated_environment = pip_compile.reload_environment("default")
assert isinstance(updated_environment.installer, installer_dict[installer])
def test_installer_unknown(pip_compile: PipCompileFixture) -> None:
"""
Test that an exception is raised when an unknown installer is configured
"""
pip_compile.toml_doc["tool"]["hatch"]["envs"]["default"]["pip-compile-installer"] = "unknown"
pip_compile.update_pyproject() | with pytest.raises(HatchPipCompileError): | 0 | 2023-11-10 00:34:00+00:00 | 2k |
google-deepmind/pix2act | pix2act/tasks/miniwob/search/write_value_fn_tf_examples.py | [
{
"identifier": "tf_utils",
"path": "pix2act/common/tf_utils.py",
"snippet": "def add_bytes_feature(\n example: tf.train.Example, key: str, value: bytes\n) -> None:\ndef add_text_feature(example: tf.train.Example, key: str, value: str) -> None:\ndef get_bytes_feature(example: tf.train.Example, key: s... | from absl import app
from absl import flags
from pix2act.common import tf_utils
from pix2act.tasks.miniwob import episode_pb2
from pix2act.tasks.miniwob.search import reward_utils
import apache_beam as beam
import tensorflow as tf | 820 | # Copyright 2023 The pix2act Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""Converts episodes to tf examples for training value function approximator.
"""
FLAGS = flags.FLAGS
flags.DEFINE_list("inputs", "", "Input tfrecord files of Episodes.")
flags.DEFINE_string("output_dir", "", "Output location for tf examples.")
flags.DEFINE_float(
"reward_threshold",
0.8,
"Demonstrations below this threshold will be discarded.",
)
class ConvertEpisode(beam.DoFn):
"""Convert episode to tf examples."""
def process(self, episode):
if not episode.task_name:
beam.metrics.Metrics.counter("ConvertEpisode", "no_task_name").inc()
elif not episode.steps:
beam.metrics.Metrics.counter("no_steps", episode.task_name).inc()
elif episode.raw_reward < FLAGS.reward_threshold:
beam.metrics.Metrics.counter(
"failed_demonstration", episode.task_name
).inc()
else:
beam.metrics.Metrics.counter("num_demos", episode.task_name).inc()
try:
total_steps = len(episode.steps)
for step_idx, step in enumerate(episode.steps):
steps_to_go = total_steps - step_idx
surrogate_reward = reward_utils.compute_surrogate_reward(
episode.raw_reward, steps_to_go
)
value_fn_target = reward_utils.surrogate_reward_to_value_fn_target(
surrogate_reward
)
example = tf.train.Example()
| # Copyright 2023 The pix2act Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""Converts episodes to tf examples for training value function approximator.
"""
FLAGS = flags.FLAGS
flags.DEFINE_list("inputs", "", "Input tfrecord files of Episodes.")
flags.DEFINE_string("output_dir", "", "Output location for tf examples.")
flags.DEFINE_float(
"reward_threshold",
0.8,
"Demonstrations below this threshold will be discarded.",
)
class ConvertEpisode(beam.DoFn):
"""Convert episode to tf examples."""
def process(self, episode):
if not episode.task_name:
beam.metrics.Metrics.counter("ConvertEpisode", "no_task_name").inc()
elif not episode.steps:
beam.metrics.Metrics.counter("no_steps", episode.task_name).inc()
elif episode.raw_reward < FLAGS.reward_threshold:
beam.metrics.Metrics.counter(
"failed_demonstration", episode.task_name
).inc()
else:
beam.metrics.Metrics.counter("num_demos", episode.task_name).inc()
try:
total_steps = len(episode.steps)
for step_idx, step in enumerate(episode.steps):
steps_to_go = total_steps - step_idx
surrogate_reward = reward_utils.compute_surrogate_reward(
episode.raw_reward, steps_to_go
)
value_fn_target = reward_utils.surrogate_reward_to_value_fn_target(
surrogate_reward
)
example = tf.train.Example()
| tf_utils.add_bytes_feature(example, "image", step.screenshot_png) | 0 | 2023-11-13 22:50:55+00:00 | 2k |
zhang-tao-whu/DVIS_Plus | mask2former/modeling/meta_arch/mask_former_head.py | [
{
"identifier": "build_transformer_decoder",
"path": "mask2former/modeling/transformer_decoder/maskformer_transformer_decoder.py",
"snippet": "def build_transformer_decoder(cfg, in_channels, mask_classification=True):\n \"\"\"\n Build a instance embedding branch from `cfg.MODEL.INS_EMBED_HEAD.NAME... | import logging
import fvcore.nn.weight_init as weight_init
from copy import deepcopy
from typing import Callable, Dict, List, Optional, Tuple, Union
from torch import nn
from torch.nn import functional as F
from detectron2.config import configurable
from detectron2.layers import Conv2d, ShapeSpec, get_norm
from detectron2.modeling import SEM_SEG_HEADS_REGISTRY
from ..transformer_decoder.maskformer_transformer_decoder import build_transformer_decoder
from ..pixel_decoder.fpn import build_pixel_decoder | 1,271 | # Copyright (c) Facebook, Inc. and its affiliates.
@SEM_SEG_HEADS_REGISTRY.register()
class MaskFormerHead(nn.Module):
_version = 2
def _load_from_state_dict(
self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
):
version = local_metadata.get("version", None)
if version is None or version < 2:
# Do not warn if train from scratch
scratch = True
logger = logging.getLogger(__name__)
for k in list(state_dict.keys()):
newk = k
# if "sem_seg_head" in k and not k.startswith(prefix + "predictor"):
# newk = k.replace(prefix, prefix + "pixel_decoder.")
# # logger.debug(f"{k} ==> {newk}")
if newk != k:
state_dict[newk] = state_dict[k]
del state_dict[k]
scratch = False
if not scratch:
logger.warning(
f"Weight format of {self.__class__.__name__} have changed! "
"Please upgrade your models. Applying automatic conversion now ..."
)
@configurable
def __init__(
self,
input_shape: Dict[str, ShapeSpec],
*,
num_classes: int,
pixel_decoder: nn.Module,
loss_weight: float = 1.0,
ignore_value: int = -1,
return_transformer_feature: bool = False,
# extra parameters
transformer_predictor: nn.Module,
transformer_in_feature: str,
):
"""
NOTE: this interface is experimental.
Args:
input_shape: shapes (channels and stride) of the input features
num_classes: number of classes to predict
pixel_decoder: the pixel decoder module
loss_weight: loss weight
ignore_value: category id to be ignored during training.
transformer_predictor: the transformer decoder that makes prediction
transformer_in_feature: input feature name to the transformer_predictor
"""
super().__init__()
input_shape = sorted(input_shape.items(), key=lambda x: x[1].stride)
self.in_features = [k for k, v in input_shape]
feature_strides = [v.stride for k, v in input_shape]
feature_channels = [v.channels for k, v in input_shape]
self.ignore_value = ignore_value
self.common_stride = 4
self.loss_weight = loss_weight
self.return_transformer_feature = return_transformer_feature
self.pixel_decoder = pixel_decoder
self.predictor = transformer_predictor
self.transformer_in_feature = transformer_in_feature
self.num_classes = num_classes
@classmethod
def from_config(cls, cfg, input_shape: Dict[str, ShapeSpec]):
# figure out in_channels to transformer predictor
if cfg.MODEL.MASK_FORMER.TRANSFORMER_IN_FEATURE == "transformer_encoder":
transformer_predictor_in_channels = cfg.MODEL.SEM_SEG_HEAD.CONVS_DIM
elif cfg.MODEL.MASK_FORMER.TRANSFORMER_IN_FEATURE == "pixel_embedding":
transformer_predictor_in_channels = cfg.MODEL.SEM_SEG_HEAD.MASK_DIM
elif cfg.MODEL.MASK_FORMER.TRANSFORMER_IN_FEATURE == "multi_scale_pixel_decoder": # for maskformer2
transformer_predictor_in_channels = cfg.MODEL.SEM_SEG_HEAD.CONVS_DIM
else:
transformer_predictor_in_channels = input_shape[cfg.MODEL.MASK_FORMER.TRANSFORMER_IN_FEATURE].channels
return {
"input_shape": {
k: v for k, v in input_shape.items() if k in cfg.MODEL.SEM_SEG_HEAD.IN_FEATURES
},
"ignore_value": cfg.MODEL.SEM_SEG_HEAD.IGNORE_VALUE,
"return_transformer_feature": cfg.MODEL.SEM_SEG_HEAD.RETURN_TRANSFORMER_FEATURE,
"num_classes": cfg.MODEL.SEM_SEG_HEAD.NUM_CLASSES,
"pixel_decoder": build_pixel_decoder(cfg, input_shape),
"loss_weight": cfg.MODEL.SEM_SEG_HEAD.LOSS_WEIGHT,
"transformer_in_feature": cfg.MODEL.MASK_FORMER.TRANSFORMER_IN_FEATURE,
| # Copyright (c) Facebook, Inc. and its affiliates.
@SEM_SEG_HEADS_REGISTRY.register()
class MaskFormerHead(nn.Module):
_version = 2
def _load_from_state_dict(
self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
):
version = local_metadata.get("version", None)
if version is None or version < 2:
# Do not warn if train from scratch
scratch = True
logger = logging.getLogger(__name__)
for k in list(state_dict.keys()):
newk = k
# if "sem_seg_head" in k and not k.startswith(prefix + "predictor"):
# newk = k.replace(prefix, prefix + "pixel_decoder.")
# # logger.debug(f"{k} ==> {newk}")
if newk != k:
state_dict[newk] = state_dict[k]
del state_dict[k]
scratch = False
if not scratch:
logger.warning(
f"Weight format of {self.__class__.__name__} have changed! "
"Please upgrade your models. Applying automatic conversion now ..."
)
@configurable
def __init__(
self,
input_shape: Dict[str, ShapeSpec],
*,
num_classes: int,
pixel_decoder: nn.Module,
loss_weight: float = 1.0,
ignore_value: int = -1,
return_transformer_feature: bool = False,
# extra parameters
transformer_predictor: nn.Module,
transformer_in_feature: str,
):
"""
NOTE: this interface is experimental.
Args:
input_shape: shapes (channels and stride) of the input features
num_classes: number of classes to predict
pixel_decoder: the pixel decoder module
loss_weight: loss weight
ignore_value: category id to be ignored during training.
transformer_predictor: the transformer decoder that makes prediction
transformer_in_feature: input feature name to the transformer_predictor
"""
super().__init__()
input_shape = sorted(input_shape.items(), key=lambda x: x[1].stride)
self.in_features = [k for k, v in input_shape]
feature_strides = [v.stride for k, v in input_shape]
feature_channels = [v.channels for k, v in input_shape]
self.ignore_value = ignore_value
self.common_stride = 4
self.loss_weight = loss_weight
self.return_transformer_feature = return_transformer_feature
self.pixel_decoder = pixel_decoder
self.predictor = transformer_predictor
self.transformer_in_feature = transformer_in_feature
self.num_classes = num_classes
@classmethod
def from_config(cls, cfg, input_shape: Dict[str, ShapeSpec]):
# figure out in_channels to transformer predictor
if cfg.MODEL.MASK_FORMER.TRANSFORMER_IN_FEATURE == "transformer_encoder":
transformer_predictor_in_channels = cfg.MODEL.SEM_SEG_HEAD.CONVS_DIM
elif cfg.MODEL.MASK_FORMER.TRANSFORMER_IN_FEATURE == "pixel_embedding":
transformer_predictor_in_channels = cfg.MODEL.SEM_SEG_HEAD.MASK_DIM
elif cfg.MODEL.MASK_FORMER.TRANSFORMER_IN_FEATURE == "multi_scale_pixel_decoder": # for maskformer2
transformer_predictor_in_channels = cfg.MODEL.SEM_SEG_HEAD.CONVS_DIM
else:
transformer_predictor_in_channels = input_shape[cfg.MODEL.MASK_FORMER.TRANSFORMER_IN_FEATURE].channels
return {
"input_shape": {
k: v for k, v in input_shape.items() if k in cfg.MODEL.SEM_SEG_HEAD.IN_FEATURES
},
"ignore_value": cfg.MODEL.SEM_SEG_HEAD.IGNORE_VALUE,
"return_transformer_feature": cfg.MODEL.SEM_SEG_HEAD.RETURN_TRANSFORMER_FEATURE,
"num_classes": cfg.MODEL.SEM_SEG_HEAD.NUM_CLASSES,
"pixel_decoder": build_pixel_decoder(cfg, input_shape),
"loss_weight": cfg.MODEL.SEM_SEG_HEAD.LOSS_WEIGHT,
"transformer_in_feature": cfg.MODEL.MASK_FORMER.TRANSFORMER_IN_FEATURE, | "transformer_predictor": build_transformer_decoder( | 0 | 2023-11-14 10:55:11+00:00 | 2k |
teamreboott/data-modori | data_modori/ops/filter/language_id_score_filter.py | [
{
"identifier": "Fields",
"path": "data_modori/utils/constant.py",
"snippet": "class Fields(object):\n stats = DEFAULT_PREFIX + 'stats__'\n meta = DEFAULT_PREFIX + 'meta__'\n context = DEFAULT_PREFIX + 'context__'\n suffix = DEFAULT_PREFIX + 'suffix__'"
},
{
"identifier": "StatsKeys"... | from jsonargparse.typing import ClosedUnitInterval
from loguru import logger
from data_modori.utils.constant import Fields, StatsKeys
from data_modori.utils.model_utils import prepare_model, get_model
from ..base_op import OPERATORS, Filter | 1,416 |
@OPERATORS.register_module('language_id_score_filter')
class LanguageIDScoreFilter(Filter):
"""Filter to keep samples in a specific language with confidence score
larger than a specific min value."""
def __init__(self,
lang: str = '',
min_score: ClosedUnitInterval = 0.8,
*args,
**kwargs):
"""
Initialization method.
:param lang: Samples in which language to keep.
:param min_score: The min language identification confidence
scores of samples to keep.
:param args: extra args
:param kwargs: extra args
"""
super().__init__(*args, **kwargs)
self.lang = lang
self.min_score = min_score
self.model_key = prepare_model(lang=lang, model_type='fasttext')
def compute_stats(self, sample):
# check if it's computed already
if StatsKeys.lang in sample[
Fields.stats] and StatsKeys.lang_score in sample[Fields.stats]:
return sample
text = sample[self.text_key].lower().replace('\n', ' ')
|
@OPERATORS.register_module('language_id_score_filter')
class LanguageIDScoreFilter(Filter):
"""Filter to keep samples in a specific language with confidence score
larger than a specific min value."""
def __init__(self,
lang: str = '',
min_score: ClosedUnitInterval = 0.8,
*args,
**kwargs):
"""
Initialization method.
:param lang: Samples in which language to keep.
:param min_score: The min language identification confidence
scores of samples to keep.
:param args: extra args
:param kwargs: extra args
"""
super().__init__(*args, **kwargs)
self.lang = lang
self.min_score = min_score
self.model_key = prepare_model(lang=lang, model_type='fasttext')
def compute_stats(self, sample):
# check if it's computed already
if StatsKeys.lang in sample[
Fields.stats] and StatsKeys.lang_score in sample[Fields.stats]:
return sample
text = sample[self.text_key].lower().replace('\n', ' ') | ft_model = get_model(self.model_key, lang=self.lang, model_type='fasttext') | 3 | 2023-11-13 04:52:55+00:00 | 2k |
52phm/pylmkit | pylmkit/tools/search.py | [
{
"identifier": "Document",
"path": "pylmkit/utils/data_utils.py",
"snippet": "class Document(BaseModel):\n page_content: str\n metadata: dict = Field(default_factory=dict)\n type: str = \"Document\"\n\n def __str__(self):\n return f\"Document(page_content='{self.page_content}', metad... | from duckduckgo_search import DDGS
from pylmkit.utils.data_utils import Document
from pylmkit.core.base import BaseKnowledgeBase | 1,104 |
class WebSearch(DDGS, BaseKnowledgeBase):
def __init__(
self,
topk=5,
backend="api",
region="wt-wt",
timelimit=None,
safesearch="moderate",
init_documents=None,
timeout=10,
headers=None,
proxies=None
):
DDGS.__init__(
self,
timeout=timeout,
headers=headers,
proxies=proxies
)
BaseKnowledgeBase.__init__(self, init_documents=init_documents)
self.topk = int(topk)
self.backend = backend
self.region = region
self.timelimit = timelimit
self.safesearch = safesearch
def get(self, keyword):
if keyword:
search_gen = super().text(keywords=keyword,
backend=self.backend,
region=self.region,
max_results=self.topk,
timelimit=self.timelimit,
safesearch=self.safesearch
)
for i, page in enumerate(list(search_gen)):
if page:
|
class WebSearch(DDGS, BaseKnowledgeBase):
def __init__(
self,
topk=5,
backend="api",
region="wt-wt",
timelimit=None,
safesearch="moderate",
init_documents=None,
timeout=10,
headers=None,
proxies=None
):
DDGS.__init__(
self,
timeout=timeout,
headers=headers,
proxies=proxies
)
BaseKnowledgeBase.__init__(self, init_documents=init_documents)
self.topk = int(topk)
self.backend = backend
self.region = region
self.timelimit = timelimit
self.safesearch = safesearch
def get(self, keyword):
if keyword:
search_gen = super().text(keywords=keyword,
backend=self.backend,
region=self.region,
max_results=self.topk,
timelimit=self.timelimit,
safesearch=self.safesearch
)
for i, page in enumerate(list(search_gen)):
if page: | self.documents.append(Document( | 0 | 2023-11-18 10:31:58+00:00 | 2k |
hadican/failedkite | app.py | [
{
"identifier": "Config",
"path": "config.py",
"snippet": "class Config:\n def __init__(self):\n self.slack_token = self._get_env_variable('SLACK_TOKEN')\n self.default_slack_email = self._get_env_variable('DEFAULT_SLACK_EMAIL')\n self.author_mapping = self._load_author_mapping('... | import logging
from flask import Flask, request
from config import Config
from notification_service import NotificationService
from slack_client import SlackClient | 1,094 |
app = Flask(__name__)
logging.basicConfig(level=logging.INFO)
config = Config()
slack_client = SlackClient(token=config.slack_token)
|
app = Flask(__name__)
logging.basicConfig(level=logging.INFO)
config = Config()
slack_client = SlackClient(token=config.slack_token) | notification_service = NotificationService(slack_client, config) | 1 | 2023-11-11 20:35:31+00:00 | 2k |
PufferAI/pokegym | pokegym/environment.py | [
{
"identifier": "ACTIONS",
"path": "pokegym/pyboy_binding.py",
"snippet": "ACTIONS = (Down, Left, Right, Up, A, B, Start, Select)"
},
{
"identifier": "make_env",
"path": "pokegym/pyboy_binding.py",
"snippet": "def make_env(gb_path, headless=True, quiet=False, **kwargs):\n gb_path='pok... | from pdb import set_trace as T
from gymnasium import Env, spaces
from pokegym.pyboy_binding import (ACTIONS, make_env, open_state_file,
load_pyboy_state, run_action_on_emulator)
from pokegym import ram_map, game_map
import numpy as np
import os | 1,269 |
def play():
'''Creates an environment and plays it'''
env = Environment(rom_path='pokemon_red.gb', state_path=None, headless=False,
disable_input=False, sound=False, sound_emulated=False, verbose=True
)
env.reset()
env.game.set_emulation_speed(1)
# Display available actions
print("Available actions:")
|
def play():
'''Creates an environment and plays it'''
env = Environment(rom_path='pokemon_red.gb', state_path=None, headless=False,
disable_input=False, sound=False, sound_emulated=False, verbose=True
)
env.reset()
env.game.set_emulation_speed(1)
# Display available actions
print("Available actions:") | for idx, action in enumerate(ACTIONS): | 0 | 2023-11-16 18:34:28+00:00 | 2k |
AlexandrErohin/home-assistant-flightradar24 | custom_components/flightradar24/coordinator.py | [
{
"identifier": "BoundingBox",
"path": "custom_components/flightradar24/models.py",
"snippet": "class BoundingBox:\n \"\"\"Bounding box for retrieving state vectors.\"\"\"\n\n min_latitude: float\n max_latitude: float\n min_longitude: float\n max_longitude: float\n\n def validate(self)... | from typing import Any
from datetime import timedelta
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from homeassistant.helpers.device_registry import DeviceInfo
from .models import BoundingBox
from .const import (
DOMAIN,
URL,
DEFAULT_NAME,
EVENT_FLIGHTRADAR24_ENTRY,
EVENT_FLIGHTRADAR24_EXIT,
)
from logging import Logger
from FlightRadar24 import FlightRadar24API
import math
import pycountry | 669 | from __future__ import annotations
class FlightRadar24Coordinator(DataUpdateCoordinator[int]):
def __init__(
self,
hass: HomeAssistant,
bound: BoundingBox,
client: FlightRadar24API,
update_interval: int,
logger: Logger,
) -> None:
self._bound = bound
self._client = client
self._logger = logger
self.tracked: dict[int, dict[str, Any]] | None = None
self.entered = {}
self.exited = {}
self.device_info = DeviceInfo(
configuration_url=URL,
| from __future__ import annotations
class FlightRadar24Coordinator(DataUpdateCoordinator[int]):
def __init__(
self,
hass: HomeAssistant,
bound: BoundingBox,
client: FlightRadar24API,
update_interval: int,
logger: Logger,
) -> None:
self._bound = bound
self._client = client
self._logger = logger
self.tracked: dict[int, dict[str, Any]] | None = None
self.entered = {}
self.exited = {}
self.device_info = DeviceInfo(
configuration_url=URL, | identifiers={(DOMAIN, DEFAULT_NAME)}, | 1 | 2023-11-16 10:51:24+00:00 | 2k |
ej0cl6/TextEE | TextEE/models/QueryAndExtract/EAEmodel.py | [
{
"identifier": "Metadata",
"path": "TextEE/models/QueryAndExtract/metadata.py",
"snippet": "class Metadata(object):\n def __init__(self, metadata_path, dataset, type_set):\n self.pos_set = ['ADJ', 'ADP', 'ADV', 'AUX', 'CCONJ', 'DET', 'INTJ', 'NOUN', 'NUM', 'PART', 'PRON', 'PROPN',\n ... | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import ipdb
import ipdb
from transformers import BertConfig, RobertaConfig, BertModel, RobertaModel
from .metadata import Metadata
from .utils import pad_seq
from keras_preprocessing.sequence import pad_sequences | 676 |
class QueryAndExtractEAEModel(nn.Module):
def __init__(self, config, tokenizer, type_set):
super().__init__()
self.config = config
self.tokenizer = tokenizer
self.type_set = type_set
self.earl_model = EARLModel(config, tokenizer, type_set)
self.ner_model = NERModel(config, tokenizer)
def forward(self, batch):
ner_loss = self.ner_model(batch)
loss, score = self.earl_model(batch)
return loss, score, ner_loss
class EARLModel(nn.Module):
def __init__(self, config, tokenizer, type_set):
super().__init__()
self.config = config
self.tokenizer = tokenizer
self.tokenizer_pad_value = self.tokenizer.convert_tokens_to_ids([self.tokenizer.pad_token])[0]
self.type_set = type_set
|
class QueryAndExtractEAEModel(nn.Module):
def __init__(self, config, tokenizer, type_set):
super().__init__()
self.config = config
self.tokenizer = tokenizer
self.type_set = type_set
self.earl_model = EARLModel(config, tokenizer, type_set)
self.ner_model = NERModel(config, tokenizer)
def forward(self, batch):
ner_loss = self.ner_model(batch)
loss, score = self.earl_model(batch)
return loss, score, ner_loss
class EARLModel(nn.Module):
def __init__(self, config, tokenizer, type_set):
super().__init__()
self.config = config
self.tokenizer = tokenizer
self.tokenizer_pad_value = self.tokenizer.convert_tokens_to_ids([self.tokenizer.pad_token])[0]
self.type_set = type_set
| self.metadata = Metadata(config.metadata_path, self.config.dataset, type_set) | 0 | 2023-11-15 21:32:56+00:00 | 2k |
fofr/cog-sdxl-multi-controlnet-lora | controlnet.py | [
{
"identifier": "ControlNetPreprocessor",
"path": "controlnet_preprocess.py",
"snippet": "class ControlNetPreprocessor:\n ANNOTATOR_CLASSES = {\n \"none\": None,\n \"edge_canny\": CannyDetector,\n \"depth_leres\": LeresDetector,\n \"depth_midas\": MidasDetector,\n \... | import torch
from diffusers import ControlNetModel
from controlnet_preprocess import ControlNetPreprocessor
from weights_downloader import WeightsDownloader | 1,238 |
CONTROLNET_MODEL_CACHE = "./controlnet-cache"
CONTROLNET_URL = "https://weights.replicate.delivery/default/controlnet/sdxl-cn-canny-depth-softe-pose-qr.tar"
class ControlNet:
CONTROLNET_MODELS = [
"none",
"edge_canny",
"illusion",
"depth_leres",
"depth_midas",
"soft_edge_pidi",
"soft_edge_hed",
"lineart",
"lineart_anime",
"openpose",
# Preprocessors without an XL model yet
# "straight_edge_mlsd",
# "face_detector",
# "content_shuffle",
# "normal_bae",
# "segementation_sam",
]
def __init__(self, predictor):
WeightsDownloader.download_if_not_exists(CONTROLNET_URL, CONTROLNET_MODEL_CACHE)
self.predictor = predictor
self.controlnet_preprocessor = None
self.models = {}
def initialize_controlnet(self, model_name):
print("Initializing", model_name)
return ControlNetModel.from_pretrained(
model_name, cache_dir=CONTROLNET_MODEL_CACHE, torch_dtype=torch.float16
)
def get_model(self, controlnet_name):
if controlnet_name not in self.models:
if controlnet_name.startswith("edge_"):
self.models[controlnet_name] = self.initialize_controlnet("diffusers/controlnet-canny-sdxl-1.0")
elif controlnet_name.startswith("depth_"):
self.models[controlnet_name] = self.initialize_controlnet("diffusers/controlnet-depth-sdxl-1.0-small")
elif controlnet_name.startswith("soft_edge") or controlnet_name.startswith("lineart"):
self.models[controlnet_name] = self.initialize_controlnet("SargeZT/controlnet-sd-xl-1.0-softedge-dexined")
elif controlnet_name == "openpose":
self.models[controlnet_name] = self.initialize_controlnet("thibaud/controlnet-openpose-sdxl-1.0")
elif controlnet_name == "illusion":
self.models[controlnet_name] = self.initialize_controlnet("monster-labs/control_v1p_sdxl_qrcode_monster")
return self.models.get(controlnet_name)
def get_models(self, controlnet_names):
models = [
self.get_model(controlnet_name) for controlnet_name in controlnet_names
]
return list(filter(None, models))
def preprocess(self, image, controlnet_name):
# Illusion model needs no preprocessing
if controlnet_name == "illusion" or controlnet_name == "none":
return image
if self.controlnet_preprocessor is None:
|
CONTROLNET_MODEL_CACHE = "./controlnet-cache"
CONTROLNET_URL = "https://weights.replicate.delivery/default/controlnet/sdxl-cn-canny-depth-softe-pose-qr.tar"
class ControlNet:
CONTROLNET_MODELS = [
"none",
"edge_canny",
"illusion",
"depth_leres",
"depth_midas",
"soft_edge_pidi",
"soft_edge_hed",
"lineart",
"lineart_anime",
"openpose",
# Preprocessors without an XL model yet
# "straight_edge_mlsd",
# "face_detector",
# "content_shuffle",
# "normal_bae",
# "segementation_sam",
]
def __init__(self, predictor):
WeightsDownloader.download_if_not_exists(CONTROLNET_URL, CONTROLNET_MODEL_CACHE)
self.predictor = predictor
self.controlnet_preprocessor = None
self.models = {}
def initialize_controlnet(self, model_name):
print("Initializing", model_name)
return ControlNetModel.from_pretrained(
model_name, cache_dir=CONTROLNET_MODEL_CACHE, torch_dtype=torch.float16
)
def get_model(self, controlnet_name):
if controlnet_name not in self.models:
if controlnet_name.startswith("edge_"):
self.models[controlnet_name] = self.initialize_controlnet("diffusers/controlnet-canny-sdxl-1.0")
elif controlnet_name.startswith("depth_"):
self.models[controlnet_name] = self.initialize_controlnet("diffusers/controlnet-depth-sdxl-1.0-small")
elif controlnet_name.startswith("soft_edge") or controlnet_name.startswith("lineart"):
self.models[controlnet_name] = self.initialize_controlnet("SargeZT/controlnet-sd-xl-1.0-softedge-dexined")
elif controlnet_name == "openpose":
self.models[controlnet_name] = self.initialize_controlnet("thibaud/controlnet-openpose-sdxl-1.0")
elif controlnet_name == "illusion":
self.models[controlnet_name] = self.initialize_controlnet("monster-labs/control_v1p_sdxl_qrcode_monster")
return self.models.get(controlnet_name)
def get_models(self, controlnet_names):
models = [
self.get_model(controlnet_name) for controlnet_name in controlnet_names
]
return list(filter(None, models))
def preprocess(self, image, controlnet_name):
# Illusion model needs no preprocessing
if controlnet_name == "illusion" or controlnet_name == "none":
return image
if self.controlnet_preprocessor is None: | self.controlnet_preprocessor = ControlNetPreprocessor(self.predictor) | 0 | 2023-11-13 13:04:41+00:00 | 2k |
ahayler/s4c | utils/base_trainer.py | [
{
"identifier": "to",
"path": "utils/array_operations.py",
"snippet": "def to(data, device, non_blocking=True):\n if isinstance(data, dict):\n return {k: to(data[k], device, non_blocking=non_blocking) for k in data.keys()}\n elif isinstance(data, list):\n return [to(v, device, non_bl... | import json
import time
import ignite
import ignite.distributed as idist
import torch
from datetime import datetime
from pathlib import Path
from typing import Union
from omegaconf import OmegaConf
from ignite.contrib.engines import common
from ignite.contrib.handlers import TensorboardLogger
from ignite.contrib.handlers.base_logger import BaseHandler
from ignite.engine import Engine, Events, EventEnum
from ignite.handlers import Checkpoint, DiskSaver, global_step_from_engine
from ignite.utils import manual_seed, setup_logger
from torch.cuda.amp import autocast, GradScaler
from utils.array_operations import to
from utils.metrics import MeanMetric
from torch.backends import cudnn | 1,018 |
# used for debugging
torch.autograd.set_detect_anomaly(True)
def base_training(local_rank, config, get_dataflow, initialize, get_metrics, visualize):
# copy the segmentation mode to the data and model_conf part of the config
config['data']['segmentation_mode'] = config.get("segmentation_mode", None)
config['model_conf']['segmentation_mode'] = config.get("segmentation_mode", None)
rank = idist.get_rank()
manual_seed(config["seed"] + rank)
device = idist.device()
logger = setup_logger(name=config["name"])
log_basic_info(logger, config)
output_path = config["output_path"]
if rank == 0:
if config["stop_iteration"] is None:
now = datetime.now().strftime("%Y%m%d-%H%M%S")
else:
now = f"stop-on-{config['stop_iteration']}"
folder_name = f"{config['name']}_backend-{idist.backend()}-{idist.get_world_size()}_{now}"
output_path = Path(output_path) / folder_name
if not output_path.exists():
output_path.mkdir(parents=True)
config["output_path"] = output_path.as_posix()
logger.info(f"Output path: {config['output_path']}")
if "cuda" in device.type:
config["cuda device name"] = torch.cuda.get_device_name(local_rank)
# Setup dataflow, model, optimizer, criterion
loaders = get_dataflow(config, logger)
if len(loaders) == 2:
train_loader, test_loader = loaders
vis_loader = None
else:
train_loader, test_loader, vis_loader = loaders
if hasattr(train_loader, "dataset"):
logger.info(f"Dataset length: Train: {len(train_loader.dataset)}, Test: {len(test_loader.dataset)}")
config["num_iters_per_epoch"] = len(train_loader)
model, optimizer, criterion, lr_scheduler = initialize(config, logger)
logger.info(f"Model parameters: {sum(p.numel() for p in model.parameters())}")
# Let's now setup evaluator engine to perform model's validation and compute metrics
metrics = get_metrics(config, device)
|
# used for debugging
torch.autograd.set_detect_anomaly(True)
def base_training(local_rank, config, get_dataflow, initialize, get_metrics, visualize):
# copy the segmentation mode to the data and model_conf part of the config
config['data']['segmentation_mode'] = config.get("segmentation_mode", None)
config['model_conf']['segmentation_mode'] = config.get("segmentation_mode", None)
rank = idist.get_rank()
manual_seed(config["seed"] + rank)
device = idist.device()
logger = setup_logger(name=config["name"])
log_basic_info(logger, config)
output_path = config["output_path"]
if rank == 0:
if config["stop_iteration"] is None:
now = datetime.now().strftime("%Y%m%d-%H%M%S")
else:
now = f"stop-on-{config['stop_iteration']}"
folder_name = f"{config['name']}_backend-{idist.backend()}-{idist.get_world_size()}_{now}"
output_path = Path(output_path) / folder_name
if not output_path.exists():
output_path.mkdir(parents=True)
config["output_path"] = output_path.as_posix()
logger.info(f"Output path: {config['output_path']}")
if "cuda" in device.type:
config["cuda device name"] = torch.cuda.get_device_name(local_rank)
# Setup dataflow, model, optimizer, criterion
loaders = get_dataflow(config, logger)
if len(loaders) == 2:
train_loader, test_loader = loaders
vis_loader = None
else:
train_loader, test_loader, vis_loader = loaders
if hasattr(train_loader, "dataset"):
logger.info(f"Dataset length: Train: {len(train_loader.dataset)}, Test: {len(test_loader.dataset)}")
config["num_iters_per_epoch"] = len(train_loader)
model, optimizer, criterion, lr_scheduler = initialize(config, logger)
logger.info(f"Model parameters: {sum(p.numel() for p in model.parameters())}")
# Let's now setup evaluator engine to perform model's validation and compute metrics
metrics = get_metrics(config, device) | metrics_loss = {k: MeanMetric((lambda y: lambda x: x["loss_dict"][y])(k)) for k in criterion.get_loss_metric_names()} | 1 | 2023-11-12 21:53:27+00:00 | 2k |
Emmo00/alxcheck | alxcheck/checks/python.py | [
{
"identifier": "print_no_module_docstring",
"path": "alxcheck/utils/error_logging.py",
"snippet": "def print_no_module_docstring(file_path):\n print(Fore.RED + f\"{file_path} does not have Module DocString\" + Fore.RESET)"
},
{
"identifier": "print_no_function_docstring",
"path": "alxche... | import os
import ast
import subprocess
from ..utils.error_logging import (
print_no_module_docstring,
print_no_function_docstring,
print_no_class_docstring,
print_check_docstrings,
print_error_parsing_file,
) | 800 |
def check_file_is_executable(file_path):
flag = True
if not os.access(file_path, os.X_OK):
flag = False
return flag
def check_python_shebang(file_path):
flag = True
with open(file_path, "rb") as f:
first_line = f.readline().strip()
if first_line not in (b"#!/usr/bin/python3", b"#!/usr/bin/env python3"):
flag = False
return flag
def check_module_function_class_documentation(file_path):
flag = True
with open(file_path, "rb") as f:
content = f.read()
# remove shebang
if content.startswith(b"#!"):
if len(content.split(b"\n")) < 2:
content = ""
else:
content = content.split(b"\n", 1)[1]
tree = None
try:
tree = ast.parse(content)
except Exception:
print_error_parsing_file(file_path)
try:
if tree is None:
return
for node in ast.walk(tree):
# check module docstring
if isinstance(node, ast.Module):
if not isinstance(node.body[0].value, ast.Str):
flag = False
print_no_module_docstring(file_path)
return
# check function docstring
if isinstance(node, ast.FunctionDef) and not isinstance(
node.body[0].value, ast.Str
):
flag = False
print_no_function_docstring(file_path, node.name)
# check class docstring
if isinstance(node, ast.ClassDef) and not isinstance(
node.body[0].value, ast.Str
):
flag = False
print_no_class_docstring(file_path, node.name)
except Exception:
|
def check_file_is_executable(file_path):
flag = True
if not os.access(file_path, os.X_OK):
flag = False
return flag
def check_python_shebang(file_path):
flag = True
with open(file_path, "rb") as f:
first_line = f.readline().strip()
if first_line not in (b"#!/usr/bin/python3", b"#!/usr/bin/env python3"):
flag = False
return flag
def check_module_function_class_documentation(file_path):
flag = True
with open(file_path, "rb") as f:
content = f.read()
# remove shebang
if content.startswith(b"#!"):
if len(content.split(b"\n")) < 2:
content = ""
else:
content = content.split(b"\n", 1)[1]
tree = None
try:
tree = ast.parse(content)
except Exception:
print_error_parsing_file(file_path)
try:
if tree is None:
return
for node in ast.walk(tree):
# check module docstring
if isinstance(node, ast.Module):
if not isinstance(node.body[0].value, ast.Str):
flag = False
print_no_module_docstring(file_path)
return
# check function docstring
if isinstance(node, ast.FunctionDef) and not isinstance(
node.body[0].value, ast.Str
):
flag = False
print_no_function_docstring(file_path, node.name)
# check class docstring
if isinstance(node, ast.ClassDef) and not isinstance(
node.body[0].value, ast.Str
):
flag = False
print_no_class_docstring(file_path, node.name)
except Exception: | print_check_docstrings(file_path) | 3 | 2023-11-14 19:28:28+00:00 | 2k |
TimbreWatermarking/TimbreWatermarking | voice.clone/Fastspeech2/TTS/tts/utils/text/cleaners.py | [
{
"identifier": "abbreviations_en",
"path": "voice.clone/Fastspeech2/TTS/tts/utils/text/english/abbreviations.py",
"snippet": ""
},
{
"identifier": "normalize_numbers",
"path": "voice.clone/Fastspeech2/TTS/tts/utils/text/english/number_norm.py",
"snippet": "def normalize_numbers(text):\n... | import re
from anyascii import anyascii
from TTS.tts.utils.text.chinese_mandarin.numbers import replace_numbers_to_characters_in_text
from .english.abbreviations import abbreviations_en
from .english.number_norm import normalize_numbers as en_normalize_numbers
from .english.time_norm import expand_time_english
from .french.abbreviations import abbreviations_fr | 776 | """Set of default text cleaners"""
# TODO: pick the cleaner for languages dynamically
# Regular expression matching whitespace:
_whitespace_re = re.compile(r"\s+")
def expand_abbreviations(text, lang="en"):
if lang == "en":
_abbreviations = abbreviations_en
elif lang == "fr":
_abbreviations = abbreviations_fr
for regex, replacement in _abbreviations:
text = re.sub(regex, replacement, text)
return text
def lowercase(text):
return text.lower()
def collapse_whitespace(text):
return re.sub(_whitespace_re, " ", text).strip()
def convert_to_ascii(text):
return anyascii(text)
def remove_aux_symbols(text):
text = re.sub(r"[\<\>\(\)\[\]\"]+", "", text)
return text
def replace_symbols(text, lang="en"):
text = text.replace(";", ",")
text = text.replace("-", " ")
text = text.replace(":", ",")
if lang == "en":
text = text.replace("&", " and ")
elif lang == "fr":
text = text.replace("&", " et ")
elif lang == "pt":
text = text.replace("&", " e ")
return text
def basic_cleaners(text):
"""Basic pipeline that lowercases and collapses whitespace without transliteration."""
text = lowercase(text)
text = collapse_whitespace(text)
return text
def transliteration_cleaners(text):
"""Pipeline for non-English text that transliterates to ASCII."""
# text = convert_to_ascii(text)
text = lowercase(text)
text = collapse_whitespace(text)
return text
def basic_german_cleaners(text):
"""Pipeline for German text"""
text = lowercase(text)
text = collapse_whitespace(text)
return text
# TODO: elaborate it
def basic_turkish_cleaners(text):
"""Pipeline for Turkish text"""
text = text.replace("I", "ı")
text = lowercase(text)
text = collapse_whitespace(text)
return text
def english_cleaners(text):
"""Pipeline for English text, including number and abbreviation expansion."""
# text = convert_to_ascii(text)
text = lowercase(text)
| """Set of default text cleaners"""
# TODO: pick the cleaner for languages dynamically
# Regular expression matching whitespace:
_whitespace_re = re.compile(r"\s+")
def expand_abbreviations(text, lang="en"):
if lang == "en":
_abbreviations = abbreviations_en
elif lang == "fr":
_abbreviations = abbreviations_fr
for regex, replacement in _abbreviations:
text = re.sub(regex, replacement, text)
return text
def lowercase(text):
return text.lower()
def collapse_whitespace(text):
return re.sub(_whitespace_re, " ", text).strip()
def convert_to_ascii(text):
return anyascii(text)
def remove_aux_symbols(text):
text = re.sub(r"[\<\>\(\)\[\]\"]+", "", text)
return text
def replace_symbols(text, lang="en"):
text = text.replace(";", ",")
text = text.replace("-", " ")
text = text.replace(":", ",")
if lang == "en":
text = text.replace("&", " and ")
elif lang == "fr":
text = text.replace("&", " et ")
elif lang == "pt":
text = text.replace("&", " e ")
return text
def basic_cleaners(text):
"""Basic pipeline that lowercases and collapses whitespace without transliteration."""
text = lowercase(text)
text = collapse_whitespace(text)
return text
def transliteration_cleaners(text):
"""Pipeline for non-English text that transliterates to ASCII."""
# text = convert_to_ascii(text)
text = lowercase(text)
text = collapse_whitespace(text)
return text
def basic_german_cleaners(text):
"""Pipeline for German text"""
text = lowercase(text)
text = collapse_whitespace(text)
return text
# TODO: elaborate it
def basic_turkish_cleaners(text):
"""Pipeline for Turkish text"""
text = text.replace("I", "ı")
text = lowercase(text)
text = collapse_whitespace(text)
return text
def english_cleaners(text):
"""Pipeline for English text, including number and abbreviation expansion."""
# text = convert_to_ascii(text)
text = lowercase(text) | text = expand_time_english(text) | 2 | 2023-11-13 01:40:03+00:00 | 2k |
nillion-oss/tinysig | src/tinysig/network.py | [
{
"identifier": "add",
"path": "src/tinysig/utils.py",
"snippet": "def add(values: list[int], size: int) -> int:\n \"\"\"\n Calculate the sum of a list of integers modulo 'size'.\n\n Args:\n values (list[int]): A list of integers to be summed.\n size (int): The modulo value.\n\n ... | from dataclasses import dataclass, field
from typing import Dict, List, Union
from .utils import add, generate_additive_shares | 1,515 |
@dataclass
class Node:
""" Represents a node in the network."""
id: int
"""Identifier for the node."""
shares_db: Dict[str, int] = field(default_factory=dict)
"""Database for holding shares."""
open_db: Dict[str, int] = field(default_factory=dict)
"""Database for holding open values."""
he_public_keys: Dict[int, int] = field(default_factory=dict)
"""Dictionary for holding homomorphic encryption public keys."""
def get_share(self, label: str) -> None:
"""Retrieve a share from the 'shares_db'."""
return self.shares_db[label]
def get_open(self, label: str) -> None:
"""Retrieve an open value from the 'open_db'."""
return self.open_db[label]
def set_share(self, value, label: str) -> None:
"""Set a share in the 'shares_db'."""
self.shares_db[label] = value
def set_open(self, value, label: str) -> None:
"""Set an open value in the 'open_db'."""
self.open_db[label] = value
def delete_share(self, label: str) -> None:
"""Delete a share from the 'shares_db'."""
self.shares_db.pop(label)
def delete_open(self, label: str) -> None:
"""Delete an open value from the 'open_db'."""
self.open_db.pop(label)
@dataclass
class Client(Node):
"""Represents a client node in the network, inheriting from the 'Node' class."""
he_private_key: int = field(default=0)
class Network:
"""Represents a network of nodes and clients.
Manages the interactions and cryptographic operations within the network,
including sharing secrets, broadcasting values, and reconstructing shared values.
"""
nodes: List[Node]
"""List of nodes in the network."""
clients: List[Client]
"""List of clients in the network."""
q: int
"""Prime field."""
h: int
"""Multiplicative field generator."""
def __init__(self, N, q, h=2, C=1):
"""
Initialize the network with 'N' nodes, prime field 'q', field generator 'h', and 'C' clients.
Parameters:
N (int): Number of nodes in the network.
q (int): Prime field.
h (int): Multiplicative field generator (default is 2).
C (int): Number of clients in the network (default is 1).
"""
self.nodes = [Node(i+1) for i in range(N)]
self.clients = [Client(i+1) for i in range(C)]
self.N = N
self.q = q
self.h = h
def print(self):
"""Print a readable representation of the network, including nodes and clients with their databases."""
print(f"Network(N={len(self.nodes)}, q={self.q},")
print(" nodes=[")
for node in self.nodes:
print(f" Node(id={node.id},")
print(" shares_db={")
for key, value in node.shares_db.items():
print(f" {key}: {value},")
print(" },")
print(" public_keys={")
for key, value in node.he_public_keys.items():
print(f" {key}: {value},")
print(" },")
print(" open_db={")
for key, value in node.open_db.items():
print(f" {key}: {value},")
print(" }")
print(" )")
print(" ]\n)")
print(" clients=[")
for client in self.clients:
print(f" Client(id={client.id},")
print(" shares_db={")
for key, value in client.shares_db.items():
print(f" {key}: {value},")
print(" },")
print(" public_keys={")
for key, value in client.he_public_keys.items():
print(f" {key}: {value},")
print(" },")
print(f" private_keys={client.he_private_key},")
print(" open_db={")
for key, value in client.open_db.items():
print(f" {key}: {value},")
print(" }")
print(" )")
print(" ]\n)")
def reconstruct_local(self, type_share: str, get_label: str, save_label: str, party: Union[Client, Node]) -> None:
"""Locally reconstruct exponent share ('exp') or base ('base') shared value."""
type_label = "_sh_exp" if type_share == "exp" else "_sh_base"
p = (self.q - 1) if type_share == "exp" else self.q
shares = [party.get_share(get_label+type_label+"_node_"+str(node.id)) for node in self.nodes]
|
@dataclass
class Node:
""" Represents a node in the network."""
id: int
"""Identifier for the node."""
shares_db: Dict[str, int] = field(default_factory=dict)
"""Database for holding shares."""
open_db: Dict[str, int] = field(default_factory=dict)
"""Database for holding open values."""
he_public_keys: Dict[int, int] = field(default_factory=dict)
"""Dictionary for holding homomorphic encryption public keys."""
def get_share(self, label: str) -> None:
"""Retrieve a share from the 'shares_db'."""
return self.shares_db[label]
def get_open(self, label: str) -> None:
"""Retrieve an open value from the 'open_db'."""
return self.open_db[label]
def set_share(self, value, label: str) -> None:
"""Set a share in the 'shares_db'."""
self.shares_db[label] = value
def set_open(self, value, label: str) -> None:
"""Set an open value in the 'open_db'."""
self.open_db[label] = value
def delete_share(self, label: str) -> None:
"""Delete a share from the 'shares_db'."""
self.shares_db.pop(label)
def delete_open(self, label: str) -> None:
"""Delete an open value from the 'open_db'."""
self.open_db.pop(label)
@dataclass
class Client(Node):
"""Represents a client node in the network, inheriting from the 'Node' class."""
he_private_key: int = field(default=0)
class Network:
"""Represents a network of nodes and clients.
Manages the interactions and cryptographic operations within the network,
including sharing secrets, broadcasting values, and reconstructing shared values.
"""
nodes: List[Node]
"""List of nodes in the network."""
clients: List[Client]
"""List of clients in the network."""
q: int
"""Prime field."""
h: int
"""Multiplicative field generator."""
def __init__(self, N, q, h=2, C=1):
"""
Initialize the network with 'N' nodes, prime field 'q', field generator 'h', and 'C' clients.
Parameters:
N (int): Number of nodes in the network.
q (int): Prime field.
h (int): Multiplicative field generator (default is 2).
C (int): Number of clients in the network (default is 1).
"""
self.nodes = [Node(i+1) for i in range(N)]
self.clients = [Client(i+1) for i in range(C)]
self.N = N
self.q = q
self.h = h
def print(self):
"""Print a readable representation of the network, including nodes and clients with their databases."""
print(f"Network(N={len(self.nodes)}, q={self.q},")
print(" nodes=[")
for node in self.nodes:
print(f" Node(id={node.id},")
print(" shares_db={")
for key, value in node.shares_db.items():
print(f" {key}: {value},")
print(" },")
print(" public_keys={")
for key, value in node.he_public_keys.items():
print(f" {key}: {value},")
print(" },")
print(" open_db={")
for key, value in node.open_db.items():
print(f" {key}: {value},")
print(" }")
print(" )")
print(" ]\n)")
print(" clients=[")
for client in self.clients:
print(f" Client(id={client.id},")
print(" shares_db={")
for key, value in client.shares_db.items():
print(f" {key}: {value},")
print(" },")
print(" public_keys={")
for key, value in client.he_public_keys.items():
print(f" {key}: {value},")
print(" },")
print(f" private_keys={client.he_private_key},")
print(" open_db={")
for key, value in client.open_db.items():
print(f" {key}: {value},")
print(" }")
print(" )")
print(" ]\n)")
def reconstruct_local(self, type_share: str, get_label: str, save_label: str, party: Union[Client, Node]) -> None:
"""Locally reconstruct exponent share ('exp') or base ('base') shared value."""
type_label = "_sh_exp" if type_share == "exp" else "_sh_base"
p = (self.q - 1) if type_share == "exp" else self.q
shares = [party.get_share(get_label+type_label+"_node_"+str(node.id)) for node in self.nodes] | reconstructed = add(shares, p) | 0 | 2023-11-14 13:55:41+00:00 | 2k |
naver-ai/scob | lightning_modules/data_modules/transforms/transformer_decoder.py | [
{
"identifier": "TRANSFORM_NAME_TO_CLASS",
"path": "lightning_modules/data_modules/transforms/common.py",
"snippet": "TRANSFORM_NAME_TO_CLASS = {\n \"RandomRotate\": RandomRotate,\n \"CraftRandomCrop\": CraftRandomCrop,\n \"Resize\": Resize,\n \"ResizeOD\": ResizeOD,\n \"PhotometricDistor... | from typing import List, Tuple, Union
from lightning_modules.data_modules.transforms.common import (
TRANSFORM_NAME_TO_CLASS,
W_Compose,
)
from utils.dataset_utils import get_image_normalize_mean_and_std
import torch
import torchvision.transforms as transforms | 1,240 |
class TransformerDecoderTransformForFineTuning:
"""
- BEiT:
https://github.com/microsoft/unilm/blob/master/beit/datasets.py#L27
- TrOCR:
https://github.com/microsoft/unilm/blob/53995b4876464146365693396aaaa09e88a4494e/trocr/data_aug.py#L120
"""
def __init__(
self,
size: Union[Tuple, List],
transforms_list=None,
image_normalize="imagenet_default",
):
self.common_transform = self.__get_common_transform(size, transforms_list)
self.patch_transform = self.__get_patch_transform(image_normalize)
def __call__(self, img, quads):
for_patches, quads = self.common_transform(img, quads)
for_patches = self.patch_transform(for_patches)
return for_patches, quads
@staticmethod
def __get_common_transform(size, transforms_list):
tranforms = []
for transform_obj in transforms_list:
transform_class = TRANSFORM_NAME_TO_CLASS[transform_obj.name]
if transform_obj.params is not None:
params = dict(transform_obj.params)
else:
params = {}
if transform_obj.name in [
"Resize",
"ResizeOD",
"KeepAspectRatioBilinearResize",
"ResizeMultiview",
"MultiScaleResize",
"KeepAspectRatioBilinearResizeOD",
]:
params["size"] = size
elif transform_obj.name == "ResizeTwoPic":
params["size"] = size
tranforms.append(transform_class(**params))
return W_Compose(tranforms)
@staticmethod
def __get_patch_transform(image_normalize):
patch_trans = [transforms.ToTensor()]
|
class TransformerDecoderTransformForFineTuning:
"""
- BEiT:
https://github.com/microsoft/unilm/blob/master/beit/datasets.py#L27
- TrOCR:
https://github.com/microsoft/unilm/blob/53995b4876464146365693396aaaa09e88a4494e/trocr/data_aug.py#L120
"""
def __init__(
self,
size: Union[Tuple, List],
transforms_list=None,
image_normalize="imagenet_default",
):
self.common_transform = self.__get_common_transform(size, transforms_list)
self.patch_transform = self.__get_patch_transform(image_normalize)
def __call__(self, img, quads):
for_patches, quads = self.common_transform(img, quads)
for_patches = self.patch_transform(for_patches)
return for_patches, quads
@staticmethod
def __get_common_transform(size, transforms_list):
tranforms = []
for transform_obj in transforms_list:
transform_class = TRANSFORM_NAME_TO_CLASS[transform_obj.name]
if transform_obj.params is not None:
params = dict(transform_obj.params)
else:
params = {}
if transform_obj.name in [
"Resize",
"ResizeOD",
"KeepAspectRatioBilinearResize",
"ResizeMultiview",
"MultiScaleResize",
"KeepAspectRatioBilinearResizeOD",
]:
params["size"] = size
elif transform_obj.name == "ResizeTwoPic":
params["size"] = size
tranforms.append(transform_class(**params))
return W_Compose(tranforms)
@staticmethod
def __get_patch_transform(image_normalize):
patch_trans = [transforms.ToTensor()]
| mean_and_std = get_image_normalize_mean_and_std(image_normalize) | 2 | 2023-11-15 00:40:08+00:00 | 2k |
speckai/speck | src/python/speck/connections/connector.py | [
{
"identifier": "ChatLogger",
"path": "src/python/speck/chat/entities.py",
"snippet": "NOT_GIVEN = None\nclass Message(BaseModel):\nclass SafeDict(dict):\nclass Prompt(str):\nclass Response(BaseModel):\nclass MessageChunk(BaseModel):\nclass Stream:\nclass LogConfig(BaseModel):\n class Config:\nclass ... | from abc import ABC
from ..chat.entities import ChatLogger, LogConfig, Prompt, Response
from .providers import Providers | 1,521 |
class IConnector(ABC):
_client: "Speck"
def __init__(self, client: "Speck", provider: Providers):
self._client = client
self.provider = provider
# @abstractmethod
# def process_message(self, messages: Messages, model: str) -> str:
# pass
def _get_log_kwargs(self, prompt: Prompt, response: Response, **kwargs):
return {
"provider": self.provider,
"model": kwargs.get("model"),
"temperature": kwargs.get("temperature"),
"stream": kwargs.get("stream", False),
"prompt": prompt,
"config": kwargs,
"response": response,
}
def log(
self, *, log_config: LogConfig, prompt: Prompt, response: Response, **kwargs
):
# Todo: refactor to use config.log_chat !!!
|
class IConnector(ABC):
_client: "Speck"
def __init__(self, client: "Speck", provider: Providers):
self._client = client
self.provider = provider
# @abstractmethod
# def process_message(self, messages: Messages, model: str) -> str:
# pass
def _get_log_kwargs(self, prompt: Prompt, response: Response, **kwargs):
return {
"provider": self.provider,
"model": kwargs.get("model"),
"temperature": kwargs.get("temperature"),
"stream": kwargs.get("stream", False),
"prompt": prompt,
"config": kwargs,
"response": response,
}
def log(
self, *, log_config: LogConfig, prompt: Prompt, response: Response, **kwargs
):
# Todo: refactor to use config.log_chat !!! | ChatLogger.log( | 0 | 2023-11-15 05:46:05+00:00 | 2k |
chaiNNer-org/spandrel | src/spandrel/architectures/KBNet/arch/kbnet_s.py | [
{
"identifier": "KBAFunction",
"path": "src/spandrel/architectures/KBNet/arch/kb_utils.py",
"snippet": "class KBAFunction(torch.autograd.Function):\n @staticmethod\n def forward(ctx, x, att, selfk, selfg, selfb, selfw):\n B, nset, H, W = att.shape\n KK = selfk**2\n selfc = x.s... | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from .kb_utils import KBAFunction, LayerNorm2d, SimpleGate | 1,359 | # type: ignore
class KBBlock_s(nn.Module):
def __init__(
self, c, DW_Expand=2, FFN_Expand=2, nset=32, k=3, gc=4, lightweight=False
):
super().__init__()
self.k, self.c = k, c
self.nset = nset
dw_ch = int(c * DW_Expand)
ffn_ch = int(FFN_Expand * c)
self.g = c // gc
self.w = nn.Parameter(torch.zeros(1, nset, c * c // self.g * self.k**2))
self.b = nn.Parameter(torch.zeros(1, nset, c))
self.init_p(self.w, self.b)
| # type: ignore
class KBBlock_s(nn.Module):
def __init__(
self, c, DW_Expand=2, FFN_Expand=2, nset=32, k=3, gc=4, lightweight=False
):
super().__init__()
self.k, self.c = k, c
self.nset = nset
dw_ch = int(c * DW_Expand)
ffn_ch = int(FFN_Expand * c)
self.g = c // gc
self.w = nn.Parameter(torch.zeros(1, nset, c * c // self.g * self.k**2))
self.b = nn.Parameter(torch.zeros(1, nset, c))
self.init_p(self.w, self.b)
| self.norm1 = LayerNorm2d(c) | 1 | 2023-11-17 01:11:47+00:00 | 2k |
robocorp/llmstatemachine | src/llmstatemachine/workflow_agent.py | [
{
"identifier": "create_definition",
"path": "src/llmstatemachine/function.py",
"snippet": "def create_definition(func: Callable, goal: str) -> FunctionDefinition:\n source = inspect.getsource(func)\n client = OpenAI()\n response = client.chat.completions.create(\n model=\"gpt-4-1106-pre... | import json
from typing import Dict, Callable, Any, Tuple, List
from openai.types.chat.chat_completion_message import FunctionCall
from .function import create_definition, FunctionDefinition
from openai import OpenAI
from openai.types.chat import (
ChatCompletionMessageParam,
ChatCompletionMessage,
completion_create_params,
) | 756 |
TransitionFunction = Callable[[...], str]
FUNCTION_NAME = "ActionSelector"
MODEL = "gpt-4-1106-preview" # "gpt-4"
_CURRENT_STEPPING_AGENT = None
class WorkflowAgent:
def __init__(
self, goal: str, transitions: Dict[str, Dict[str, TransitionFunction]]
):
if "INIT" not in transitions:
raise Exception("Must define INIT state")
self._transitions: Dict[str, Dict[str, TransitionFunction]] = transitions
self._current_state = "INIT"
self.next_state = None
self._messages: List[ChatCompletionMessageParam] = []
self._messages.append({"role": "system", "content": goal})
self._client = OpenAI()
|
TransitionFunction = Callable[[...], str]
FUNCTION_NAME = "ActionSelector"
MODEL = "gpt-4-1106-preview" # "gpt-4"
_CURRENT_STEPPING_AGENT = None
class WorkflowAgent:
def __init__(
self, goal: str, transitions: Dict[str, Dict[str, TransitionFunction]]
):
if "INIT" not in transitions:
raise Exception("Must define INIT state")
self._transitions: Dict[str, Dict[str, TransitionFunction]] = transitions
self._current_state = "INIT"
self.next_state = None
self._messages: List[ChatCompletionMessageParam] = []
self._messages.append({"role": "system", "content": goal})
self._client = OpenAI() | self._func_defs: Dict[TransitionFunction, FunctionDefinition] = dict() | 1 | 2023-11-17 17:37:08+00:00 | 2k |
GoldenThrust/Virtual-Bank | api/debit_cards/serializers.py | [
{
"identifier": "DebitCard",
"path": "api/debit_cards/models.py",
"snippet": "class DebitCard(models.Model):\n account = models.ForeignKey(Account, on_delete=models.CASCADE)\n card_number = models.BigIntegerField()\n cvv = models.CharField(max_length=4)\n expiration_date = models.DateTimeFie... | from rest_framework import serializers
from .models import DebitCard, DebitCardTransaction
from .utils import generate_valid_credit_card_number, generate_cvv
from accounts.serializers import AccountSerializer
from transactions.serializers import TransactionSerializer | 790 |
class DebitCardSerializer(serializers.ModelSerializer):
card_number = serializers.CharField(read_only=True)
cvv = serializers.CharField(read_only=True)
created_date = serializers.DateTimeField(read_only=True)
account = AccountSerializer()
expiration_date = serializers.SerializerMethodField()
class Meta:
|
class DebitCardSerializer(serializers.ModelSerializer):
card_number = serializers.CharField(read_only=True)
cvv = serializers.CharField(read_only=True)
created_date = serializers.DateTimeField(read_only=True)
account = AccountSerializer()
expiration_date = serializers.SerializerMethodField()
class Meta: | model = DebitCard | 0 | 2023-11-10 12:39:38+00:00 | 2k |
Mj23978/OpenServer | openserver/core/vector_store/qdrant.py | [
{
"identifier": "get_config",
"path": "openserver/core/config/config.py",
"snippet": "def get_config(self, key: str, default: Optional[str] = None) -> str | None:\n return self.model_dump().get(key, default)"
},
{
"identifier": "VectorStore",
"path": "openserver/core/vector_store/base.py"... | from mimetypes import common_types
from typing import Dict, Optional, Union
from qdrant_client import QdrantClient
from qdrant_client.conversions import common_types
from langchain.vectorstores.qdrant import Qdrant
from ..config.config import get_config
from .base import VectorStore
from .embedding.base import BaseEmbedding | 783 | from __future__ import annotations
DictFilter = Dict[str, Union[str, int, bool, dict, list]]
MetadataFilter = Union[DictFilter, common_types.Filter]
def create_qdrant_client(api_key: Optional[str] = None, url: Optional[str] = None, port: Optional[int] = None
) -> QdrantClient:
if api_key is None:
qdrant_host_name = get_config("QDRANT_HOST_NAME") or "localhost"
qdrant_port = int(get_config("QDRANT_PORT", default="6333"))
qdrant_client = QdrantClient(host=qdrant_host_name, port=qdrant_port)
else:
qdrant_client = QdrantClient(api_key=api_key, url=url, port=port)
return qdrant_client
class QdrantVectorStore(VectorStore):
def __init__(
self,
client: QdrantClient,
collection_name: str,
| from __future__ import annotations
DictFilter = Dict[str, Union[str, int, bool, dict, list]]
MetadataFilter = Union[DictFilter, common_types.Filter]
def create_qdrant_client(api_key: Optional[str] = None, url: Optional[str] = None, port: Optional[int] = None
) -> QdrantClient:
if api_key is None:
qdrant_host_name = get_config("QDRANT_HOST_NAME") or "localhost"
qdrant_port = int(get_config("QDRANT_PORT", default="6333"))
qdrant_client = QdrantClient(host=qdrant_host_name, port=qdrant_port)
else:
qdrant_client = QdrantClient(api_key=api_key, url=url, port=port)
return qdrant_client
class QdrantVectorStore(VectorStore):
def __init__(
self,
client: QdrantClient,
collection_name: str, | embedding_model: BaseEmbedding, | 2 | 2023-11-11 00:32:31+00:00 | 2k |
TCLResearchEurope/torch-dag | torch_dag_algorithms/pruning/orbit.py | [
{
"identifier": "OrbitsDiscoveryStage",
"path": "torch_dag_algorithms/pruning/orbits_search_stage.py",
"snippet": "class OrbitsDiscoveryStage(enum.Enum):\n EXTENDED_ORBIT_DISCOVERY = 'extended_orbits_discovery'\n FINAL_ORBIT_DISCOVERY = 'final_orbits_discovery'\n CLASSIC_ATTENTION_DISCOVERY = '... | from typing import List
from typing import Set
from typing import Tuple
from torch_dag_algorithms.pruning.orbits_search_stage import OrbitsDiscoveryStage
from torch_dag.core.dag_module import InnerVertex | 911 |
class Orbit:
def __init__(self, color: int):
"""Basic orbit object that can represent either extended or final orbit. If orbit has `allow_for_further_processing` set to True then it can be processed by Orbitalizer by it's general mechanism. If set to False orbit won't be processed in any way and will be passed to orbitalization algorithm in unchanged state.
`_found_by` - indicates what stage lead to orbit being found. It's used in testing handling custom known patterns that are handled by hand. It also holds information that can be usefull durning debugging.
Args:
color (int): orbit color. has to be unique
allow_for_further_processing (bool, optional): If False orbit won't be process in any way. Defaults to True.
"""
self.color = color
self.vertices_in_scope: Set[InnerVertex] = set()
self.sources: List[InnerVertex] = []
self.sinks: List[InnerVertex] = []
self.end_path: List[Tuple[InnerVertex, InnerVertex]] = []
self.kmapps = None
self._discovery_stage = None
@property
|
class Orbit:
def __init__(self, color: int):
"""Basic orbit object that can represent either extended or final orbit. If orbit has `allow_for_further_processing` set to True then it can be processed by Orbitalizer by it's general mechanism. If set to False orbit won't be processed in any way and will be passed to orbitalization algorithm in unchanged state.
`_found_by` - indicates what stage lead to orbit being found. It's used in testing handling custom known patterns that are handled by hand. It also holds information that can be usefull durning debugging.
Args:
color (int): orbit color. has to be unique
allow_for_further_processing (bool, optional): If False orbit won't be process in any way. Defaults to True.
"""
self.color = color
self.vertices_in_scope: Set[InnerVertex] = set()
self.sources: List[InnerVertex] = []
self.sinks: List[InnerVertex] = []
self.end_path: List[Tuple[InnerVertex, InnerVertex]] = []
self.kmapps = None
self._discovery_stage = None
@property | def discovery_stage(self) -> OrbitsDiscoveryStage: | 0 | 2023-11-17 15:36:44+00:00 | 2k |
repeating/Binance-P2P-alerts-Telegram-bot | bot/alerts/alert.py | [
{
"identifier": "get_offers",
"path": "bot/binance_api.py",
"snippet": "async def get_offers(asset: str, fiat: str, trade_type: str, payment_method: str,\n rows: int = 5, page: int = 1, trans_amount: str = None) -> List[dict]:\n \"\"\"\n Fetch the best offers from Binance P2P.\... | from datetime import datetime, timedelta
from bot.binance_api import get_offers, get_link
from bot.utils import send_telegram_message | 1,063 |
class Alert:
def __init__(self, alert_id, user_id, asset, fiat, trade_type, threshold_price, payment_method):
self.alert_id = alert_id
self.user_id = user_id
self.asset = asset
self.fiat = fiat
self.trade_type = trade_type
self.threshold_price = threshold_price
self.payment_method = payment_method
self.active = True
self.last_triggered = None # Track when the alert was last triggered
self.trigger_interval = 15 # in minutes
|
class Alert:
def __init__(self, alert_id, user_id, asset, fiat, trade_type, threshold_price, payment_method):
self.alert_id = alert_id
self.user_id = user_id
self.asset = asset
self.fiat = fiat
self.trade_type = trade_type
self.threshold_price = threshold_price
self.payment_method = payment_method
self.active = True
self.last_triggered = None # Track when the alert was last triggered
self.trigger_interval = 15 # in minutes | self.link = get_link(self.fiat, self.asset, self.payment_method, self.trade_type) | 1 | 2023-11-12 10:20:26+00:00 | 2k |
timlrx/simple-ai-agents | simple_ai_agents/chat_session.py | [
{
"identifier": "ChatMessage",
"path": "simple_ai_agents/models.py",
"snippet": "class ChatMessage(BaseModel):\n role: str\n content: str\n name: Optional[str] = None\n function_call: Optional[str] = None\n received_at: datetime.datetime = Field(default_factory=now_tz)\n finish_reason:... | from json import JSONDecodeError
from typing import Any, AsyncGenerator, Generator, Optional, Type, TypeVar
from instructor.function_calls import Mode
from instructor.patch import handle_response_model, process_response
from litellm import ModelResponse, acompletion, completion
from pydantic import BaseModel, ValidationError
from simple_ai_agents.models import ChatMessage, ChatSession, LLMOptions
import litellm | 862 |
litellm.telemetry = False
litellm.add_function_to_prompt = True # add function to prompt for non openai models
litellm.drop_params = True # drop params if unsupported by provider
litellm.suppress_debug_info = True
T = TypeVar("T", bound=BaseModel)
|
litellm.telemetry = False
litellm.add_function_to_prompt = True # add function to prompt for non openai models
litellm.drop_params = True # drop params if unsupported by provider
litellm.suppress_debug_info = True
T = TypeVar("T", bound=BaseModel)
| class ChatLLMSession(ChatSession): | 1 | 2023-11-10 06:01:25+00:00 | 2k |
DIAGNijmegen/HoVer-UNet | models/HoVerNet/post_proc.py | [
{
"identifier": "remove_small_objects",
"path": "models/HoVerNet/utils.py",
"snippet": "def remove_small_objects(pred, min_size=64, connectivity=1):\n \"\"\"Remove connected components smaller than the specified size.\n\n This function is taken from skimage.morphology.remove_small_objects, but the... | import warnings
import cv2
import numpy as np
from scipy.ndimage import measurements
from scipy.ndimage.morphology import (
binary_fill_holes,
)
from skimage.segmentation import watershed
from models.HoVerNet.utils import remove_small_objects, get_bounding_box | 1,523 |
def noop(*args, **kargs):
pass
warnings.warn = noop
####
def __proc_np_hv(pred):
"""Process Nuclei Prediction with XY Coordinate Map.
Args:
pred: prediction output, assuming
channel 0 contain probability map of nuclei
channel 1 containing the regressed X-map
channel 2 containing the regressed Y-map
"""
pred = np.array(pred, dtype=np.float32)
blb_raw = pred[..., 0]
h_dir_raw = pred[..., 1]
v_dir_raw = pred[..., 2]
# processing
blb = np.array(blb_raw >= 0.5, dtype=np.int32)
blb = measurements.label(blb)[0]
blb = remove_small_objects(blb, min_size=10)
blb[blb > 0] = 1 # background is 0 already
h_dir = cv2.normalize(
h_dir_raw, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F
)
v_dir = cv2.normalize(
v_dir_raw, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F
)
sobelh = cv2.Sobel(h_dir, cv2.CV_64F, 1, 0, ksize=21)
sobelv = cv2.Sobel(v_dir, cv2.CV_64F, 0, 1, ksize=21)
sobelh = 1 - (
cv2.normalize(
sobelh, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F
)
)
sobelv = 1 - (
cv2.normalize(
sobelv, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F
)
)
overall = np.maximum(sobelh, sobelv)
overall = overall - (1 - blb)
overall[overall < 0] = 0
dist = (1.0 - overall) * blb
## nuclei values form mountains so inverse to get basins
dist = -cv2.GaussianBlur(dist, (3, 3), 0)
overall = np.array(overall >= 0.4, dtype=np.int32)
marker = blb - overall
marker[marker < 0] = 0
marker = binary_fill_holes(marker).astype("uint8")
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
marker = cv2.morphologyEx(marker, cv2.MORPH_OPEN, kernel)
marker = measurements.label(marker)[0]
marker = remove_small_objects(marker, min_size=10)
proced_pred = watershed(dist, markers=marker, mask=blb)
return proced_pred
####
def process(pred_map, nr_types=None, return_centroids=False):
"""Post processing script for image tiles.
Args:
pred_map: commbined output of tp, np and hv branches, in the same order
nr_types: number of types considered at output of nc branch
overlaid_img: img to overlay the predicted instances upon, `None` means no
type_colour (dict) : `None` to use random, else overlay instances of a type to colour in the dict
output_dtype: data type of output
Returns:
pred_inst: pixel-wise nuclear instance segmentation prediction
pred_type_out: pixel-wise nuclear type prediction
"""
if nr_types is not None:
pred_type = pred_map[..., :1]
pred_inst = pred_map[..., 1:]
pred_type = pred_type.astype(np.int32)
else:
pred_inst = pred_map
pred_inst = np.squeeze(pred_inst)
pred_inst = __proc_np_hv(pred_inst)
inst_info_dict = None
if return_centroids or nr_types is not None:
inst_id_list = np.unique(pred_inst)[1:] # exlcude background
inst_info_dict = {}
for inst_id in inst_id_list:
inst_map = pred_inst == inst_id
# TODO: chane format of bbox output
|
def noop(*args, **kargs):
pass
warnings.warn = noop
####
def __proc_np_hv(pred):
"""Process Nuclei Prediction with XY Coordinate Map.
Args:
pred: prediction output, assuming
channel 0 contain probability map of nuclei
channel 1 containing the regressed X-map
channel 2 containing the regressed Y-map
"""
pred = np.array(pred, dtype=np.float32)
blb_raw = pred[..., 0]
h_dir_raw = pred[..., 1]
v_dir_raw = pred[..., 2]
# processing
blb = np.array(blb_raw >= 0.5, dtype=np.int32)
blb = measurements.label(blb)[0]
blb = remove_small_objects(blb, min_size=10)
blb[blb > 0] = 1 # background is 0 already
h_dir = cv2.normalize(
h_dir_raw, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F
)
v_dir = cv2.normalize(
v_dir_raw, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F
)
sobelh = cv2.Sobel(h_dir, cv2.CV_64F, 1, 0, ksize=21)
sobelv = cv2.Sobel(v_dir, cv2.CV_64F, 0, 1, ksize=21)
sobelh = 1 - (
cv2.normalize(
sobelh, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F
)
)
sobelv = 1 - (
cv2.normalize(
sobelv, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F
)
)
overall = np.maximum(sobelh, sobelv)
overall = overall - (1 - blb)
overall[overall < 0] = 0
dist = (1.0 - overall) * blb
## nuclei values form mountains so inverse to get basins
dist = -cv2.GaussianBlur(dist, (3, 3), 0)
overall = np.array(overall >= 0.4, dtype=np.int32)
marker = blb - overall
marker[marker < 0] = 0
marker = binary_fill_holes(marker).astype("uint8")
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
marker = cv2.morphologyEx(marker, cv2.MORPH_OPEN, kernel)
marker = measurements.label(marker)[0]
marker = remove_small_objects(marker, min_size=10)
proced_pred = watershed(dist, markers=marker, mask=blb)
return proced_pred
####
def process(pred_map, nr_types=None, return_centroids=False):
"""Post processing script for image tiles.
Args:
pred_map: commbined output of tp, np and hv branches, in the same order
nr_types: number of types considered at output of nc branch
overlaid_img: img to overlay the predicted instances upon, `None` means no
type_colour (dict) : `None` to use random, else overlay instances of a type to colour in the dict
output_dtype: data type of output
Returns:
pred_inst: pixel-wise nuclear instance segmentation prediction
pred_type_out: pixel-wise nuclear type prediction
"""
if nr_types is not None:
pred_type = pred_map[..., :1]
pred_inst = pred_map[..., 1:]
pred_type = pred_type.astype(np.int32)
else:
pred_inst = pred_map
pred_inst = np.squeeze(pred_inst)
pred_inst = __proc_np_hv(pred_inst)
inst_info_dict = None
if return_centroids or nr_types is not None:
inst_id_list = np.unique(pred_inst)[1:] # exlcude background
inst_info_dict = {}
for inst_id in inst_id_list:
inst_map = pred_inst == inst_id
# TODO: chane format of bbox output | rmin, rmax, cmin, cmax = get_bounding_box(inst_map) | 1 | 2023-11-10 09:37:29+00:00 | 2k |
fofr/cog-sdxl-lcm-multi-controlnet-lora | controlnet.py | [
{
"identifier": "ControlNetPreprocessor",
"path": "controlnet_preprocess.py",
"snippet": "class ControlNetPreprocessor:\n ANNOTATOR_NAMES = [\n \"none\",\n \"edge_canny\",\n \"depth_leres\",\n \"depth_midas\",\n \"soft_edge_pidi\",\n \"soft_edge_hed\",\n ... | import torch
from diffusers import ControlNetModel
from controlnet_preprocess import ControlNetPreprocessor
from weights_downloader import WeightsDownloader | 917 |
CONTROLNET_MODEL_CACHE = "./controlnet-cache"
CONTROLNET_URL = "https://weights.replicate.delivery/default/controlnet/sdxl-cn-canny-depth-softe-pose-qr.tar"
class ControlNet:
CONTROLNET_MODELS = [
"none",
"edge_canny",
"illusion",
"depth_leres",
"depth_midas",
"soft_edge_pidi",
"soft_edge_hed",
"lineart",
"lineart_anime",
"openpose",
# Preprocessors without an XL model yet
# "straight_edge_mlsd",
# "face_detector",
# "content_shuffle",
# "normal_bae",
# "segementation_sam",
]
def __init__(self, predictor):
|
CONTROLNET_MODEL_CACHE = "./controlnet-cache"
CONTROLNET_URL = "https://weights.replicate.delivery/default/controlnet/sdxl-cn-canny-depth-softe-pose-qr.tar"
class ControlNet:
CONTROLNET_MODELS = [
"none",
"edge_canny",
"illusion",
"depth_leres",
"depth_midas",
"soft_edge_pidi",
"soft_edge_hed",
"lineart",
"lineart_anime",
"openpose",
# Preprocessors without an XL model yet
# "straight_edge_mlsd",
# "face_detector",
# "content_shuffle",
# "normal_bae",
# "segementation_sam",
]
def __init__(self, predictor): | WeightsDownloader.download_if_not_exists(CONTROLNET_URL, CONTROLNET_MODEL_CACHE) | 1 | 2023-11-16 11:11:27+00:00 | 2k |
joyn-gg/discord.http | discord_http/view.py | [
{
"identifier": "PartialEmoji",
"path": "discord_http/emoji.py",
"snippet": "class PartialEmoji:\n def __init__(self, emoji: str):\n self._original_name: str = emoji\n\n self.id: Optional[int] = None\n self.animated: bool = False\n self.discord_emoji: bool = False\n\n ... | import asyncio
import inspect
import logging
import secrets
import time
from typing import Union, Optional, TYPE_CHECKING, Callable
from .emoji import PartialEmoji
from .enums import ButtonStyles, ComponentType, TextStyles, ChannelType
from . import Snowflake
from .channel import BaseChannel
from .context import Context
from .message import Message
from .response import BaseResponse | 1,198 |
if TYPE_CHECKING:
_log = logging.getLogger(__name__)
__all__ = (
"Button",
"ChannelSelect",
"Item",
"Link",
"MentionableSelect",
"Modal",
"RoleSelect",
"Select",
"UserSelect",
"View",
)
def _garbage_id() -> str:
""" `str`: Returns a random ID to satisfy Discord API """
return secrets.token_hex(16)
class Item:
def __init__(self, *, type: int, row: Optional[int] = None):
self.row: Optional[int] = row
self.type: int = type
def __repr__(self) -> str:
return f"<Item type={self.type} row={self.row}>"
def to_dict(self) -> dict:
""" `dict`: Returns a dict representation of the item """
raise NotImplementedError("to_dict not implemented")
class Button(Item):
def __init__(
self,
*,
label: Optional[str] = None,
style: Union[ButtonStyles, str, int] = ButtonStyles.primary,
disabled: bool = False,
row: Optional[int] = None,
custom_id: Optional[str] = None,
emoji: Optional[Union[str, dict]] = None,
url: Optional[str] = None
):
|
if TYPE_CHECKING:
_log = logging.getLogger(__name__)
__all__ = (
"Button",
"ChannelSelect",
"Item",
"Link",
"MentionableSelect",
"Modal",
"RoleSelect",
"Select",
"UserSelect",
"View",
)
def _garbage_id() -> str:
""" `str`: Returns a random ID to satisfy Discord API """
return secrets.token_hex(16)
class Item:
def __init__(self, *, type: int, row: Optional[int] = None):
self.row: Optional[int] = row
self.type: int = type
def __repr__(self) -> str:
return f"<Item type={self.type} row={self.row}>"
def to_dict(self) -> dict:
""" `dict`: Returns a dict representation of the item """
raise NotImplementedError("to_dict not implemented")
class Button(Item):
def __init__(
self,
*,
label: Optional[str] = None,
style: Union[ButtonStyles, str, int] = ButtonStyles.primary,
disabled: bool = False,
row: Optional[int] = None,
custom_id: Optional[str] = None,
emoji: Optional[Union[str, dict]] = None,
url: Optional[str] = None
): | super().__init__(type=int(ComponentType.button), row=row) | 2 | 2023-11-14 12:50:42+00:00 | 2k |
catid/aiwebcam2 | app.py | [
{
"identifier": "logger",
"path": "utils.py",
"snippet": "class ColoredFormatter(logging.Formatter):\n def format(self, record):\ndef setup_colored_logging(level=logging.INFO):"
},
{
"identifier": "ASRServiceRunner",
"path": "service_asr.py",
"snippet": "class ASRServiceRunner:\n d... | from utils import logger
from service_asr import ASRServiceRunner
from service_llm import LLMServiceRunner
from service_tts import TTSServiceRunner
from aiortc import RTCIceCandidate, RTCSessionDescription, RTCPeerConnection
from aiortc.mediastreams import AudioStreamTrack, VideoStreamTrack, MediaStreamError, MediaStreamTrack
from queue import Queue
from fractions import Fraction
from PIL import Image
from zoneinfo import ZoneInfo
import socketio
import asyncio
import re
import io
import base64
import numpy as np
import time, datetime
import aiohttp.web
import asyncio
import ssl
import argparse | 1,591 | # Logging
sio = socketio.AsyncServer(cors_allowed_origins='*')
# Background services
asr_runner = ASRServiceRunner()
llm_runner = LLMServiceRunner()
# WebRTC peer listening for a single browser to connect
# We run each WebRTC peer in a separate process to avoid stalls in playback
# WebRTC Connection
class VideoReceiver(VideoStreamTrack):
kind = "video"
def __init__(self, track):
super().__init__() # Initialize the MediaStreamTrack
self.track = track
self.recording = False
self.recorded_frame = None
def startRecording(self):
self.recording = True
self.recorded_frame = None
def endRecording(self):
self.recording = False
image = self.recorded_frame
self.recorded_frame = None
return image
async def recv(self):
frame = await self.track.recv()
# Process the frame (e.g., save to a file, play audio, etc.)
if self.recording:
if not self.recorded_frame:
self.recorded_frame = frame
return frame
class CustomAudioStream(MediaStreamTrack):
kind = "audio"
def __init__(self):
super().__init__() # don't forget this!
self.tts = TTSServiceRunner()
self.stream_time = None
async def close(self):
super().stop()
self.tts.close()
async def recv(self):
packet, duration = self.tts.poll_packet()
#logger.info(f"opus duration={duration} pts={packet.pts}")
if self.stream_time is None:
self.stream_time = time.time()
wait = self.stream_time - time.time()
await asyncio.sleep(wait)
self.stream_time += duration
return packet
class WebRTCConnection:
def __init__(self, sid):
self.sid = sid
self.pc = RTCPeerConnection()
self.video_track = None
self.processing_audio = False
self.recording = False
self.opus_track = CustomAudioStream()
@self.pc.on("connectionstatechange")
async def on_connectionstatechange():
| # Logging
sio = socketio.AsyncServer(cors_allowed_origins='*')
# Background services
asr_runner = ASRServiceRunner()
llm_runner = LLMServiceRunner()
# WebRTC peer listening for a single browser to connect
# We run each WebRTC peer in a separate process to avoid stalls in playback
# WebRTC Connection
class VideoReceiver(VideoStreamTrack):
kind = "video"
def __init__(self, track):
super().__init__() # Initialize the MediaStreamTrack
self.track = track
self.recording = False
self.recorded_frame = None
def startRecording(self):
self.recording = True
self.recorded_frame = None
def endRecording(self):
self.recording = False
image = self.recorded_frame
self.recorded_frame = None
return image
async def recv(self):
frame = await self.track.recv()
# Process the frame (e.g., save to a file, play audio, etc.)
if self.recording:
if not self.recorded_frame:
self.recorded_frame = frame
return frame
class CustomAudioStream(MediaStreamTrack):
kind = "audio"
def __init__(self):
super().__init__() # don't forget this!
self.tts = TTSServiceRunner()
self.stream_time = None
async def close(self):
super().stop()
self.tts.close()
async def recv(self):
packet, duration = self.tts.poll_packet()
#logger.info(f"opus duration={duration} pts={packet.pts}")
if self.stream_time is None:
self.stream_time = time.time()
wait = self.stream_time - time.time()
await asyncio.sleep(wait)
self.stream_time += duration
return packet
class WebRTCConnection:
def __init__(self, sid):
self.sid = sid
self.pc = RTCPeerConnection()
self.video_track = None
self.processing_audio = False
self.recording = False
self.opus_track = CustomAudioStream()
@self.pc.on("connectionstatechange")
async def on_connectionstatechange(): | logger.info(f"self.pc.connectionState = {self.pc.connectionState}") | 0 | 2023-11-16 03:37:47+00:00 | 2k |
chziakas/backbone-learn | experiments/benchmark_decision_tree.py | [
{
"identifier": "BackboneDecisionTree",
"path": "backbone_learn/backbone/backbone_decision_tree.py",
"snippet": "class BackboneDecisionTree(BackboneSupervised):\n \"\"\"\n Specific implementation of the Backbone method for sparse regression.\n\n This class combines Pearson correlation for featu... | import time
from itertools import product
from sklearn.datasets import make_classification
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import KBinsDiscretizer, OneHotEncoder
from utils import save_results
from backbone_learn.backbone.backbone_decision_tree import BackboneDecisionTree
from backbone_learn.heuristic_solvers.cart_decision_tree import CARTDecisionTree | 1,590 |
# Define parameter ranges for Backbone parameters
alpha_range = [0.1, 0.5]
beta_range = [0.5, 0.9]
num_subproblems_range = [5, 10]
num_iterations_range = [1]
# Define parameter ranges for FlowOCT parameters
depth_range = [2]
_lambda_range = [0.5]
# Define dataset parameters
n_informative = 4
n_bins = 5
n_features_range = [20]
n_samples = 500
n_classes = 2
random_state = 17
time_limit = 3600
log_filename = "decision_tree_results.json"
results = []
# Experiment loop
for n_features in n_features_range:
# Generate synthetic classification data
X, y = make_classification(
n_samples=n_samples,
n_informative=n_informative,
n_features=n_features,
n_classes=n_classes,
random_state=random_state,
)
# Convert features to binary
est_X = KBinsDiscretizer(
n_bins=n_bins, encode="ordinal", strategy="quantile", random_state=random_state
)
est_X.fit(X)
X_bin = est_X.transform(X)
enc = OneHotEncoder(handle_unknown="error", drop="if_binary")
X_cat_enc = enc.fit_transform(X_bin).toarray()
# Split data into train and test sets
X_train, X_test, y_train, y_test = train_test_split(
X_cat_enc, y, test_size=0.2, random_state=random_state
)
for depth in depth_range:
# CARTDecisionTree model iteration for heuristic_model
|
# Define parameter ranges for Backbone parameters
alpha_range = [0.1, 0.5]
beta_range = [0.5, 0.9]
num_subproblems_range = [5, 10]
num_iterations_range = [1]
# Define parameter ranges for FlowOCT parameters
depth_range = [2]
_lambda_range = [0.5]
# Define dataset parameters
n_informative = 4
n_bins = 5
n_features_range = [20]
n_samples = 500
n_classes = 2
random_state = 17
time_limit = 3600
log_filename = "decision_tree_results.json"
results = []
# Experiment loop
for n_features in n_features_range:
# Generate synthetic classification data
X, y = make_classification(
n_samples=n_samples,
n_informative=n_informative,
n_features=n_features,
n_classes=n_classes,
random_state=random_state,
)
# Convert features to binary
est_X = KBinsDiscretizer(
n_bins=n_bins, encode="ordinal", strategy="quantile", random_state=random_state
)
est_X.fit(X)
X_bin = est_X.transform(X)
enc = OneHotEncoder(handle_unknown="error", drop="if_binary")
X_cat_enc = enc.fit_transform(X_bin).toarray()
# Split data into train and test sets
X_train, X_test, y_train, y_test = train_test_split(
X_cat_enc, y, test_size=0.2, random_state=random_state
)
for depth in depth_range:
# CARTDecisionTree model iteration for heuristic_model | heuristic_model = CARTDecisionTree(max_depth=depth) | 1 | 2023-11-18 14:28:12+00:00 | 2k |
openclimatefix/Open-Source-Quartz-Solar-Forecast | tests/eval/test_pv.py | [
{
"identifier": "get_pv_truth",
"path": "quartz_solar_forecast/eval/pv.py",
"snippet": "def get_pv_truth(testset: pd.DataFrame):\n\n print('Loading PV data')\n\n # download from hugginface or load from cache\n cache_dir = \"data/pv\"\n metadata_file = f\"{cache_dir}/pv.netcdf\"\n if not o... | from quartz_solar_forecast.eval.pv import get_pv_truth, get_pv_metadata
import pandas as pd | 840 |
def test_get_pv_metadata():
test_set_df = pd.DataFrame(
[
{
"timestamp": pd.Timestamp("2021-01-26 01:15:00"),
"pv_id": 8215,
}
]
)
|
def test_get_pv_metadata():
test_set_df = pd.DataFrame(
[
{
"timestamp": pd.Timestamp("2021-01-26 01:15:00"),
"pv_id": 8215,
}
]
)
| metadata_df = get_pv_metadata(test_set_df) | 1 | 2023-11-16 07:37:42+00:00 | 2k |
newcastleuniversity/DISPEL | dispel/providers/generic/tasks/sbt_utt/sbt_func.py | [
{
"identifier": "MIN_MOTION_DUR",
"path": "dispel/providers/generic/tasks/sbt_utt/const.py",
"snippet": "MIN_MOTION_DUR = 1"
},
{
"identifier": "signal_duration",
"path": "dispel/signal/core.py",
"snippet": "def signal_duration(data: Union[pd.Series, pd.DataFrame]) -> float:\n \"\"\"G... | import numpy as np
import pandas as pd
from dispel.providers.generic.tasks.sbt_utt.const import MIN_MOTION_DUR
from dispel.signal.core import signal_duration
from dispel.signal.geometric import extract_ellipse_axes
from dispel.signal.vectorial import mean_norm_planar, resultant_norm_planar, rms_planar | 1,471 | """Functionality implemented in SBT.steps module."""
def label_bouts(data: pd.Series) -> pd.Series:
"""Label each valid and invalid chunk as a bout.
Parameters
----------
data
A Series that contains one column including the flag continuous
signal
Returns
-------
Series
A labelled pd.Series where each valid/invalid bout is assigned an
increasing integer number
"""
# We increase a counter number everytime the flag changes (solution
# inspired in StakOverflow community
return data.astype(bool).diff().fillna(method="bfill").cumsum()
def reject_short_bouts(bout_mask: pd.Series, flag: pd.Series) -> pd.Series:
"""Reject bouts whose duration is less than MIN_MOTION_DUR seconds.
Parameters
----------
bout_mask
A Series containing a flag_signal and a bout_number.
flag
A Series containing a flag_signal and a bout_number.
Returns
-------
Series
A Series with a flag_signal where the valence has been inverted
in case its duration is below MIN_MOTION_DUR seconds.
"""
flag = flag.astype(bool)
for _, bout in bout_mask.groupby(bout_mask):
| """Functionality implemented in SBT.steps module."""
def label_bouts(data: pd.Series) -> pd.Series:
"""Label each valid and invalid chunk as a bout.
Parameters
----------
data
A Series that contains one column including the flag continuous
signal
Returns
-------
Series
A labelled pd.Series where each valid/invalid bout is assigned an
increasing integer number
"""
# We increase a counter number everytime the flag changes (solution
# inspired in StakOverflow community
return data.astype(bool).diff().fillna(method="bfill").cumsum()
def reject_short_bouts(bout_mask: pd.Series, flag: pd.Series) -> pd.Series:
"""Reject bouts whose duration is less than MIN_MOTION_DUR seconds.
Parameters
----------
bout_mask
A Series containing a flag_signal and a bout_number.
flag
A Series containing a flag_signal and a bout_number.
Returns
-------
Series
A Series with a flag_signal where the valence has been inverted
in case its duration is below MIN_MOTION_DUR seconds.
"""
flag = flag.astype(bool)
for _, bout in bout_mask.groupby(bout_mask): | if signal_duration(bout) < MIN_MOTION_DUR: | 0 | 2023-11-14 10:06:46+00:00 | 2k |
runDMCA/home-assistant-mazda | custom_components/mazda/pymazda/sensordata/system_info.py | [
{
"identifier": "AndroidBuilds",
"path": "custom_components/mazda/pymazda/sensordata/android_builds.py",
"snippet": "class AndroidBuilds: # noqa: D101\n def __init__(self): # noqa: D107\n self.builds = None\n\n def get_builds(self): # noqa: D102\n if self.builds is None:\n ... | import random # noqa: D100
import secrets
from .android_builds import AndroidBuilds
from .sensor_data_util import percent_encode, sum_char_codes | 1,250 |
SCREEN_SIZES = [[1280, 720], [1920, 1080], [2560, 1440]]
ANDROID_VERSION_TO_SDK_VERSION = {
"11": 30,
"10": 29,
"9": 28,
"8.1.0": 27,
"8.0.0": 26,
"7.1": 25,
"7.0": 24,
}
class SystemInfo: # noqa: D101
def __init__(self): # noqa: D107
self.android_builds = AndroidBuilds()
def randomize(self): # noqa: D102
device_model, device = random.choice(
list(self.android_builds.get_builds().items())
)
codename = device["codename"]
build = random.choice(device["builds"])
build_version_incremental = random.randrange(1000000, 9999999)
self.screen_height, self.screen_width = random.choice(SCREEN_SIZES)
self.battery_charging = random.randrange(0, 10) <= 1
self.battery_level = random.randrange(10, 90)
self.orientation = 1
self.language = "en"
self.android_version = build["version"]
self.rotation_lock = "1" if random.randrange(0, 10) > 1 else "0"
self.build_model = device_model
self.build_bootloader = str(random.randrange(1000000, 9999999))
self.build_hardware = codename
self.package_name = "com.interrait.mymazda"
self.android_id = secrets.token_bytes(8).hex()
self.keyboard = 0
self.adb_enabled = False
self.build_version_codename = "REL"
self.build_version_incremental = build_version_incremental
self.build_version_sdk = ANDROID_VERSION_TO_SDK_VERSION.get(build["version"])
self.build_manufacturer = "Google"
self.build_product = codename
self.build_tags = "release-keys"
self.build_type = "user"
self.build_user = "android-build"
self.build_display = build["buildId"]
self.build_board = codename
self.build_brand = "google"
self.build_device = codename
self.build_fingerprint = f"google/{codename}/{codename}:{build['version']}/{build['buildId']}/{build_version_incremental}:user/release-keys"
self.build_host = f"abfarm-{random.randrange(10000, 99999)}"
self.build_id = build["buildId"]
def to_string(self): # noqa: D102
return ",".join(
[
"-1",
"uaend",
"-1",
str(self.screen_height),
str(self.screen_width),
("1" if self.battery_charging else "0"),
str(self.battery_level),
str(self.orientation),
percent_encode(self.language),
percent_encode(self.android_version),
self.rotation_lock,
percent_encode(self.build_model),
percent_encode(self.build_bootloader),
percent_encode(self.build_hardware),
"-1",
self.package_name,
"-1",
"-1",
self.android_id,
"-1",
str(self.keyboard),
"1" if self.adb_enabled else "0",
percent_encode(self.build_version_codename),
percent_encode(str(self.build_version_incremental)),
str(self.build_version_sdk),
percent_encode(self.build_manufacturer),
percent_encode(self.build_product),
percent_encode(self.build_tags),
percent_encode(self.build_type),
percent_encode(self.build_user),
percent_encode(self.build_display),
percent_encode(self.build_board),
percent_encode(self.build_brand),
percent_encode(self.build_device),
percent_encode(self.build_fingerprint),
percent_encode(self.build_host),
percent_encode(self.build_id),
]
)
def get_char_code_sum(self): # noqa: D102
|
SCREEN_SIZES = [[1280, 720], [1920, 1080], [2560, 1440]]
ANDROID_VERSION_TO_SDK_VERSION = {
"11": 30,
"10": 29,
"9": 28,
"8.1.0": 27,
"8.0.0": 26,
"7.1": 25,
"7.0": 24,
}
class SystemInfo: # noqa: D101
def __init__(self): # noqa: D107
self.android_builds = AndroidBuilds()
def randomize(self): # noqa: D102
device_model, device = random.choice(
list(self.android_builds.get_builds().items())
)
codename = device["codename"]
build = random.choice(device["builds"])
build_version_incremental = random.randrange(1000000, 9999999)
self.screen_height, self.screen_width = random.choice(SCREEN_SIZES)
self.battery_charging = random.randrange(0, 10) <= 1
self.battery_level = random.randrange(10, 90)
self.orientation = 1
self.language = "en"
self.android_version = build["version"]
self.rotation_lock = "1" if random.randrange(0, 10) > 1 else "0"
self.build_model = device_model
self.build_bootloader = str(random.randrange(1000000, 9999999))
self.build_hardware = codename
self.package_name = "com.interrait.mymazda"
self.android_id = secrets.token_bytes(8).hex()
self.keyboard = 0
self.adb_enabled = False
self.build_version_codename = "REL"
self.build_version_incremental = build_version_incremental
self.build_version_sdk = ANDROID_VERSION_TO_SDK_VERSION.get(build["version"])
self.build_manufacturer = "Google"
self.build_product = codename
self.build_tags = "release-keys"
self.build_type = "user"
self.build_user = "android-build"
self.build_display = build["buildId"]
self.build_board = codename
self.build_brand = "google"
self.build_device = codename
self.build_fingerprint = f"google/{codename}/{codename}:{build['version']}/{build['buildId']}/{build_version_incremental}:user/release-keys"
self.build_host = f"abfarm-{random.randrange(10000, 99999)}"
self.build_id = build["buildId"]
def to_string(self): # noqa: D102
return ",".join(
[
"-1",
"uaend",
"-1",
str(self.screen_height),
str(self.screen_width),
("1" if self.battery_charging else "0"),
str(self.battery_level),
str(self.orientation),
percent_encode(self.language),
percent_encode(self.android_version),
self.rotation_lock,
percent_encode(self.build_model),
percent_encode(self.build_bootloader),
percent_encode(self.build_hardware),
"-1",
self.package_name,
"-1",
"-1",
self.android_id,
"-1",
str(self.keyboard),
"1" if self.adb_enabled else "0",
percent_encode(self.build_version_codename),
percent_encode(str(self.build_version_incremental)),
str(self.build_version_sdk),
percent_encode(self.build_manufacturer),
percent_encode(self.build_product),
percent_encode(self.build_tags),
percent_encode(self.build_type),
percent_encode(self.build_user),
percent_encode(self.build_display),
percent_encode(self.build_board),
percent_encode(self.build_brand),
percent_encode(self.build_device),
percent_encode(self.build_fingerprint),
percent_encode(self.build_host),
percent_encode(self.build_id),
]
)
def get_char_code_sum(self): # noqa: D102 | return sum_char_codes(self.to_string()) | 2 | 2023-11-14 01:42:43+00:00 | 2k |
uysalserkan/url-shorter | app.py | [
{
"identifier": "URLS",
"path": "models/urls.py",
"snippet": "class URLS(SQLModel, table=True):\n id: Optional[int] = Field(default=None, primary_key=True)\n long_url: str = Field(nullable=False)\n generated_url: str = Field(nullable=True)\n created_date: int = datetime.utcnow().timestamp()\... | import multiprocessing
import time
from datetime import datetime, timedelta
from fastapi import FastAPI, Response, UploadFile, Request
from fastapi.responses import RedirectResponse, JSONResponse
from sqlmodel import select
from prometheus_fastapi_instrumentator import Instrumentator
from models.urls import URLS
from controller.url_c import URLController
from config import settings, secrets
from engines import DatabaseEngine, MinIOEngine
from validators import url_validation | 1,116 | """URL Shorter API."""
app = FastAPI(
title="URL Shorter Service",
description="Short your long url links.",
)
Instrumentator().instrument(app).expose(app)
| """URL Shorter API."""
app = FastAPI(
title="URL Shorter Service",
description="Short your long url links.",
)
Instrumentator().instrument(app).expose(app)
| DB_engine = DatabaseEngine() | 3 | 2023-11-16 10:43:45+00:00 | 2k |
logicalroot/gpt-4v-demos | pages/3_📋_Quality_Control.py | [
{
"identifier": "show_code",
"path": "utils.py",
"snippet": "def show_code(code):\n \"\"\"Showing the code of the demo.\"\"\"\n show_code = st.sidebar.checkbox(\"Show code\", False)\n if show_code:\n st.markdown(\"## Code\")\n for function in code:\n # Showing the code ... | import streamlit as st
import base64
import requests
import json
import components
from utils import show_code
from parsers import extract_json | 762 |
def submit(image, api_key, issue_attributes):
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {api_key}"}
base64_image = base64.b64encode(image).decode("utf-8")
payload = {
"model": "gpt-4-vision-preview",
"messages": [
{
"role": "system",
"content": "You are an expert quality control inspector for leading manufacturers.",
},
{
"role": "user",
"content": [
{
"type": "text",
"text": (
"Inspect this image and write a report in the following format:\n\n"
"```json\n"
"{\n"
' "issues": [\n'
" {\n"
f"{issue_attributes}\n"
" }\n"
" ]\n"
"}\n"
"```\n\n"
"If you see any signs of quality deterioration of any kind, such as corrosion, "
"physical damage, decay, or contamination, add them as separate issues in the "
"`issues` array. If there are no issues, the `issues` array should be empty. "
"Your response should contain only valid JSON."
),
},
{
"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{base64_image}"},
},
],
},
],
"max_tokens": 1024,
"temperature": 0.1,
# Response format not yet supported by GPT-4V
# "response_format": {"type": "json_object"},
}
try:
response = requests.post(
"https://api.openai.com/v1/chat/completions", headers=headers, json=payload
)
response.raise_for_status()
|
def submit(image, api_key, issue_attributes):
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {api_key}"}
base64_image = base64.b64encode(image).decode("utf-8")
payload = {
"model": "gpt-4-vision-preview",
"messages": [
{
"role": "system",
"content": "You are an expert quality control inspector for leading manufacturers.",
},
{
"role": "user",
"content": [
{
"type": "text",
"text": (
"Inspect this image and write a report in the following format:\n\n"
"```json\n"
"{\n"
' "issues": [\n'
" {\n"
f"{issue_attributes}\n"
" }\n"
" ]\n"
"}\n"
"```\n\n"
"If you see any signs of quality deterioration of any kind, such as corrosion, "
"physical damage, decay, or contamination, add them as separate issues in the "
"`issues` array. If there are no issues, the `issues` array should be empty. "
"Your response should contain only valid JSON."
),
},
{
"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{base64_image}"},
},
],
},
],
"max_tokens": 1024,
"temperature": 0.1,
# Response format not yet supported by GPT-4V
# "response_format": {"type": "json_object"},
}
try:
response = requests.post(
"https://api.openai.com/v1/chat/completions", headers=headers, json=payload
)
response.raise_for_status()
| text = extract_json(response.json()["choices"][0]["message"]["content"]) | 1 | 2023-11-14 21:29:43+00:00 | 2k |
intel/llm-on-ray | inference/api_server_openai.py | [
{
"identifier": "RouterQueryClient",
"path": "inference/api_openai_backend/query_client.py",
"snippet": "class RouterQueryClient():\n def __init__(self, serve_deployments):\n self.serve_deployments = serve_deployments\n\n async def query(self, model: str, prompt: Prompt, request_id: str):\n... | import os
from ray import serve
from inference.api_openai_backend.query_client import RouterQueryClient
from inference.api_openai_backend.router_app import Router, router_app | 1,317 | #
# Copyright 2023 The LLM-on-Ray Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ===========================================================================
#
# This file is adapted from
# https://github.com/ray-project/ray-llm/blob/b3560aa55dadf6978f0de0a6f8f91002a5d2bed1/aviary/backend/server/run.py
# Copyright 2023 Anyscale
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
def router_application(deployments):
"""Create a Router Deployment.
Router Deployment will point to a Serve Deployment for each specified base model,
and have a client to query each one.
"""
merged_client = RouterQueryClient(deployments)
RouterDeployment = serve.deployment(
route_prefix="/",
autoscaling_config={
"min_replicas": int(os.environ.get("ROUTER_MIN_REPLICAS", 2)),
"initial_replicas": int(os.environ.get("ROUTER_INITIAL_REPLICAS", 2)),
"max_replicas": int(os.environ.get("ROUTER_MAX_REPLICAS", 16)),
"target_num_ongoing_requests_per_replica": int(
os.environ.get("ROUTER_TARGET_NUM_ONGOING_REQUESTS_PER_REPLICA", 200)
),
},
max_concurrent_queries=1000, # Maximum backlog for a single replica
| #
# Copyright 2023 The LLM-on-Ray Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ===========================================================================
#
# This file is adapted from
# https://github.com/ray-project/ray-llm/blob/b3560aa55dadf6978f0de0a6f8f91002a5d2bed1/aviary/backend/server/run.py
# Copyright 2023 Anyscale
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
def router_application(deployments):
"""Create a Router Deployment.
Router Deployment will point to a Serve Deployment for each specified base model,
and have a client to query each one.
"""
merged_client = RouterQueryClient(deployments)
RouterDeployment = serve.deployment(
route_prefix="/",
autoscaling_config={
"min_replicas": int(os.environ.get("ROUTER_MIN_REPLICAS", 2)),
"initial_replicas": int(os.environ.get("ROUTER_INITIAL_REPLICAS", 2)),
"max_replicas": int(os.environ.get("ROUTER_MAX_REPLICAS", 16)),
"target_num_ongoing_requests_per_replica": int(
os.environ.get("ROUTER_TARGET_NUM_ONGOING_REQUESTS_PER_REPLICA", 200)
),
},
max_concurrent_queries=1000, # Maximum backlog for a single replica | )(serve.ingress(router_app)(Router)) | 1 | 2023-11-13 05:08:21+00:00 | 2k |
carlhampuswall/smartknob_ha | custom_components/smartknob/store.py | [
{
"identifier": "DATA_REGISTRY",
"path": "custom_components/smartknob/const.py",
"snippet": "DATA_REGISTRY = f\"{DOMAIN}_storage\""
},
{
"identifier": "SAVE_DELAY",
"path": "custom_components/smartknob/const.py",
"snippet": "SAVE_DELAY = 10"
},
{
"identifier": "STORAGE_KEY",
... | from collections import OrderedDict
from collections.abc import MutableMapping
from typing import Dict, cast
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.storage import Store
from homeassistant.loader import bind_hass
from .const import DATA_REGISTRY, SAVE_DELAY, STORAGE_KEY
from .logger import _LOGGER
import attr | 758 |
@attr.s(slots=True, frozen=True)
class AppEntry:
"""App storage entry."""
app_id = attr.ib(type=str, default=None)
app_slug_id = attr.ib(type=str, default=None)
entity_id = attr.ib(type=str, default=None)
friendly_name = attr.ib(type=str, default=None)
@attr.s(slots=True, frozen=True)
class SmartknobConfig:
"""Smartknob device configuration, storage entry."""
mac_address = attr.ib(type=str, default=None)
apps = attr.ib(type=list[AppEntry], default=None)
class SmartknobStorage:
"""Class to hold Smartknob storage."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize the Smartknob storage."""
self.hass = hass
self.config: MutableMapping[
str, str
] = {} #! ADD SMARTKNOB DEVICE SPECIFIC CONFIG HERE
self.knobs: MutableMapping[str, SmartknobConfig] = {}
self._store = Store(hass, 1, STORAGE_KEY)
async def async_load(self) -> None:
"""Load the registry of Smartknob."""
data = await self._store.async_load()
knobs: "OrderedDict[str, AppEntry]" = OrderedDict()
if data is None:
return
if "knobs" in data:
for knob in data["knobs"]:
apps = [
AppEntry(
app_id=app["app_id"],
app_slug_id=app["app_slug_id"],
entity_id=app["entity_id"],
friendly_name=app["friendly_name"],
)
for (app) in knob["apps"]
]
knobs[knob["mac_address"]] = SmartknobConfig(
mac_address=knob["mac_address"], apps=apps
)
self.knobs = knobs
# TODO ADD CHECK IF NO APPS
# if not apps:
# await self.async_factory_default()
@callback
def async_schedule_save(self) -> None:
"""Schedule saving the registry of alarmo."""
self._store.async_delay_save(self._data_to_save, SAVE_DELAY)
async def async_save(self) -> None:
"""Save the registry of Smartknob."""
await self._store.async_save(self._data_to_save())
@callback
def _data_to_save(self) -> dict:
store_data = {"knobs": [attr.asdict(entry) for entry in self.knobs.values()]}
# EXAMPLE OF ADDING MORE DATA TO STORE
# store_data["apps"] = [attr.asdict(entry) for entry in self.areas.values()]
return store_data
async def async_delete(self):
"""Delete all registry data."""
|
@attr.s(slots=True, frozen=True)
class AppEntry:
"""App storage entry."""
app_id = attr.ib(type=str, default=None)
app_slug_id = attr.ib(type=str, default=None)
entity_id = attr.ib(type=str, default=None)
friendly_name = attr.ib(type=str, default=None)
@attr.s(slots=True, frozen=True)
class SmartknobConfig:
"""Smartknob device configuration, storage entry."""
mac_address = attr.ib(type=str, default=None)
apps = attr.ib(type=list[AppEntry], default=None)
class SmartknobStorage:
"""Class to hold Smartknob storage."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize the Smartknob storage."""
self.hass = hass
self.config: MutableMapping[
str, str
] = {} #! ADD SMARTKNOB DEVICE SPECIFIC CONFIG HERE
self.knobs: MutableMapping[str, SmartknobConfig] = {}
self._store = Store(hass, 1, STORAGE_KEY)
async def async_load(self) -> None:
"""Load the registry of Smartknob."""
data = await self._store.async_load()
knobs: "OrderedDict[str, AppEntry]" = OrderedDict()
if data is None:
return
if "knobs" in data:
for knob in data["knobs"]:
apps = [
AppEntry(
app_id=app["app_id"],
app_slug_id=app["app_slug_id"],
entity_id=app["entity_id"],
friendly_name=app["friendly_name"],
)
for (app) in knob["apps"]
]
knobs[knob["mac_address"]] = SmartknobConfig(
mac_address=knob["mac_address"], apps=apps
)
self.knobs = knobs
# TODO ADD CHECK IF NO APPS
# if not apps:
# await self.async_factory_default()
@callback
def async_schedule_save(self) -> None:
"""Schedule saving the registry of alarmo."""
self._store.async_delay_save(self._data_to_save, SAVE_DELAY)
async def async_save(self) -> None:
"""Save the registry of Smartknob."""
await self._store.async_save(self._data_to_save())
@callback
def _data_to_save(self) -> dict:
store_data = {"knobs": [attr.asdict(entry) for entry in self.knobs.values()]}
# EXAMPLE OF ADDING MORE DATA TO STORE
# store_data["apps"] = [attr.asdict(entry) for entry in self.areas.values()]
return store_data
async def async_delete(self):
"""Delete all registry data.""" | _LOGGER.warning("Removing Smartknob configuration data!") | 3 | 2023-11-13 16:37:20+00:00 | 2k |
chuzhumin98/LLM_Eval | PRE/eval.py | [
{
"identifier": "DataLoader",
"path": "PRE/data.py",
"snippet": "class DataLoader:\n '''\n The loader to load for evaluated task, with given prompt template to generate a series of prompts feeding for each LLM\n '''\n def __init__(self, args):\n self.path_data = args['path_data'] # th... | import os
import yaml
import warnings
import json
import copy
import sys
import numpy as np
from PRE.data import DataLoader
from PRE.api import Auto_API
from PRE.utils import parse_response | 1,253 | '''
The implement of the peer review and result aggregation module
'''
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
class PEER_REVIEW:
'''
Conduct peer review, process for one prompt (pairwise or pointwise)
'''
def __init__(self, args) -> None:
self.parser_type = args['parser_type'] # int, float, str
self.task_name = args['task_name']
self.save_dir = args['save_dir']
if self.parser_type == 'str':
self.nominal_list = [nn.strip() for nn in args['nominal_list'].split(',')]
self.nominal_ticks = [int(nn.strip()) for nn in args['nominal_ticks'].split(',')]
else:
self.nominal_list, self.nominal_ticks = None, None
def peer_review_single_round(self, reviewers, prompts):
'''
used in gaming sampling strategy
reviewers: LLM config list
prompts: an array, each item is a dict with key "prompt"
return a dict to denote the results of each evaluate task under all the reviews, key: reviewer model name, value: the original response of this reviewer
'''
| '''
The implement of the peer review and result aggregation module
'''
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
class PEER_REVIEW:
'''
Conduct peer review, process for one prompt (pairwise or pointwise)
'''
def __init__(self, args) -> None:
self.parser_type = args['parser_type'] # int, float, str
self.task_name = args['task_name']
self.save_dir = args['save_dir']
if self.parser_type == 'str':
self.nominal_list = [nn.strip() for nn in args['nominal_list'].split(',')]
self.nominal_ticks = [int(nn.strip()) for nn in args['nominal_ticks'].split(',')]
else:
self.nominal_list, self.nominal_ticks = None, None
def peer_review_single_round(self, reviewers, prompts):
'''
used in gaming sampling strategy
reviewers: LLM config list
prompts: an array, each item is a dict with key "prompt"
return a dict to denote the results of each evaluate task under all the reviews, key: reviewer model name, value: the original response of this reviewer
''' | apis_reviewer = [Auto_API.instantiate_api(config_api['api_type'], config_api) for config_api in reviewers] | 1 | 2023-11-16 18:40:23+00:00 | 2k |
tahaafarooq/werkzeug-hash-cracker | cracker.py | [
{
"identifier": "SimplifierSingle",
"path": "simplifiers/simplifier.py",
"snippet": "class SimplifierSingle(object):\n def __init__(self, hasho, wordlist):\n self.hasho = hasho\n self.wordlist = wordlist\n\n def crack_single_hash(self):\n with open(self.wordlist, \"r\", encodi... | import argparse
from simplifiers.simplifier import SimplifierSingle, SimplifierFile | 778 |
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Werkzeug Security Hash Cracker :: @tahaafarooq")
parser.add_argument('--single', nargs=2, metavar=('hash', 'wordlist'), help='Crack a single hash string')
parser.add_argument('--file', nargs=2, metavar=('hashfile', 'wordlist'), help='Crack a file with multiple hashes')
parser.add_argument('--about', action='store_true', help='Print core information about the script and developer')
args = parser.parse_args()
if args.about:
about = """
Werkzeug Hash Cracker: Is a minimal script that cracks hashes which are generated from werkzeug.security library in python\n
About Developer: Tahaa Farooq is a cybersecurity professional with a passion in programming. Check his github for more information (https://github.com/tahaafarooq)"""
print(about)
elif args.single:
hash_string, wordlist_file = args.single
simple_crack = SimplifierSingle(hash_string, wordlist_file)
simple_crack.crack_single_hash()
elif args.file:
hash_file, wordlist_file = args.file
|
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Werkzeug Security Hash Cracker :: @tahaafarooq")
parser.add_argument('--single', nargs=2, metavar=('hash', 'wordlist'), help='Crack a single hash string')
parser.add_argument('--file', nargs=2, metavar=('hashfile', 'wordlist'), help='Crack a file with multiple hashes')
parser.add_argument('--about', action='store_true', help='Print core information about the script and developer')
args = parser.parse_args()
if args.about:
about = """
Werkzeug Hash Cracker: Is a minimal script that cracks hashes which are generated from werkzeug.security library in python\n
About Developer: Tahaa Farooq is a cybersecurity professional with a passion in programming. Check his github for more information (https://github.com/tahaafarooq)"""
print(about)
elif args.single:
hash_string, wordlist_file = args.single
simple_crack = SimplifierSingle(hash_string, wordlist_file)
simple_crack.crack_single_hash()
elif args.file:
hash_file, wordlist_file = args.file | simple_crack = SimplifierFile(hash_file, wordlist_file) | 1 | 2023-11-10 01:29:15+00:00 | 2k |
victor0089/AirBnB_clone_v2 | models/engine/db_storage.py | [
{
"identifier": "Base",
"path": "models/base_model.py",
"snippet": "class BaseModel:\n def __init__(self, *args, **kwargs):\n def __str__(self):\n def __repr__(self):\n def save(self):\n def to_dict(self):\n def delete(self):"
},
{
"identifier": "State",
"path": "models/sta... | from os import getenv
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy import (create_engine)
from sqlalchemy.ext.declarative import declarative_base
from models.base_model import Base
from models.state import State
from models.city import City
from models.user import User
from models.place import Place
from models.review import Review
from models.amenity import Amenity | 1,599 | #!/usr/bin/python3
""" new class for sqlAlchemy """
class DBStorage:
""" create tables in environmental"""
__engine = None
__session = None
def __init__(self):
'''instantiate new dbstorage instance'''
HBNB_MYSQL_USER = getenv('HBNB_MYSQL_USER')
HBNB_MYSQL_PWD = getenv('HBNB_MYSQL_PWD')
HBNB_MYSQL_HOST = getenv('HBNB_MYSQL_HOST')
HBNB_MYSQL_DB = getenv('HBNB_MYSQL_DB')
HBNB_ENV = getenv('HBNB_ENV')
self.__engine = create_engine(
'mysql+mysqldb://{}:{}@{}/{}'.format(
HBNB_MYSQL_USER,
HBNB_MYSQL_PWD,
HBNB_MYSQL_HOST,
HBNB_MYSQL_DB
), pool_pre_ping=True)
if HBNB_ENV == 'test':
| #!/usr/bin/python3
""" new class for sqlAlchemy """
class DBStorage:
""" create tables in environmental"""
__engine = None
__session = None
def __init__(self):
'''instantiate new dbstorage instance'''
HBNB_MYSQL_USER = getenv('HBNB_MYSQL_USER')
HBNB_MYSQL_PWD = getenv('HBNB_MYSQL_PWD')
HBNB_MYSQL_HOST = getenv('HBNB_MYSQL_HOST')
HBNB_MYSQL_DB = getenv('HBNB_MYSQL_DB')
HBNB_ENV = getenv('HBNB_ENV')
self.__engine = create_engine(
'mysql+mysqldb://{}:{}@{}/{}'.format(
HBNB_MYSQL_USER,
HBNB_MYSQL_PWD,
HBNB_MYSQL_HOST,
HBNB_MYSQL_DB
), pool_pre_ping=True)
if HBNB_ENV == 'test': | Base.metadata.drop_all(self.__engine) | 0 | 2023-11-17 07:59:13+00:00 | 2k |
believethehype/nostrdvm | examples/ollama_dvm/main.py | [
{
"identifier": "TextGenerationLLMLite",
"path": "nostr_dvm/tasks/textgeneration_llmlite.py",
"snippet": "class TextGenerationLLMLite(DVMTaskInterface):\n KIND: int = EventDefinitions.KIND_NIP90_GENERATE_TEXT\n TASK: str = \"text-to-text\"\n FIX_COST: float = 0\n dependencies = [(\"nostr-dvm... | import json
import dotenv
from pathlib import Path
from nostr_dvm.tasks.textgeneration_llmlite import TextGenerationLLMLite
from nostr_dvm.utils.admin_utils import AdminConfig
from nostr_dvm.utils.dvmconfig import build_default_config
from nostr_dvm.utils.nip89_utils import NIP89Config, check_and_set_d_tag | 1,406 |
def main():
identifier = "llama2"
name = "Ollama"
|
def main():
identifier = "llama2"
name = "Ollama"
| dvm_config = build_default_config(identifier) | 2 | 2023-11-17 18:32:56+00:00 | 2k |
zouXH-god/meme_web | meme_generator/manager.py | [
{
"identifier": "meme_config",
"path": "meme_generator/config.py",
"snippet": "class MemeConfig(BaseModel):\nclass ResourceConfig(BaseModel):\nclass GifConfig(BaseModel):\nclass TranslatorConfig(BaseModel):\nclass ServerConfig(BaseModel):\nclass LogConfig(BaseModel):\nclass Config(BaseModel, extra=Extra... | import importlib
import importlib.util
import pkgutil
from pathlib import Path
from typing import Dict, List, Optional, Union
from .config import meme_config
from .exception import NoSuchMeme
from .log import logger
from .meme import Meme, MemeArgsType, MemeFunction, MemeParamsType | 942 |
_memes: Dict[str, Meme] = {}
def path_to_module_name(path: Path) -> str:
rel_path = path.resolve().relative_to(Path.cwd().resolve())
if rel_path.stem == "__init__":
return ".".join(rel_path.parts[:-1])
else:
return ".".join(rel_path.parts[:-1] + (rel_path.stem,))
def load_meme(module_path: Union[str, Path]):
module_name = (
path_to_module_name(module_path)
if isinstance(module_path, Path)
else module_path
)
try:
importlib.import_module(module_name)
except Exception as e:
logger.opt(colors=True, exception=e).error(f"Failed to import {module_path}!")
def load_memes(dir_path: Union[str, Path]):
if isinstance(dir_path, Path):
dir_path = str(dir_path.resolve())
for module_info in pkgutil.iter_modules([dir_path]):
if module_info.name.startswith("_"):
continue
if not (
module_spec := module_info.module_finder.find_spec(module_info.name, None)
):
continue
if not (module_path := module_spec.origin):
continue
if not (module_loader := module_spec.loader):
continue
try:
module = importlib.util.module_from_spec(module_spec)
module_loader.exec_module(module)
except Exception as e:
logger.opt(colors=True, exception=e).error(
f"Failed to import {module_path}!"
)
def add_meme(
key: str,
|
_memes: Dict[str, Meme] = {}
def path_to_module_name(path: Path) -> str:
rel_path = path.resolve().relative_to(Path.cwd().resolve())
if rel_path.stem == "__init__":
return ".".join(rel_path.parts[:-1])
else:
return ".".join(rel_path.parts[:-1] + (rel_path.stem,))
def load_meme(module_path: Union[str, Path]):
module_name = (
path_to_module_name(module_path)
if isinstance(module_path, Path)
else module_path
)
try:
importlib.import_module(module_name)
except Exception as e:
logger.opt(colors=True, exception=e).error(f"Failed to import {module_path}!")
def load_memes(dir_path: Union[str, Path]):
if isinstance(dir_path, Path):
dir_path = str(dir_path.resolve())
for module_info in pkgutil.iter_modules([dir_path]):
if module_info.name.startswith("_"):
continue
if not (
module_spec := module_info.module_finder.find_spec(module_info.name, None)
):
continue
if not (module_path := module_spec.origin):
continue
if not (module_loader := module_spec.loader):
continue
try:
module = importlib.util.module_from_spec(module_spec)
module_loader.exec_module(module)
except Exception as e:
logger.opt(colors=True, exception=e).error(
f"Failed to import {module_path}!"
)
def add_meme(
key: str, | function: MemeFunction, | 3 | 2023-11-12 12:31:53+00:00 | 2k |
embrake/Aquilify | aquilify/middlewares/dispatcher.py | [
{
"identifier": "ASGIApp",
"path": "aquilify/types.py",
"snippet": "T = typing.TypeVar(\"T\")"
},
{
"identifier": "JsonResponse",
"path": "aquilify/responses.py",
"snippet": "class JsonResponse(BaseResponse):\n def __init__(\n self,\n content: Union[Dict, Callable, None]... | import logging
from typing import Awaitable, Callable, Dict, Optional, Union
from ..types import ASGIApp, Receive, Scope, Send
from ..responses import JsonResponse | 1,306 | class Dispatcher:
"""
Dispatches incoming requests to different mounted ASGI apps based on the URL path.
Usage:
```python
# Create the main application
main_app = Aquilify()
# Create instances of the mounted apps
app1 = Aquilify()
app2 = Aquilify()
# Create the Dispatcher instance
dispatcher = Dispatcher(main_app, {})
# Map app1 to /app1 and app2 to /app2
dispatcher.map_url('/app1', app1)
dispatcher.map_url('/app2', app2)
# Define error handlers if necessary
async def error_handler1(scope, receive, send, exc):
# Custom error handling logic for app1
pass
async def error_handler2(scope, receive, send, exc):
# Custom error handling logic for app2
pass
dispatcher.map_url('/app1', app1, error_handler1)
dispatcher.map_url('/app2', app2, error_handler2)
# Run the dispatcher
@app.route("/")
async def homepage(request):
return JsonResponse({"message": "Hello, world!"})
@app.route("/app1")
async def app1_homepage(request):
return JSONResponse({"message": "App 1 homepage"})
@app.route("/app2")
async def app2_homepage(request):
return JSONResponse({"message": "App 2 homepage"})
```
"""
def __init__(self, main_app: ASGIApp, mounts: Dict[str, ASGIApp]) -> None:
"""
Initializes the Dispatcher instance.
Args:
main_app (ASGIApp): The main ASGI app to handle the requests.
mounts (Dict[str, ASGIApp]): A dictionary containing mounted apps.
Usage:
```python
main_app = Aquilify() # create a main app instance
app2 = Aquilify() #sub app for mounting in main_app
dispatcher = Dispatcher(main_app, {
'/app2': app2
})
Run:
$ netix --debug main:dispatcher
---------- or -----------
$ uvicorn main:dispatcher
"""
self.main_app: ASGIApp = main_app
self.mounts: Dict[str, ASGIApp] = mounts
self.error_handlers: Dict[str, Optional[Callable[..., Awaitable[None]]]] = {
mount_point: None for mount_point in mounts
}
self.logger = logging.getLogger(__name__)
def map_url(self, mount_point: str, app: ASGIApp,
error_handler: Optional[Callable[..., Awaitable[None]]] = None) -> None:
"""
Maps a URL mount point to a specified ASGI app.
Args:
mount_point (str): The URL mount point.
app (ASGIApp): The ASGI app to mount at the specified point.
error_handler (Optional[Callable[..., Awaitable[None]]]): Error handler for this mounted app.
"""
self.mounts[mount_point] = app
self.error_handlers[mount_point] = error_handler
def unmap_url(self, mount_point: str) -> None:
"""
Unmaps a URL mount point, removing the mounted app.
Args:
mount_point (str): The URL mount point to unmap.
"""
if mount_point in self.mounts:
del self.mounts[mount_point]
del self.error_handlers[mount_point]
async def conditional_mount(self, mount_point: str, app: ASGIApp,
condition: Union[Callable, Awaitable[bool]],
error_handler: Optional[Callable[..., Awaitable[None]]] = None) -> None:
"""
Mounts an ASGI app based on a specified condition.
Args:
mount_point (str): The URL mount point.
app (ASGIApp): The ASGI app to mount at the specified point.
condition (Union[Callable, Awaitable[bool]]): Condition to decide the mounting.
error_handler (Optional[Callable[..., Awaitable[None]]]): Error handler for this mounted app.
"""
if callable(condition):
condition = await condition()
if condition:
self.mounts[mount_point] = app
self.error_handlers[mount_point] = error_handler
|
class Dispatcher:
"""
Dispatches incoming requests to different mounted ASGI apps based on the URL path.
Usage:
```python
# Create the main application
main_app = Aquilify()
# Create instances of the mounted apps
app1 = Aquilify()
app2 = Aquilify()
# Create the Dispatcher instance
dispatcher = Dispatcher(main_app, {})
# Map app1 to /app1 and app2 to /app2
dispatcher.map_url('/app1', app1)
dispatcher.map_url('/app2', app2)
# Define error handlers if necessary
async def error_handler1(scope, receive, send, exc):
# Custom error handling logic for app1
pass
async def error_handler2(scope, receive, send, exc):
# Custom error handling logic for app2
pass
dispatcher.map_url('/app1', app1, error_handler1)
dispatcher.map_url('/app2', app2, error_handler2)
# Run the dispatcher
@app.route("/")
async def homepage(request):
return JsonResponse({"message": "Hello, world!"})
@app.route("/app1")
async def app1_homepage(request):
return JSONResponse({"message": "App 1 homepage"})
@app.route("/app2")
async def app2_homepage(request):
return JSONResponse({"message": "App 2 homepage"})
```
"""
def __init__(self, main_app: ASGIApp, mounts: Dict[str, ASGIApp]) -> None:
"""
Initializes the Dispatcher instance.
Args:
main_app (ASGIApp): The main ASGI app to handle the requests.
mounts (Dict[str, ASGIApp]): A dictionary containing mounted apps.
Usage:
```python
main_app = Aquilify() # create a main app instance
app2 = Aquilify() #sub app for mounting in main_app
dispatcher = Dispatcher(main_app, {
'/app2': app2
})
Run:
$ netix --debug main:dispatcher
---------- or -----------
$ uvicorn main:dispatcher
"""
self.main_app: ASGIApp = main_app
self.mounts: Dict[str, ASGIApp] = mounts
self.error_handlers: Dict[str, Optional[Callable[..., Awaitable[None]]]] = {
mount_point: None for mount_point in mounts
}
self.logger = logging.getLogger(__name__)
def map_url(self, mount_point: str, app: ASGIApp,
error_handler: Optional[Callable[..., Awaitable[None]]] = None) -> None:
"""
Maps a URL mount point to a specified ASGI app.
Args:
mount_point (str): The URL mount point.
app (ASGIApp): The ASGI app to mount at the specified point.
error_handler (Optional[Callable[..., Awaitable[None]]]): Error handler for this mounted app.
"""
self.mounts[mount_point] = app
self.error_handlers[mount_point] = error_handler
def unmap_url(self, mount_point: str) -> None:
"""
Unmaps a URL mount point, removing the mounted app.
Args:
mount_point (str): The URL mount point to unmap.
"""
if mount_point in self.mounts:
del self.mounts[mount_point]
del self.error_handlers[mount_point]
async def conditional_mount(self, mount_point: str, app: ASGIApp,
condition: Union[Callable, Awaitable[bool]],
error_handler: Optional[Callable[..., Awaitable[None]]] = None) -> None:
"""
Mounts an ASGI app based on a specified condition.
Args:
mount_point (str): The URL mount point.
app (ASGIApp): The ASGI app to mount at the specified point.
condition (Union[Callable, Awaitable[bool]]): Condition to decide the mounting.
error_handler (Optional[Callable[..., Awaitable[None]]]): Error handler for this mounted app.
"""
if callable(condition):
condition = await condition()
if condition:
self.mounts[mount_point] = app
self.error_handlers[mount_point] = error_handler
| async def dispatch(self, scope: Scope, receive: Receive, send: Send) -> None: | 0 | 2023-11-16 08:26:02+00:00 | 2k |
Viicos/django-autotyping | src/django_autotyping/app_settings.py | [
{
"identifier": "Self",
"path": "src/django_autotyping/_compat.py",
"snippet": "def is_relative_to(path: Path, other: Path) -> bool:"
},
{
"identifier": "AutotypingSettingsDict",
"path": "src/django_autotyping/typing.py",
"snippet": "class AutotypingSettingsDict(TypedDict, total=False):\... | from copy import deepcopy
from dataclasses import dataclass, field
from pathlib import Path
from django.conf import LazySettings
from ._compat import Self
from .typing import AutotypingSettingsDict, RulesT | 1,178 | from __future__ import annotations
@dataclass
class CodeGenerationSettings:
"""Configuration for adding type annotations to Django user code."""
PROJECT_DIR: Path | None = None
"""The directory of the project, where code modifications should be applied."""
DIFF: bool = False
"""Show changes to be applied instead of modifying existing files."""
TYPE_CHECKING_BLOCK: bool = True
"""Whether newly added imports should be in an `if TYPE_CHECKING` block (avoids circular imports)."""
ASSUME_CLASS_GETITEM: bool = False
"""Whether generic classes in stubs files but not at runtime should be assumed to have a
`__class_getitem__` method. This can be achieved by using `django-stubs-ext` or manually.
Affected rules: `DJA001`.
"""
@dataclass
class StubsGenerationSettings:
"""Configuration for dynamic stubs generation."""
LOCAL_STUBS_DIR: Path | None = None
"""The directory of the local type stubs. If not set, this setting must be set as a CLI argument."""
SOURCE_STUBS_DIR: Path | None = None
"""The directory of the source `django-stubs` to be used. Will default
to the first entry in site packages.
"""
ALLOW_PLAIN_MODEL_REFERENCES: bool = True
"""Whether string references in the form of `{model_name}` should be generated in overloads.
If set to `True`, both `{model_name}` and `{model_name}.{app_label}` are allowed
(unless the model name has a duplicate in a different app).
Affected rules: `DJAS001`.
"""
ALLOW_NONE_SET_TYPE: bool = False
"""Whether to allow having the `__set__` type variable set to `None`, even if the field is not nullable.
While Django allows setting most model instance fields to any value (before saving),
it is generally a bad practice to do so. However, it might be beneficial to allow `None`
to be set temporarly.
This also works for foreign fields, where unlike standard fields, the Django descriptor used
only allows model instances and `None` to be set.
Affected rules: `DJAS001`.
"""
MODEL_FIELDS_OPTIONAL: bool = True
"""Whether all model fields should be considered optional when creating model instances.
This affects the following signatures:
- [`Manager.create/acreate`][django.db.models.Manager]
- `__init__` methods of models
A lot can happen behind the scenes when instantiating models. Even if a field doesn't have
a default value provided, the database could have triggers implemented that would provide one.
This is why, by default, this configuration attribute defaults to `True`. If set to `False`,
`django-autotyping` will try its best to determine required fields, namely by checking if:
- the field can be [`null`][django.db.models.Field.null]
- the field has a default or a database default value set
- the field is a subclass of [`DateField`][django.db.models.DateField] and has
[`auto_now`][django.db.models.DateField.auto_now] or [`auto_now_add`][django.db.models.DateField.auto_now_add]
set to `True`.
Affected rules: `DJAS002`.
"""
ALLOW_REVERSE_ARGS: bool = False
"""Whether type checking should be added to the `args` argument of [`reverse`][django.urls.reverse].
By default, this is set to `False` to avoid having too many overloads being generated.
Moreover, only tuples can be type checked, and most people are using lists for this argument.
Instead, it is recommended to use the `kwargs` argument.
Affected rules: `DJAS011`.
"""
@dataclass
class AutotypingSettings:
"""A class holding the django-autotyping configuration."""
IGNORE: list[RulesT] = field(default_factory=list)
"""A list of ignored rules."""
STUBS_GENERATION: StubsGenerationSettings = field(default_factory=StubsGenerationSettings)
"""Stub related settings."""
CODE_GENERATION: CodeGenerationSettings = field(default_factory=CodeGenerationSettings)
"""Code generation related settings."""
@classmethod
| from __future__ import annotations
@dataclass
class CodeGenerationSettings:
"""Configuration for adding type annotations to Django user code."""
PROJECT_DIR: Path | None = None
"""The directory of the project, where code modifications should be applied."""
DIFF: bool = False
"""Show changes to be applied instead of modifying existing files."""
TYPE_CHECKING_BLOCK: bool = True
"""Whether newly added imports should be in an `if TYPE_CHECKING` block (avoids circular imports)."""
ASSUME_CLASS_GETITEM: bool = False
"""Whether generic classes in stubs files but not at runtime should be assumed to have a
`__class_getitem__` method. This can be achieved by using `django-stubs-ext` or manually.
Affected rules: `DJA001`.
"""
@dataclass
class StubsGenerationSettings:
"""Configuration for dynamic stubs generation."""
LOCAL_STUBS_DIR: Path | None = None
"""The directory of the local type stubs. If not set, this setting must be set as a CLI argument."""
SOURCE_STUBS_DIR: Path | None = None
"""The directory of the source `django-stubs` to be used. Will default
to the first entry in site packages.
"""
ALLOW_PLAIN_MODEL_REFERENCES: bool = True
"""Whether string references in the form of `{model_name}` should be generated in overloads.
If set to `True`, both `{model_name}` and `{model_name}.{app_label}` are allowed
(unless the model name has a duplicate in a different app).
Affected rules: `DJAS001`.
"""
ALLOW_NONE_SET_TYPE: bool = False
"""Whether to allow having the `__set__` type variable set to `None`, even if the field is not nullable.
While Django allows setting most model instance fields to any value (before saving),
it is generally a bad practice to do so. However, it might be beneficial to allow `None`
to be set temporarly.
This also works for foreign fields, where unlike standard fields, the Django descriptor used
only allows model instances and `None` to be set.
Affected rules: `DJAS001`.
"""
MODEL_FIELDS_OPTIONAL: bool = True
"""Whether all model fields should be considered optional when creating model instances.
This affects the following signatures:
- [`Manager.create/acreate`][django.db.models.Manager]
- `__init__` methods of models
A lot can happen behind the scenes when instantiating models. Even if a field doesn't have
a default value provided, the database could have triggers implemented that would provide one.
This is why, by default, this configuration attribute defaults to `True`. If set to `False`,
`django-autotyping` will try its best to determine required fields, namely by checking if:
- the field can be [`null`][django.db.models.Field.null]
- the field has a default or a database default value set
- the field is a subclass of [`DateField`][django.db.models.DateField] and has
[`auto_now`][django.db.models.DateField.auto_now] or [`auto_now_add`][django.db.models.DateField.auto_now_add]
set to `True`.
Affected rules: `DJAS002`.
"""
ALLOW_REVERSE_ARGS: bool = False
"""Whether type checking should be added to the `args` argument of [`reverse`][django.urls.reverse].
By default, this is set to `False` to avoid having too many overloads being generated.
Moreover, only tuples can be type checked, and most people are using lists for this argument.
Instead, it is recommended to use the `kwargs` argument.
Affected rules: `DJAS011`.
"""
@dataclass
class AutotypingSettings:
"""A class holding the django-autotyping configuration."""
IGNORE: list[RulesT] = field(default_factory=list)
"""A list of ignored rules."""
STUBS_GENERATION: StubsGenerationSettings = field(default_factory=StubsGenerationSettings)
"""Stub related settings."""
CODE_GENERATION: CodeGenerationSettings = field(default_factory=CodeGenerationSettings)
"""Code generation related settings."""
@classmethod | def from_django_settings(cls, settings: LazySettings) -> Self: | 0 | 2023-11-11 20:42:05+00:00 | 2k |
IBM/oper8 | oper8/cmd/setup_vcs_cmd.py | [
{
"identifier": "DEFAULT_DEST",
"path": "oper8/setup_vcs.py",
"snippet": "DEFAULT_DEST = \"oper8_vcs\""
},
{
"identifier": "DEFAULT_TAG_EXPR",
"path": "oper8/setup_vcs.py",
"snippet": "DEFAULT_TAG_EXPR = r\"[0-9]+\\.[0-9]+\\.[0-9]+\""
},
{
"identifier": "setup_vcs",
"path": "... | import argparse
import alog
from ..setup_vcs import DEFAULT_DEST, DEFAULT_TAG_EXPR, setup_vcs
from .base import CmdBase | 750 | """
CLI command for setting up a VCS version repo
"""
# Standard
# First Party
# Local
log = alog.use_channel("CMD-VCS")
class SetupVCSCmd(CmdBase):
__doc__ = __doc__
def add_subparser(
self,
subparsers: argparse._SubParsersAction,
) -> argparse.ArgumentParser:
"""Add the subparser for this command"""
parser = subparsers.add_parser(
"setup-vcs",
help="Initialize a clean git repo to use with VCS versioning",
)
command_args = parser.add_argument_group("Command Arguments")
command_args.add_argument(
"--source",
"-s",
required=True,
help="Source repo to seed the clean git history",
)
command_args.add_argument(
"--destination",
"-d",
| """
CLI command for setting up a VCS version repo
"""
# Standard
# First Party
# Local
log = alog.use_channel("CMD-VCS")
class SetupVCSCmd(CmdBase):
__doc__ = __doc__
def add_subparser(
self,
subparsers: argparse._SubParsersAction,
) -> argparse.ArgumentParser:
"""Add the subparser for this command"""
parser = subparsers.add_parser(
"setup-vcs",
help="Initialize a clean git repo to use with VCS versioning",
)
command_args = parser.add_argument_group("Command Arguments")
command_args.add_argument(
"--source",
"-s",
required=True,
help="Source repo to seed the clean git history",
)
command_args.add_argument(
"--destination",
"-d", | default=DEFAULT_DEST, | 0 | 2023-11-15 16:43:29+00:00 | 2k |
ariebovenberg/whenever | tests/test_naive_datetime.py | [
{
"identifier": "AlwaysEqual",
"path": "tests/common.py",
"snippet": "class AlwaysEqual:\n def __eq__(self, other):\n return True"
},
{
"identifier": "AlwaysLarger",
"path": "tests/common.py",
"snippet": "class AlwaysLarger:\n def __lt__(self, other):\n return False\n... | import pickle
import weakref
import pytest
from datetime import datetime as py_datetime
from datetime import timedelta, timezone
from hypothesis import given
from hypothesis.strategies import text
from whenever import InvalidFormat, NaiveDateTime
from .common import (
AlwaysEqual,
AlwaysLarger,
AlwaysSmaller,
NeverEqual,
local_ams_tz,
) | 1,181 |
def test_minimal():
d = NaiveDateTime(2020, 8, 15, 5, 12, 30, 450)
assert d.year == 2020
assert d.month == 8
assert d.day == 15
assert d.hour == 5
assert d.minute == 12
assert d.second == 30
assert d.microsecond == 450
assert (
NaiveDateTime(2020, 8, 15, 12)
== NaiveDateTime(2020, 8, 15, 12, 0)
== NaiveDateTime(2020, 8, 15, 12, 0, 0)
== NaiveDateTime(2020, 8, 15, 12, 0, 0, 0)
)
def test_immutable():
d = NaiveDateTime(2020, 8, 15)
with pytest.raises(AttributeError):
d.year = 2021 # type: ignore[misc]
class TestFromCanonicalStr:
def test_valid(self):
assert NaiveDateTime.from_canonical_str(
"2020-08-15T12:08:30"
) == NaiveDateTime(2020, 8, 15, 12, 8, 30)
def test_valid_three_fractions(self):
assert NaiveDateTime.from_canonical_str(
"2020-08-15T12:08:30.349"
) == NaiveDateTime(2020, 8, 15, 12, 8, 30, 349_000)
def test_valid_six_fractions(self):
assert NaiveDateTime.from_canonical_str(
"2020-08-15T12:08:30.349123"
) == NaiveDateTime(2020, 8, 15, 12, 8, 30, 349_123)
def test_single_space_instead_of_T(self):
assert NaiveDateTime.from_canonical_str(
"2020-08-15 12:08:30"
) == NaiveDateTime(2020, 8, 15, 12, 8, 30)
def test_unpadded(self):
with pytest.raises(InvalidFormat):
NaiveDateTime.from_canonical_str("2020-8-15T12:8:30")
def test_overly_precise_fraction(self):
with pytest.raises(InvalidFormat):
NaiveDateTime.from_canonical_str(
"2020-08-15T12:08:30.123456789123"
)
def test_trailing_z(self):
with pytest.raises(InvalidFormat):
NaiveDateTime.from_canonical_str("2020-08-15T12:08:30Z")
def test_no_seconds(self):
with pytest.raises(InvalidFormat):
NaiveDateTime.from_canonical_str("2020-08-15T12:08")
def test_empty(self):
with pytest.raises(InvalidFormat):
NaiveDateTime.from_canonical_str("")
def test_garbage(self):
with pytest.raises(InvalidFormat):
NaiveDateTime.from_canonical_str("garbage")
@given(text())
def test_fuzzing(self, s: str):
with pytest.raises(InvalidFormat):
NaiveDateTime.from_canonical_str(s)
def test_equality():
d = NaiveDateTime(2020, 8, 15)
different = NaiveDateTime(2020, 8, 16)
same = NaiveDateTime(2020, 8, 15)
assert d == same
assert d != different
assert not d == different
assert not d != same
assert hash(d) == hash(same)
assert hash(d) != hash(different)
|
def test_minimal():
d = NaiveDateTime(2020, 8, 15, 5, 12, 30, 450)
assert d.year == 2020
assert d.month == 8
assert d.day == 15
assert d.hour == 5
assert d.minute == 12
assert d.second == 30
assert d.microsecond == 450
assert (
NaiveDateTime(2020, 8, 15, 12)
== NaiveDateTime(2020, 8, 15, 12, 0)
== NaiveDateTime(2020, 8, 15, 12, 0, 0)
== NaiveDateTime(2020, 8, 15, 12, 0, 0, 0)
)
def test_immutable():
d = NaiveDateTime(2020, 8, 15)
with pytest.raises(AttributeError):
d.year = 2021 # type: ignore[misc]
class TestFromCanonicalStr:
def test_valid(self):
assert NaiveDateTime.from_canonical_str(
"2020-08-15T12:08:30"
) == NaiveDateTime(2020, 8, 15, 12, 8, 30)
def test_valid_three_fractions(self):
assert NaiveDateTime.from_canonical_str(
"2020-08-15T12:08:30.349"
) == NaiveDateTime(2020, 8, 15, 12, 8, 30, 349_000)
def test_valid_six_fractions(self):
assert NaiveDateTime.from_canonical_str(
"2020-08-15T12:08:30.349123"
) == NaiveDateTime(2020, 8, 15, 12, 8, 30, 349_123)
def test_single_space_instead_of_T(self):
assert NaiveDateTime.from_canonical_str(
"2020-08-15 12:08:30"
) == NaiveDateTime(2020, 8, 15, 12, 8, 30)
def test_unpadded(self):
with pytest.raises(InvalidFormat):
NaiveDateTime.from_canonical_str("2020-8-15T12:8:30")
def test_overly_precise_fraction(self):
with pytest.raises(InvalidFormat):
NaiveDateTime.from_canonical_str(
"2020-08-15T12:08:30.123456789123"
)
def test_trailing_z(self):
with pytest.raises(InvalidFormat):
NaiveDateTime.from_canonical_str("2020-08-15T12:08:30Z")
def test_no_seconds(self):
with pytest.raises(InvalidFormat):
NaiveDateTime.from_canonical_str("2020-08-15T12:08")
def test_empty(self):
with pytest.raises(InvalidFormat):
NaiveDateTime.from_canonical_str("")
def test_garbage(self):
with pytest.raises(InvalidFormat):
NaiveDateTime.from_canonical_str("garbage")
@given(text())
def test_fuzzing(self, s: str):
with pytest.raises(InvalidFormat):
NaiveDateTime.from_canonical_str(s)
def test_equality():
d = NaiveDateTime(2020, 8, 15)
different = NaiveDateTime(2020, 8, 16)
same = NaiveDateTime(2020, 8, 15)
assert d == same
assert d != different
assert not d == different
assert not d != same
assert hash(d) == hash(same)
assert hash(d) != hash(different)
| assert d == AlwaysEqual() | 0 | 2023-11-10 21:08:49+00:00 | 2k |
DataWizual/Raycasting | drawing.py | [
{
"identifier": "ray_casting",
"path": "ray_casting.py",
"snippet": "def ray_casting(sc, player_pos, player_angle):\r\n ox, oy = player_pos\r\n xm, ym = mapping(ox, oy)\r\n cur_angle = player_angle - HALF_FOV\r\n for ray in range(NUM_RAYS):\r\n sin_a = math.sin(cur_angle)\r\n c... | import pygame
from settings import *
from ray_casting import ray_casting
from map import mini_map
| 650 |
class Drawing:
def __init__(self, sc, sc_map):
self.sc = sc
self.sc_map = sc_map
self.font = pygame.font.SysFont('Arial', 36, bold=True)
def background(self):
pygame.draw.rect(self.sc, SKYBLUE, (0, 0, WIDTH, HALF_HEIGHT))
pygame.draw.rect(self.sc, DARKGREY, (0, HALF_HEIGHT, WIDTH, HALF_HEIGHT))
def world(self, player_pos, player_angle):
ray_casting(self.sc, player_pos, player_angle)
def fps(self, clock):
display_fps = str(int(clock.get_fps()))
render = self.font.render(display_fps, 0, CRED)
self.sc.blit(render, FPS_POS)
|
class Drawing:
def __init__(self, sc, sc_map):
self.sc = sc
self.sc_map = sc_map
self.font = pygame.font.SysFont('Arial', 36, bold=True)
def background(self):
pygame.draw.rect(self.sc, SKYBLUE, (0, 0, WIDTH, HALF_HEIGHT))
pygame.draw.rect(self.sc, DARKGREY, (0, HALF_HEIGHT, WIDTH, HALF_HEIGHT))
def world(self, player_pos, player_angle):
ray_casting(self.sc, player_pos, player_angle)
def fps(self, clock):
display_fps = str(int(clock.get_fps()))
render = self.font.render(display_fps, 0, CRED)
self.sc.blit(render, FPS_POS)
| def mini_map(self, player):
| 1 | 2023-11-15 12:18:25+00:00 | 2k |
CV-Reimplementation/Ucolor-Reimplementation | train.py | [
{
"identifier": "Config",
"path": "config/config.py",
"snippet": "class Config(object):\n r\"\"\"\n A collection of all the required configuration parameters. This class is a nested dict-like\n structure, with nested keys accessible as attributes. It contains sensible default values for\n al... | import warnings
import torch.optim as optim
from accelerate import Accelerator
from pytorch_msssim import SSIM
from torch.utils.data import DataLoader
from torchmetrics.functional import peak_signal_noise_ratio, structural_similarity_index_measure
from tqdm import tqdm
from config import Config
from data import get_training_data, get_validation_data
from models import *
from utils import * | 1,388 |
warnings.filterwarnings('ignore')
opt = Config('config.yml')
seed_everything(opt.OPTIM.SEED)
def train():
# Accelerate
accelerator = Accelerator(log_with='wandb') if opt.OPTIM.WANDB else Accelerator()
device = accelerator.device
config = {
"dataset": opt.TRAINING.TRAIN_DIR
}
accelerator.init_trackers("shadow", config=config)
if accelerator.is_local_main_process:
os.makedirs(opt.TRAINING.SAVE_DIR, exist_ok=True)
# Data Loader
train_dir = opt.TRAINING.TRAIN_DIR
val_dir = opt.TRAINING.VAL_DIR
train_dataset = get_training_data(train_dir, opt.MODEL.INPUT, opt.MODEL.TARGET, {'w': opt.TRAINING.PS_W, 'h': opt.TRAINING.PS_H})
train_loader = DataLoader(dataset=train_dataset, batch_size=opt.OPTIM.BATCH_SIZE, shuffle=True, num_workers=16,
drop_last=False, pin_memory=True)
|
warnings.filterwarnings('ignore')
opt = Config('config.yml')
seed_everything(opt.OPTIM.SEED)
def train():
# Accelerate
accelerator = Accelerator(log_with='wandb') if opt.OPTIM.WANDB else Accelerator()
device = accelerator.device
config = {
"dataset": opt.TRAINING.TRAIN_DIR
}
accelerator.init_trackers("shadow", config=config)
if accelerator.is_local_main_process:
os.makedirs(opt.TRAINING.SAVE_DIR, exist_ok=True)
# Data Loader
train_dir = opt.TRAINING.TRAIN_DIR
val_dir = opt.TRAINING.VAL_DIR
train_dataset = get_training_data(train_dir, opt.MODEL.INPUT, opt.MODEL.TARGET, {'w': opt.TRAINING.PS_W, 'h': opt.TRAINING.PS_H})
train_loader = DataLoader(dataset=train_dataset, batch_size=opt.OPTIM.BATCH_SIZE, shuffle=True, num_workers=16,
drop_last=False, pin_memory=True) | val_dataset = get_validation_data(val_dir, opt.MODEL.INPUT, opt.MODEL.TARGET, {'w': opt.TRAINING.PS_W, 'h': opt.TRAINING.PS_H, 'ori': opt.TRAINING.ORI}) | 2 | 2023-11-14 05:40:54+00:00 | 2k |
ottuco/multi-api-mocker | multi_api_mocker/contrib/pytest_plugin.py | [
{
"identifier": "group_by_url",
"path": "multi_api_mocker/utils.py",
"snippet": "def group_by_url(api_mocks: List[MockAPIResponse]) -> List[MockConfiguration]:\n \"\"\"\n Organizes a list of MockAPIResponse objects by their URL and method, grouping\n them into lists of responses for each endpoi... | import pytest
from requests_mock import Mocker
from ..utils import group_by_url, MockSet | 1,383 |
@pytest.fixture(scope="function")
def setup_api_mocks(requests_mock: Mocker, request) -> MockSet:
"""
A pytest fixture for configuring mock API responses in a test environment.
It takes subclasses of MockAPIResponse, each representing a unique API call
configuration. These subclasses facilitate the creation of simple or complex
response flows, simulating real-world API interactions.
Parameters:
requests_mock (Mocker): The pytest requests_mock fixture.
request: The pytest request object containing parametrized test data.
Returns:
MockSet: An instance of MockSet containing the organized MockAPIResponse
objects, ready for use in tests.
The fixture supports multiple test scenarios, allowing for thorough
testing of varying API response conditions. This is especially useful
for simulating sequences of API calls like Fork, Commit, and Push
in a version control system context.
Example Usage:
- Single API Call Test:
@pytest.mark.parametrize("setup_api_mocks", [([Fork()])], indirect=True)
- Multi-call Sequence Test:
@pytest.mark.parametrize(
"setup_api_mocks", [([Fork(), Commit(), Push()])], indirect=True
)
- Testing Multiple Scenarios:
@pytest.mark.parametrize(
"setup_api_mocks",
[([Fork(), Commit(), Push()]), ([Fork(), Commit(), ForcePush()])],
indirect=True
)
This fixture converts the list of MockAPIResponse subclasses into MockConfiguration
instances, registers them with requests_mock, and returns a MockSet object, which
allows querying each mock by its endpoint name.
"""
# Convert the incoming parameter to a list of MockConfiguration instances
|
@pytest.fixture(scope="function")
def setup_api_mocks(requests_mock: Mocker, request) -> MockSet:
"""
A pytest fixture for configuring mock API responses in a test environment.
It takes subclasses of MockAPIResponse, each representing a unique API call
configuration. These subclasses facilitate the creation of simple or complex
response flows, simulating real-world API interactions.
Parameters:
requests_mock (Mocker): The pytest requests_mock fixture.
request: The pytest request object containing parametrized test data.
Returns:
MockSet: An instance of MockSet containing the organized MockAPIResponse
objects, ready for use in tests.
The fixture supports multiple test scenarios, allowing for thorough
testing of varying API response conditions. This is especially useful
for simulating sequences of API calls like Fork, Commit, and Push
in a version control system context.
Example Usage:
- Single API Call Test:
@pytest.mark.parametrize("setup_api_mocks", [([Fork()])], indirect=True)
- Multi-call Sequence Test:
@pytest.mark.parametrize(
"setup_api_mocks", [([Fork(), Commit(), Push()])], indirect=True
)
- Testing Multiple Scenarios:
@pytest.mark.parametrize(
"setup_api_mocks",
[([Fork(), Commit(), Push()]), ([Fork(), Commit(), ForcePush()])],
indirect=True
)
This fixture converts the list of MockAPIResponse subclasses into MockConfiguration
instances, registers them with requests_mock, and returns a MockSet object, which
allows querying each mock by its endpoint name.
"""
# Convert the incoming parameter to a list of MockConfiguration instances | api_mocks_configurations = group_by_url(request.param) | 0 | 2023-11-12 08:01:06+00:00 | 2k |
Jisencc/yolov5_dual_weighting | utils/segment/augmentations.py | [
{
"identifier": "box_candidates",
"path": "utils/augmentations.py",
"snippet": "def box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n)\n # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio\n ... | import math
import random
import cv2
import numpy as np
from ..augmentations import box_candidates
from ..general import resample_segments, segment2box | 1,500 | # YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
"""
Image augmentation functions
"""
def mixup(im, labels, segments, im2, labels2, segments2):
# Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf
r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
im = (im * r + im2 * (1 - r)).astype(np.uint8)
labels = np.concatenate((labels, labels2), 0)
segments = np.concatenate((segments, segments2), 0)
return im, labels, segments
def random_perspective(im,
targets=(),
segments=(),
degrees=10,
translate=.1,
scale=.1,
shear=10,
perspective=0.0,
border=(0, 0)):
# torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
# targets = [cls, xyxy]
height = im.shape[0] + border[0] * 2 # shape(h,w,c)
width = im.shape[1] + border[1] * 2
# Center
C = np.eye(3)
C[0, 2] = -im.shape[1] / 2 # x translation (pixels)
C[1, 2] = -im.shape[0] / 2 # y translation (pixels)
# Perspective
P = np.eye(3)
P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
# Rotation and Scale
R = np.eye(3)
a = random.uniform(-degrees, degrees)
# a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
s = random.uniform(1 - scale, 1 + scale)
# s = 2 ** random.uniform(-scale, scale)
R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
# Shear
S = np.eye(3)
S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
# Translation
T = np.eye(3)
T[0, 2] = (random.uniform(0.5 - translate, 0.5 + translate) * width) # x translation (pixels)
T[1, 2] = (random.uniform(0.5 - translate, 0.5 + translate) * height) # y translation (pixels)
# Combined rotation matrix
M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
if perspective:
im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114))
else: # affine
im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
# Visualize
# import matplotlib.pyplot as plt
# ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
# ax[0].imshow(im[:, :, ::-1]) # base
# ax[1].imshow(im2[:, :, ::-1]) # warped
# Transform label coordinates
n = len(targets)
new_segments = []
if n:
new = np.zeros((n, 4))
| # YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
"""
Image augmentation functions
"""
def mixup(im, labels, segments, im2, labels2, segments2):
# Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf
r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
im = (im * r + im2 * (1 - r)).astype(np.uint8)
labels = np.concatenate((labels, labels2), 0)
segments = np.concatenate((segments, segments2), 0)
return im, labels, segments
def random_perspective(im,
targets=(),
segments=(),
degrees=10,
translate=.1,
scale=.1,
shear=10,
perspective=0.0,
border=(0, 0)):
# torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
# targets = [cls, xyxy]
height = im.shape[0] + border[0] * 2 # shape(h,w,c)
width = im.shape[1] + border[1] * 2
# Center
C = np.eye(3)
C[0, 2] = -im.shape[1] / 2 # x translation (pixels)
C[1, 2] = -im.shape[0] / 2 # y translation (pixels)
# Perspective
P = np.eye(3)
P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
# Rotation and Scale
R = np.eye(3)
a = random.uniform(-degrees, degrees)
# a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
s = random.uniform(1 - scale, 1 + scale)
# s = 2 ** random.uniform(-scale, scale)
R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
# Shear
S = np.eye(3)
S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
# Translation
T = np.eye(3)
T[0, 2] = (random.uniform(0.5 - translate, 0.5 + translate) * width) # x translation (pixels)
T[1, 2] = (random.uniform(0.5 - translate, 0.5 + translate) * height) # y translation (pixels)
# Combined rotation matrix
M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
if perspective:
im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114))
else: # affine
im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
# Visualize
# import matplotlib.pyplot as plt
# ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
# ax[0].imshow(im[:, :, ::-1]) # base
# ax[1].imshow(im2[:, :, ::-1]) # warped
# Transform label coordinates
n = len(targets)
new_segments = []
if n:
new = np.zeros((n, 4)) | segments = resample_segments(segments) # upsample | 1 | 2023-11-12 13:28:26+00:00 | 2k |
Subsets and Splits
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that have consistent code formatting levels across multiple scales (2k, 4k, 8k, 12k) and reveals the structured formatting patterns within these repositories.
SQL Console for tianyang/repobench_python_v1.1
Compares cross-file and in-file code structure patterns across different complexity levels, revealing how file organization strategies vary with code size and potentially informing better code architecture decisions.
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that have complete performance data across all seven code complexity levels, revealing consistent benchmarking patterns across different code sizes.
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that contain all 7 distinct quality levels (2k through 32k), revealing complete datasets that might be useful for comprehensive analysis.