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 |
|---|---|---|---|---|---|---|---|---|---|---|
zkarpinski/codeinsight-sdk-python | codeinsight_sdk/client.py | [
{
"identifier": "ProjectHandler",
"path": "codeinsight_sdk/handlers.py",
"snippet": "class ProjectHandler(Handler):\n def __init__(self, client):\n super().__init__(client)\n self.cls = Project\n\n def create(self, name:str, description:str = None, folder:str = None,\n ... | import requests
import logging
from .handlers import ProjectHandler, Handler, ReportHandler
from .models import Project, ProjectInventory, Report
from .exceptions import CodeInsightError | 2,652 |
logger = logging.getLogger(__name__)
class CodeInsightClient:
def __init__(self,
base_url: str,
api_token: str,
timeout: int = 60,
verify_ssl: bool = True
):
self.base_url = base_url
self.api_url = f"{base_url}/codeinsight/api"
self.__api_token = api_token
self.__api_headers = {
'Content-Type': 'application/json',
"Authorization": "Bearer %s" % self.__api_token,
"User-Agent": "codeinsight_sdk_python",
}
self.__timeout = timeout
self.__verify_ssl = verify_ssl
def request(self, method, url_part: str, params: dict = None, body: any = None ):
url = f"{self.api_url}/{url_part}"
# Iterate over params and remove any that are None (Empty)
if(params):
for k, v in list(params.items()):
if v is None:
del params[k]
response = requests.request(method, url,
headers=self.__api_headers, params=params, json=body,
timeout=self.__timeout, verify=self.__verify_ssl)
if not response.ok:
logger.error(f"Error: {response.status_code} - {response.reason}", exc_info=True)
logger.error(response.text)
raise CodeInsightError(response)
return response
@property
|
logger = logging.getLogger(__name__)
class CodeInsightClient:
def __init__(self,
base_url: str,
api_token: str,
timeout: int = 60,
verify_ssl: bool = True
):
self.base_url = base_url
self.api_url = f"{base_url}/codeinsight/api"
self.__api_token = api_token
self.__api_headers = {
'Content-Type': 'application/json',
"Authorization": "Bearer %s" % self.__api_token,
"User-Agent": "codeinsight_sdk_python",
}
self.__timeout = timeout
self.__verify_ssl = verify_ssl
def request(self, method, url_part: str, params: dict = None, body: any = None ):
url = f"{self.api_url}/{url_part}"
# Iterate over params and remove any that are None (Empty)
if(params):
for k, v in list(params.items()):
if v is None:
del params[k]
response = requests.request(method, url,
headers=self.__api_headers, params=params, json=body,
timeout=self.__timeout, verify=self.__verify_ssl)
if not response.ok:
logger.error(f"Error: {response.status_code} - {response.reason}", exc_info=True)
logger.error(response.text)
raise CodeInsightError(response)
return response
@property | def projects(self) -> ProjectHandler: | 0 | 2023-12-29 00:49:12+00:00 | 4k |
daswer123/rvc-python | rvc_python/lib/infer_pack/modules.py | [
{
"identifier": "commons",
"path": "rvc_python/lib/infer_pack/commons.py",
"snippet": "def init_weights(m, mean=0.0, std=0.01):\ndef get_padding(kernel_size, dilation=1):\ndef convert_pad_shape(pad_shape):\ndef kl_divergence(m_p, logs_p, m_q, logs_q):\ndef rand_gumbel(shape):\ndef rand_gumbel_like(x):\n... | import copy
import math
import numpy as np
import scipy
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
from torch.nn.utils import weight_norm, remove_weight_norm
from rvc_python.lib.infer_pack import commons
from rvc_python.lib.infer_pack.commons import init_weights, get_padding
from rvc_python.lib.infer_pack.transforms import piecewise_rational_quadratic_transform | 2,889 | class ElementwiseAffine(nn.Module):
def __init__(self, channels):
super().__init__()
self.channels = channels
self.m = nn.Parameter(torch.zeros(channels, 1))
self.logs = nn.Parameter(torch.zeros(channels, 1))
def forward(self, x, x_mask, reverse=False, **kwargs):
if not reverse:
y = self.m + torch.exp(self.logs) * x
y = y * x_mask
logdet = torch.sum(self.logs * x_mask, [1, 2])
return y, logdet
else:
x = (x - self.m) * torch.exp(-self.logs) * x_mask
return x
class ResidualCouplingLayer(nn.Module):
def __init__(
self,
channels,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
p_dropout=0,
gin_channels=0,
mean_only=False,
):
assert channels % 2 == 0, "channels should be divisible by 2"
super().__init__()
self.channels = channels
self.hidden_channels = hidden_channels
self.kernel_size = kernel_size
self.dilation_rate = dilation_rate
self.n_layers = n_layers
self.half_channels = channels // 2
self.mean_only = mean_only
self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
self.enc = WN(
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
p_dropout=p_dropout,
gin_channels=gin_channels,
)
self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
self.post.weight.data.zero_()
self.post.bias.data.zero_()
def forward(self, x, x_mask, g=None, reverse=False):
x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
h = self.pre(x0) * x_mask
h = self.enc(h, x_mask, g=g)
stats = self.post(h) * x_mask
if not self.mean_only:
m, logs = torch.split(stats, [self.half_channels] * 2, 1)
else:
m = stats
logs = torch.zeros_like(m)
if not reverse:
x1 = m + x1 * torch.exp(logs) * x_mask
x = torch.cat([x0, x1], 1)
logdet = torch.sum(logs, [1, 2])
return x, logdet
else:
x1 = (x1 - m) * torch.exp(-logs) * x_mask
x = torch.cat([x0, x1], 1)
return x
def remove_weight_norm(self):
self.enc.remove_weight_norm()
class ConvFlow(nn.Module):
def __init__(
self,
in_channels,
filter_channels,
kernel_size,
n_layers,
num_bins=10,
tail_bound=5.0,
):
super().__init__()
self.in_channels = in_channels
self.filter_channels = filter_channels
self.kernel_size = kernel_size
self.n_layers = n_layers
self.num_bins = num_bins
self.tail_bound = tail_bound
self.half_channels = in_channels // 2
self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.0)
self.proj = nn.Conv1d(
filter_channels, self.half_channels * (num_bins * 3 - 1), 1
)
self.proj.weight.data.zero_()
self.proj.bias.data.zero_()
def forward(self, x, x_mask, g=None, reverse=False):
x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
h = self.pre(x0)
h = self.convs(h, x_mask, g=g)
h = self.proj(h) * x_mask
b, c, t = x0.shape
h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
unnormalized_widths = h[..., : self.num_bins] / math.sqrt(self.filter_channels)
unnormalized_heights = h[..., self.num_bins : 2 * self.num_bins] / math.sqrt(
self.filter_channels
)
unnormalized_derivatives = h[..., 2 * self.num_bins :]
|
LRELU_SLOPE = 0.1
class LayerNorm(nn.Module):
def __init__(self, channels, eps=1e-5):
super().__init__()
self.channels = channels
self.eps = eps
self.gamma = nn.Parameter(torch.ones(channels))
self.beta = nn.Parameter(torch.zeros(channels))
def forward(self, x):
x = x.transpose(1, -1)
x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
return x.transpose(1, -1)
class ConvReluNorm(nn.Module):
def __init__(
self,
in_channels,
hidden_channels,
out_channels,
kernel_size,
n_layers,
p_dropout,
):
super().__init__()
self.in_channels = in_channels
self.hidden_channels = hidden_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.n_layers = n_layers
self.p_dropout = p_dropout
assert n_layers > 1, "Number of layers should be larger than 0."
self.conv_layers = nn.ModuleList()
self.norm_layers = nn.ModuleList()
self.conv_layers.append(
nn.Conv1d(
in_channels, hidden_channels, kernel_size, padding=kernel_size // 2
)
)
self.norm_layers.append(LayerNorm(hidden_channels))
self.relu_drop = nn.Sequential(nn.ReLU(), nn.Dropout(p_dropout))
for _ in range(n_layers - 1):
self.conv_layers.append(
nn.Conv1d(
hidden_channels,
hidden_channels,
kernel_size,
padding=kernel_size // 2,
)
)
self.norm_layers.append(LayerNorm(hidden_channels))
self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
self.proj.weight.data.zero_()
self.proj.bias.data.zero_()
def forward(self, x, x_mask):
x_org = x
for i in range(self.n_layers):
x = self.conv_layers[i](x * x_mask)
x = self.norm_layers[i](x)
x = self.relu_drop(x)
x = x_org + self.proj(x)
return x * x_mask
class DDSConv(nn.Module):
"""
Dialted and Depth-Separable Convolution
"""
def __init__(self, channels, kernel_size, n_layers, p_dropout=0.0):
super().__init__()
self.channels = channels
self.kernel_size = kernel_size
self.n_layers = n_layers
self.p_dropout = p_dropout
self.drop = nn.Dropout(p_dropout)
self.convs_sep = nn.ModuleList()
self.convs_1x1 = nn.ModuleList()
self.norms_1 = nn.ModuleList()
self.norms_2 = nn.ModuleList()
for i in range(n_layers):
dilation = kernel_size**i
padding = (kernel_size * dilation - dilation) // 2
self.convs_sep.append(
nn.Conv1d(
channels,
channels,
kernel_size,
groups=channels,
dilation=dilation,
padding=padding,
)
)
self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
self.norms_1.append(LayerNorm(channels))
self.norms_2.append(LayerNorm(channels))
def forward(self, x, x_mask, g=None):
if g is not None:
x = x + g
for i in range(self.n_layers):
y = self.convs_sep[i](x * x_mask)
y = self.norms_1[i](y)
y = F.gelu(y)
y = self.convs_1x1[i](y)
y = self.norms_2[i](y)
y = F.gelu(y)
y = self.drop(y)
x = x + y
return x * x_mask
class WN(torch.nn.Module):
def __init__(
self,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
gin_channels=0,
p_dropout=0,
):
super(WN, self).__init__()
assert kernel_size % 2 == 1
self.hidden_channels = hidden_channels
self.kernel_size = (kernel_size,)
self.dilation_rate = dilation_rate
self.n_layers = n_layers
self.gin_channels = gin_channels
self.p_dropout = p_dropout
self.in_layers = torch.nn.ModuleList()
self.res_skip_layers = torch.nn.ModuleList()
self.drop = nn.Dropout(p_dropout)
if gin_channels != 0:
cond_layer = torch.nn.Conv1d(
gin_channels, 2 * hidden_channels * n_layers, 1
)
self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name="weight")
for i in range(n_layers):
dilation = dilation_rate**i
padding = int((kernel_size * dilation - dilation) / 2)
in_layer = torch.nn.Conv1d(
hidden_channels,
2 * hidden_channels,
kernel_size,
dilation=dilation,
padding=padding,
)
in_layer = torch.nn.utils.weight_norm(in_layer, name="weight")
self.in_layers.append(in_layer)
# last one is not necessary
if i < n_layers - 1:
res_skip_channels = 2 * hidden_channels
else:
res_skip_channels = hidden_channels
res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name="weight")
self.res_skip_layers.append(res_skip_layer)
def forward(self, x, x_mask, g=None, **kwargs):
output = torch.zeros_like(x)
n_channels_tensor = torch.IntTensor([self.hidden_channels])
if g is not None:
g = self.cond_layer(g)
for i in range(self.n_layers):
x_in = self.in_layers[i](x)
if g is not None:
cond_offset = i * 2 * self.hidden_channels
g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
else:
g_l = torch.zeros_like(x_in)
acts = commons.fused_add_tanh_sigmoid_multiply(x_in, g_l, n_channels_tensor)
acts = self.drop(acts)
res_skip_acts = self.res_skip_layers[i](acts)
if i < self.n_layers - 1:
res_acts = res_skip_acts[:, : self.hidden_channels, :]
x = (x + res_acts) * x_mask
output = output + res_skip_acts[:, self.hidden_channels :, :]
else:
output = output + res_skip_acts
return output * x_mask
def remove_weight_norm(self):
if self.gin_channels != 0:
torch.nn.utils.remove_weight_norm(self.cond_layer)
for l in self.in_layers:
torch.nn.utils.remove_weight_norm(l)
for l in self.res_skip_layers:
torch.nn.utils.remove_weight_norm(l)
class ResBlock1(torch.nn.Module):
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
super(ResBlock1, self).__init__()
self.convs1 = nn.ModuleList(
[
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=dilation[0],
padding=get_padding(kernel_size, dilation[0]),
)
),
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=dilation[1],
padding=get_padding(kernel_size, dilation[1]),
)
),
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=dilation[2],
padding=get_padding(kernel_size, dilation[2]),
)
),
]
)
self.convs1.apply(init_weights)
self.convs2 = nn.ModuleList(
[
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=1,
padding=get_padding(kernel_size, 1),
)
),
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=1,
padding=get_padding(kernel_size, 1),
)
),
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=1,
padding=get_padding(kernel_size, 1),
)
),
]
)
self.convs2.apply(init_weights)
def forward(self, x, x_mask=None):
for c1, c2 in zip(self.convs1, self.convs2):
xt = F.leaky_relu(x, LRELU_SLOPE)
if x_mask is not None:
xt = xt * x_mask
xt = c1(xt)
xt = F.leaky_relu(xt, LRELU_SLOPE)
if x_mask is not None:
xt = xt * x_mask
xt = c2(xt)
x = xt + x
if x_mask is not None:
x = x * x_mask
return x
def remove_weight_norm(self):
for l in self.convs1:
remove_weight_norm(l)
for l in self.convs2:
remove_weight_norm(l)
class ResBlock2(torch.nn.Module):
def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
super(ResBlock2, self).__init__()
self.convs = nn.ModuleList(
[
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=dilation[0],
padding=get_padding(kernel_size, dilation[0]),
)
),
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=dilation[1],
padding=get_padding(kernel_size, dilation[1]),
)
),
]
)
self.convs.apply(init_weights)
def forward(self, x, x_mask=None):
for c in self.convs:
xt = F.leaky_relu(x, LRELU_SLOPE)
if x_mask is not None:
xt = xt * x_mask
xt = c(xt)
x = xt + x
if x_mask is not None:
x = x * x_mask
return x
def remove_weight_norm(self):
for l in self.convs:
remove_weight_norm(l)
class Log(nn.Module):
def forward(self, x, x_mask, reverse=False, **kwargs):
if not reverse:
y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
logdet = torch.sum(-y, [1, 2])
return y, logdet
else:
x = torch.exp(x) * x_mask
return x
class Flip(nn.Module):
def forward(self, x, *args, reverse=False, **kwargs):
x = torch.flip(x, [1])
if not reverse:
logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
return x, logdet
else:
return x
class ElementwiseAffine(nn.Module):
def __init__(self, channels):
super().__init__()
self.channels = channels
self.m = nn.Parameter(torch.zeros(channels, 1))
self.logs = nn.Parameter(torch.zeros(channels, 1))
def forward(self, x, x_mask, reverse=False, **kwargs):
if not reverse:
y = self.m + torch.exp(self.logs) * x
y = y * x_mask
logdet = torch.sum(self.logs * x_mask, [1, 2])
return y, logdet
else:
x = (x - self.m) * torch.exp(-self.logs) * x_mask
return x
class ResidualCouplingLayer(nn.Module):
def __init__(
self,
channels,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
p_dropout=0,
gin_channels=0,
mean_only=False,
):
assert channels % 2 == 0, "channels should be divisible by 2"
super().__init__()
self.channels = channels
self.hidden_channels = hidden_channels
self.kernel_size = kernel_size
self.dilation_rate = dilation_rate
self.n_layers = n_layers
self.half_channels = channels // 2
self.mean_only = mean_only
self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
self.enc = WN(
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
p_dropout=p_dropout,
gin_channels=gin_channels,
)
self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
self.post.weight.data.zero_()
self.post.bias.data.zero_()
def forward(self, x, x_mask, g=None, reverse=False):
x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
h = self.pre(x0) * x_mask
h = self.enc(h, x_mask, g=g)
stats = self.post(h) * x_mask
if not self.mean_only:
m, logs = torch.split(stats, [self.half_channels] * 2, 1)
else:
m = stats
logs = torch.zeros_like(m)
if not reverse:
x1 = m + x1 * torch.exp(logs) * x_mask
x = torch.cat([x0, x1], 1)
logdet = torch.sum(logs, [1, 2])
return x, logdet
else:
x1 = (x1 - m) * torch.exp(-logs) * x_mask
x = torch.cat([x0, x1], 1)
return x
def remove_weight_norm(self):
self.enc.remove_weight_norm()
class ConvFlow(nn.Module):
def __init__(
self,
in_channels,
filter_channels,
kernel_size,
n_layers,
num_bins=10,
tail_bound=5.0,
):
super().__init__()
self.in_channels = in_channels
self.filter_channels = filter_channels
self.kernel_size = kernel_size
self.n_layers = n_layers
self.num_bins = num_bins
self.tail_bound = tail_bound
self.half_channels = in_channels // 2
self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.0)
self.proj = nn.Conv1d(
filter_channels, self.half_channels * (num_bins * 3 - 1), 1
)
self.proj.weight.data.zero_()
self.proj.bias.data.zero_()
def forward(self, x, x_mask, g=None, reverse=False):
x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
h = self.pre(x0)
h = self.convs(h, x_mask, g=g)
h = self.proj(h) * x_mask
b, c, t = x0.shape
h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
unnormalized_widths = h[..., : self.num_bins] / math.sqrt(self.filter_channels)
unnormalized_heights = h[..., self.num_bins : 2 * self.num_bins] / math.sqrt(
self.filter_channels
)
unnormalized_derivatives = h[..., 2 * self.num_bins :]
| x1, logabsdet = piecewise_rational_quadratic_transform( | 3 | 2023-12-26 19:05:42+00:00 | 4k |
Eeems-Org/remarkable-update-fuse | remarkable_update_fuse/fuse.py | [
{
"identifier": "UpdateImage",
"path": "remarkable_update_fuse/image.py",
"snippet": "class UpdateImage(io.RawIOBase):\n _manifest = None\n _offset = -1\n _size = 0\n _pos = 0\n\n def __init__(self, update_file, cache_size=500, cache_ttl=60):\n self.update_file = update_file\n ... | import errno
import os
import queue
import sys
import threading
import time
import warnings
import fuse
import ext4
from pathlib import PurePosixPath
from .image import UpdateImage
from .image import UpdateImageSignatureException
from .threads import KillableThread | 2,927 | f" {self.modifiers}",
" -o ",
]
)
+ ",\n ".join(self._str_core())
+ " >"
)
class FuseOptParse(fuse.FuseOptParse):
def __init__(self, *args, **kw):
fuse.FuseOptParse.__init__(self, *args, **kw)
def parse_args(self, args=None, values=None):
_opts, _args = fuse.FuseOptParse.parse_args(self, args, values)
if _args:
self.fuse_args.update_file = os.path.realpath(_args.pop())
return _opts, _args
class Stat(fuse.Stat):
def __init__(self):
self.st_mode = 0
self.st_ino = 0
self.st_dev = 0
self.st_nlink = 0
self.st_uid = 0
self.st_gid = 0
self.st_size = 0
self.st_atime = 0
self.st_mtime = 0
self.st_ctime = 0
class UpdateFS(fuse.Fuse):
version = "%prog " + fuse.__version__
fusage = "%prog update_file mountpoint [options]"
dash_s_do = "setsingle"
disable_path_cache = False
cache_debug = False
cache_size = 500
cache_ttl = 60
image = None
volume = None
inode_cache = {}
queue = None
exit_threads = False
def __init__(self, *args, **kw):
fuse.Fuse.__init__(
self,
*args,
fuse_args=FuseArgs(),
parser_class=FuseOptParse,
**kw,
)
self.parser.add_option(
mountopt="disable_path_cache",
action="store_true",
help="Disable path caching",
)
self.parser.add_option(
mountopt="cache_debug",
action="store_true",
help="Debug output for path caching",
)
self.parser.add_option(
mountopt="cache_size",
default=500,
type="int",
help="Size in MB of memory cache for speeding up filesytem access [default: %default]",
)
self.parser.add_option(
mountopt="cache_ttl",
default=60,
type="int",
help="Seconds before the memory cache will evict unused chunks [default: %default]",
)
@property
def update_file(self):
return self.fuse_args.update_file
@property
def mountpoint(self):
return self.fuse_args.mountpoint
def fuse_error(self, msg):
print(msg, file=sys.stderr)
self.fuse_args.setmod("showhelp")
fuse.Fuse.main(self, self.args)
sys.exit(1)
def main(self, args=None):
self.args = args
if self.fuse_args.getmod("showhelp"):
fuse.Fuse.main(self, args)
return
if self.update_file is None:
self.fuse_error("fuse: missing update_file parameter")
if not os.path.exists(self.update_file):
self.fuse_error(f"fuse: File does not exist {self.update_file}")
self.image = UpdateImage(
self.update_file,
cache_size=self.cache_size,
cache_ttl=self.cache_ttl,
)
self.volume = ext4.Volume(self.image, offset=0)
print("Verifying signature...")
try:
self.image.verify(
self.get_inode("/usr/share/update_engine/update-payload-key.pub.pem")
.open()
.read()
)
print("Signature verified")
|
fuse.fuse_python_api = (0, 2)
class ImageException(Exception):
pass
class FuseArgs(fuse.FuseArgs):
def __init__(self):
fuse.FuseArgs.__init__(self)
self.update_file = None
def __str__(self):
return (
"\n".join(
[
f"< {self.update_file} on {self.mountpoint}:",
f" {self.modifiers}",
" -o ",
]
)
+ ",\n ".join(self._str_core())
+ " >"
)
class FuseOptParse(fuse.FuseOptParse):
def __init__(self, *args, **kw):
fuse.FuseOptParse.__init__(self, *args, **kw)
def parse_args(self, args=None, values=None):
_opts, _args = fuse.FuseOptParse.parse_args(self, args, values)
if _args:
self.fuse_args.update_file = os.path.realpath(_args.pop())
return _opts, _args
class Stat(fuse.Stat):
def __init__(self):
self.st_mode = 0
self.st_ino = 0
self.st_dev = 0
self.st_nlink = 0
self.st_uid = 0
self.st_gid = 0
self.st_size = 0
self.st_atime = 0
self.st_mtime = 0
self.st_ctime = 0
class UpdateFS(fuse.Fuse):
version = "%prog " + fuse.__version__
fusage = "%prog update_file mountpoint [options]"
dash_s_do = "setsingle"
disable_path_cache = False
cache_debug = False
cache_size = 500
cache_ttl = 60
image = None
volume = None
inode_cache = {}
queue = None
exit_threads = False
def __init__(self, *args, **kw):
fuse.Fuse.__init__(
self,
*args,
fuse_args=FuseArgs(),
parser_class=FuseOptParse,
**kw,
)
self.parser.add_option(
mountopt="disable_path_cache",
action="store_true",
help="Disable path caching",
)
self.parser.add_option(
mountopt="cache_debug",
action="store_true",
help="Debug output for path caching",
)
self.parser.add_option(
mountopt="cache_size",
default=500,
type="int",
help="Size in MB of memory cache for speeding up filesytem access [default: %default]",
)
self.parser.add_option(
mountopt="cache_ttl",
default=60,
type="int",
help="Seconds before the memory cache will evict unused chunks [default: %default]",
)
@property
def update_file(self):
return self.fuse_args.update_file
@property
def mountpoint(self):
return self.fuse_args.mountpoint
def fuse_error(self, msg):
print(msg, file=sys.stderr)
self.fuse_args.setmod("showhelp")
fuse.Fuse.main(self, self.args)
sys.exit(1)
def main(self, args=None):
self.args = args
if self.fuse_args.getmod("showhelp"):
fuse.Fuse.main(self, args)
return
if self.update_file is None:
self.fuse_error("fuse: missing update_file parameter")
if not os.path.exists(self.update_file):
self.fuse_error(f"fuse: File does not exist {self.update_file}")
self.image = UpdateImage(
self.update_file,
cache_size=self.cache_size,
cache_ttl=self.cache_ttl,
)
self.volume = ext4.Volume(self.image, offset=0)
print("Verifying signature...")
try:
self.image.verify(
self.get_inode("/usr/share/update_engine/update-payload-key.pub.pem")
.open()
.read()
)
print("Signature verified") | except UpdateImageSignatureException: | 1 | 2023-12-28 06:13:21+00:00 | 4k |
run-llama/rags | core/param_cache.py | [
{
"identifier": "load_data",
"path": "core/utils.py",
"snippet": "def load_data(\n file_names: Optional[List[str]] = None,\n directory: Optional[str] = None,\n urls: Optional[List[str]] = None,\n) -> List[Document]:\n \"\"\"Load data.\"\"\"\n file_names = file_names or []\n directory =... | from pydantic import BaseModel, Field
from llama_index import (
VectorStoreIndex,
StorageContext,
load_index_from_storage,
)
from typing import List, cast, Optional
from llama_index.chat_engine.types import BaseChatEngine
from pathlib import Path
from core.utils import (
load_data,
get_tool_objects,
construct_agent,
RAGParams,
construct_mm_agent,
)
from llama_index.indices.multi_modal.base import MultiModalVectorStoreIndex
import json
import uuid | 2,616 | """Param cache."""
class ParamCache(BaseModel):
"""Cache for RAG agent builder.
Created a wrapper class around a dict in case we wanted to more explicitly
type different items in the cache.
"""
# arbitrary types
class Config:
arbitrary_types_allowed = True
# system prompt
system_prompt: Optional[str] = Field(
default=None, description="System prompt for RAG agent."
)
# data
file_names: List[str] = Field(
default_factory=list, description="File names as data source (if specified)"
)
urls: List[str] = Field(
default_factory=list, description="URLs as data source (if specified)"
)
directory: Optional[str] = Field(
default=None, description="Directory as data source (if specified)"
)
docs: List = Field(default_factory=list, description="Documents for RAG agent.")
# tools
tools: List = Field(
default_factory=list, description="Additional tools for RAG agent (e.g. web)"
)
# RAG params
rag_params: RAGParams = Field(
default_factory=RAGParams, description="RAG parameters for RAG agent."
)
# agent params
builder_type: str = Field(
default="default", description="Builder type (default, multimodal)."
)
vector_index: Optional[VectorStoreIndex] = Field(
default=None, description="Vector index for RAG agent."
)
agent_id: str = Field(
default_factory=lambda: f"Agent_{str(uuid.uuid4())}",
description="Agent ID for RAG agent.",
)
agent: Optional[BaseChatEngine] = Field(default=None, description="RAG agent.")
def save_to_disk(self, save_dir: str) -> None:
"""Save cache to disk."""
# NOTE: more complex than just calling dict() because we want to
# only store serializable fields and be space-efficient
dict_to_serialize = {
"system_prompt": self.system_prompt,
"file_names": self.file_names,
"urls": self.urls,
"directory": self.directory,
# TODO: figure out tools
"tools": self.tools,
"rag_params": self.rag_params.dict(),
"builder_type": self.builder_type,
"agent_id": self.agent_id,
}
# store the vector store within the agent
if self.vector_index is None:
raise ValueError("Must specify vector index in order to save.")
self.vector_index.storage_context.persist(Path(save_dir) / "storage")
# if save_path directories don't exist, create it
if not Path(save_dir).exists():
Path(save_dir).mkdir(parents=True)
with open(Path(save_dir) / "cache.json", "w") as f:
json.dump(dict_to_serialize, f)
@classmethod
def load_from_disk(
cls,
save_dir: str,
) -> "ParamCache":
"""Load cache from disk."""
with open(Path(save_dir) / "cache.json", "r") as f:
cache_dict = json.load(f)
storage_context = StorageContext.from_defaults(
persist_dir=str(Path(save_dir) / "storage")
)
if cache_dict["builder_type"] == "multimodal":
vector_index: VectorStoreIndex = cast(
MultiModalVectorStoreIndex, load_index_from_storage(storage_context)
)
else:
vector_index = cast(
VectorStoreIndex, load_index_from_storage(storage_context)
)
# replace rag params with RAGParams object
cache_dict["rag_params"] = RAGParams(**cache_dict["rag_params"])
# add in the missing fields
# load docs
cache_dict["docs"] = load_data(
file_names=cache_dict["file_names"],
urls=cache_dict["urls"],
directory=cache_dict["directory"],
)
# load agent from index
| """Param cache."""
class ParamCache(BaseModel):
"""Cache for RAG agent builder.
Created a wrapper class around a dict in case we wanted to more explicitly
type different items in the cache.
"""
# arbitrary types
class Config:
arbitrary_types_allowed = True
# system prompt
system_prompt: Optional[str] = Field(
default=None, description="System prompt for RAG agent."
)
# data
file_names: List[str] = Field(
default_factory=list, description="File names as data source (if specified)"
)
urls: List[str] = Field(
default_factory=list, description="URLs as data source (if specified)"
)
directory: Optional[str] = Field(
default=None, description="Directory as data source (if specified)"
)
docs: List = Field(default_factory=list, description="Documents for RAG agent.")
# tools
tools: List = Field(
default_factory=list, description="Additional tools for RAG agent (e.g. web)"
)
# RAG params
rag_params: RAGParams = Field(
default_factory=RAGParams, description="RAG parameters for RAG agent."
)
# agent params
builder_type: str = Field(
default="default", description="Builder type (default, multimodal)."
)
vector_index: Optional[VectorStoreIndex] = Field(
default=None, description="Vector index for RAG agent."
)
agent_id: str = Field(
default_factory=lambda: f"Agent_{str(uuid.uuid4())}",
description="Agent ID for RAG agent.",
)
agent: Optional[BaseChatEngine] = Field(default=None, description="RAG agent.")
def save_to_disk(self, save_dir: str) -> None:
"""Save cache to disk."""
# NOTE: more complex than just calling dict() because we want to
# only store serializable fields and be space-efficient
dict_to_serialize = {
"system_prompt": self.system_prompt,
"file_names": self.file_names,
"urls": self.urls,
"directory": self.directory,
# TODO: figure out tools
"tools": self.tools,
"rag_params": self.rag_params.dict(),
"builder_type": self.builder_type,
"agent_id": self.agent_id,
}
# store the vector store within the agent
if self.vector_index is None:
raise ValueError("Must specify vector index in order to save.")
self.vector_index.storage_context.persist(Path(save_dir) / "storage")
# if save_path directories don't exist, create it
if not Path(save_dir).exists():
Path(save_dir).mkdir(parents=True)
with open(Path(save_dir) / "cache.json", "w") as f:
json.dump(dict_to_serialize, f)
@classmethod
def load_from_disk(
cls,
save_dir: str,
) -> "ParamCache":
"""Load cache from disk."""
with open(Path(save_dir) / "cache.json", "r") as f:
cache_dict = json.load(f)
storage_context = StorageContext.from_defaults(
persist_dir=str(Path(save_dir) / "storage")
)
if cache_dict["builder_type"] == "multimodal":
vector_index: VectorStoreIndex = cast(
MultiModalVectorStoreIndex, load_index_from_storage(storage_context)
)
else:
vector_index = cast(
VectorStoreIndex, load_index_from_storage(storage_context)
)
# replace rag params with RAGParams object
cache_dict["rag_params"] = RAGParams(**cache_dict["rag_params"])
# add in the missing fields
# load docs
cache_dict["docs"] = load_data(
file_names=cache_dict["file_names"],
urls=cache_dict["urls"],
directory=cache_dict["directory"],
)
# load agent from index | additional_tools = get_tool_objects(cache_dict["tools"]) | 1 | 2023-11-16 07:49:44+00:00 | 4k |
open-mmlab/Amphion | models/tts/naturalspeech2/prior_encoder.py | [
{
"identifier": "TransformerEncoder",
"path": "modules/naturalpseech2/transformers.py",
"snippet": "class TransformerEncoder(nn.Module):\n def __init__(\n self,\n enc_emb_tokens=None,\n encoder_layer=None,\n encoder_hidden=None,\n encoder_head=None,\n conv_fi... | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from modules.naturalpseech2.transformers import (
TransformerEncoder,
DurationPredictor,
PitchPredictor,
LengthRegulator,
) | 3,057 | # 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 PriorEncoder(nn.Module):
def __init__(self, cfg):
super().__init__()
self.cfg = cfg
self.enc_emb_tokens = nn.Embedding(
cfg.vocab_size, cfg.encoder.encoder_hidden, padding_idx=0
)
self.enc_emb_tokens.weight.data.normal_(mean=0.0, std=1e-5)
self.encoder = TransformerEncoder(
enc_emb_tokens=self.enc_emb_tokens, cfg=cfg.encoder
)
self.duration_predictor = DurationPredictor(cfg.duration_predictor)
| # 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 PriorEncoder(nn.Module):
def __init__(self, cfg):
super().__init__()
self.cfg = cfg
self.enc_emb_tokens = nn.Embedding(
cfg.vocab_size, cfg.encoder.encoder_hidden, padding_idx=0
)
self.enc_emb_tokens.weight.data.normal_(mean=0.0, std=1e-5)
self.encoder = TransformerEncoder(
enc_emb_tokens=self.enc_emb_tokens, cfg=cfg.encoder
)
self.duration_predictor = DurationPredictor(cfg.duration_predictor) | self.pitch_predictor = PitchPredictor(cfg.pitch_predictor) | 2 | 2023-11-15 09:19:27+00:00 | 4k |
KwaiKEG/KwaiAgents | kwaiagents/agents/prompts.py | [
{
"identifier": "get_current_time_and_date",
"path": "kwaiagents/utils/date_utils.py",
"snippet": "def get_current_time_and_date(lang=\"en\"):\n solar = Solar.fromDate(datetime.now())\n lunar = solar.getLunar()\n if lang == \"zh\":\n rst = f'''\n当前阳历日期和时间: {str(datetime.now())}\n当前星期: 星期... | import json
from kwaiagents.utils.date_utils import get_current_time_and_date
from kwaiagents.utils.function_utils import transform_to_openai_function | 1,925 | planning_prompt_template = """
你是{agent_name},{agent_bio}
{agent_instructions}
当前阶段是任务规划阶段,你将给定目标或问题,你的决策将独立执行而不依赖于人类的帮助,请发挥LLM的优势并且追求高效的策略进行任务规划。
1.你有~4000字的短期记忆
2.不需要用户的帮助
3.规划的时候可以用参考工具中提到的工具
4.互联网搜索、信息聚合和鉴别真伪的能力
5.保持谦逊,对自己没把握的问题,尽可能调用command,但尽量少调用,不能重复调用
6.当你从自身知识或者历史记忆中能得出结论,请聪明且高效,完成任务并得出结论
7.经常建设性地自我批评整个行为大局,反思过去的决策和策略,以改进你的方法
8.你最多只能进行{max_iter_num}步思考,规划{max_iter_num}个任务,所以尽可能高效规划任务
9.你有反思能力,如果已完成的任务和结果暂不能得到回答问题所需信息或尚不能完成目标,应继续规划,但不能跟之前任务重复
{tool_specification}
{current_date_and_time}
{memory}
GOAL:{goal}
\n根据目标和已有任务,规划一个新Task(不能重复),你只能以以下json列表的格式生成Task
{{
"task_name": "任务描述",
"command":{{
"name":"command name",
"args":{{
"arg name":"value"
}}
}}
}}
确保Task可以被Python的json.loads解析
当已完成的Tasks已经能够帮助回答这个目标,则尽可能生成任务完成Task,否则生成一个其他Task。一个新Task:
""".strip()
planning_prompt_template_en = """
You are a {agent_name},{agent_bio}
{agent_instructions}
Currently, you are in the task planning phase, where you will be given specific goals or problems to address. \
Your decisions will be executed independently without relying on human assistance. \
Please utilize LLM's advantages and pursue efficient strategies for task planning.\
1. You have a short-term memory of approximately 4,000 characters.
2. You do not require assistance from users.
3. You can use the reference tools mentioned when planning.
4. You have the abilities to perform internet searches, aggregate information, and discern between genuine and fake information.
5. Remain humble and, if unsure about an issue, make use of commands when possible but minimize their usage and avoid repetition.
6. When drawing conclusions from your knowledge or historical memory, be clever and efficient in task completion and conclusion.
7. Regularly engage in constructive self-criticism to reflect on past decisions and strategies and improve your approach.
8. You can think and plan up to {max_iter_num} steps, so strive to plan tasks as efficiently as possible.
9. You have the capability for reflection; if a completed task and its results cannot provide the necessary information to answer a question or achieve a goal, continue planning but avoid repeating previous tasks.
{tool_specification}
{current_date_and_time}
{memory}
GOAL:{goal}
\nBased on the goal and existing tasks, plan a new Task (no repetitions), and you can only generate the Task in the following json list format:
{{
"task_name": "task description",
"command":{{
"name":"command name",
"args":{{
"arg name":"value"
}}
}}
}}
Ensure that the Task can be parsed by Python's json.loads function.
If the already completed Tasks are sufficient to answer the goal, then try to generate the Task to complete it as much as possible. Otherwise, create another Task.
A new Task:
""".strip()
conclusion_prompt_template = """
你是{agent_name},{agent_bio},{agent_instructions}
当前阶段是总结阶段,在前几次交互中,对于用户给定的目标和问题,你已经通过自己搜寻出了一定信息,你需要整合这些信息用中文给出最终的结论。
1. 搜寻的信息从很多工具中获取,会出现冗余
2. 当不同工具获取的信息冲突的时候,你应该遵循一定的优先级(Wiki > search)去解决冲突
{current_date_and_time}
{memory}
问题或目标:{goal}\n生成对用户有帮助的中文回答:
"""
conclusion_prompt_template_en = """
You are a {agent_name},{agent_bio},{agent_instructions}
The current stage is the concluding stage. In the previous interactions, \
you have already found some information by searching on your own for the user's given goals and problems. \
You need to integrate this information and provide the final conclusion in Chinese.
If there is information from Knowledge info, and the information can answer the question, \
you can use the Knowledge info information as much as possible to answer the question without using external tool results or creating your own content.
1. The information you search for comes from many sources and may be redundant.
2. When the information obtained from different tools conflicts, you should follow a certain priority (Knowledge info > Wiki > search) to resolve the conflict.
{current_date_and_time}
{memory}
Goal: {goal}
Generate helpful answers **in English** for users:
"""
def make_planning_prompt(agent_profile, goal, used_tools, memory, max_tokens_num, tokenizer, lang="en"):
tool_spec = make_tool_specification(used_tools, lang)
template = planning_prompt_template if lang == "zh" else planning_prompt_template_en
prompt = template.format(**{
"agent_name": agent_profile.name,
"agent_bio": agent_profile.bio,
"agent_instructions": agent_profile.instructions,
"max_iter_num": agent_profile.max_iter_num,
"tool_specification": tool_spec,
|
planning_prompt_template = """
你是{agent_name},{agent_bio}
{agent_instructions}
当前阶段是任务规划阶段,你将给定目标或问题,你的决策将独立执行而不依赖于人类的帮助,请发挥LLM的优势并且追求高效的策略进行任务规划。
1.你有~4000字的短期记忆
2.不需要用户的帮助
3.规划的时候可以用参考工具中提到的工具
4.互联网搜索、信息聚合和鉴别真伪的能力
5.保持谦逊,对自己没把握的问题,尽可能调用command,但尽量少调用,不能重复调用
6.当你从自身知识或者历史记忆中能得出结论,请聪明且高效,完成任务并得出结论
7.经常建设性地自我批评整个行为大局,反思过去的决策和策略,以改进你的方法
8.你最多只能进行{max_iter_num}步思考,规划{max_iter_num}个任务,所以尽可能高效规划任务
9.你有反思能力,如果已完成的任务和结果暂不能得到回答问题所需信息或尚不能完成目标,应继续规划,但不能跟之前任务重复
{tool_specification}
{current_date_and_time}
{memory}
GOAL:{goal}
\n根据目标和已有任务,规划一个新Task(不能重复),你只能以以下json列表的格式生成Task
{{
"task_name": "任务描述",
"command":{{
"name":"command name",
"args":{{
"arg name":"value"
}}
}}
}}
确保Task可以被Python的json.loads解析
当已完成的Tasks已经能够帮助回答这个目标,则尽可能生成任务完成Task,否则生成一个其他Task。一个新Task:
""".strip()
planning_prompt_template_en = """
You are a {agent_name},{agent_bio}
{agent_instructions}
Currently, you are in the task planning phase, where you will be given specific goals or problems to address. \
Your decisions will be executed independently without relying on human assistance. \
Please utilize LLM's advantages and pursue efficient strategies for task planning.\
1. You have a short-term memory of approximately 4,000 characters.
2. You do not require assistance from users.
3. You can use the reference tools mentioned when planning.
4. You have the abilities to perform internet searches, aggregate information, and discern between genuine and fake information.
5. Remain humble and, if unsure about an issue, make use of commands when possible but minimize their usage and avoid repetition.
6. When drawing conclusions from your knowledge or historical memory, be clever and efficient in task completion and conclusion.
7. Regularly engage in constructive self-criticism to reflect on past decisions and strategies and improve your approach.
8. You can think and plan up to {max_iter_num} steps, so strive to plan tasks as efficiently as possible.
9. You have the capability for reflection; if a completed task and its results cannot provide the necessary information to answer a question or achieve a goal, continue planning but avoid repeating previous tasks.
{tool_specification}
{current_date_and_time}
{memory}
GOAL:{goal}
\nBased on the goal and existing tasks, plan a new Task (no repetitions), and you can only generate the Task in the following json list format:
{{
"task_name": "task description",
"command":{{
"name":"command name",
"args":{{
"arg name":"value"
}}
}}
}}
Ensure that the Task can be parsed by Python's json.loads function.
If the already completed Tasks are sufficient to answer the goal, then try to generate the Task to complete it as much as possible. Otherwise, create another Task.
A new Task:
""".strip()
conclusion_prompt_template = """
你是{agent_name},{agent_bio},{agent_instructions}
当前阶段是总结阶段,在前几次交互中,对于用户给定的目标和问题,你已经通过自己搜寻出了一定信息,你需要整合这些信息用中文给出最终的结论。
1. 搜寻的信息从很多工具中获取,会出现冗余
2. 当不同工具获取的信息冲突的时候,你应该遵循一定的优先级(Wiki > search)去解决冲突
{current_date_and_time}
{memory}
问题或目标:{goal}\n生成对用户有帮助的中文回答:
"""
conclusion_prompt_template_en = """
You are a {agent_name},{agent_bio},{agent_instructions}
The current stage is the concluding stage. In the previous interactions, \
you have already found some information by searching on your own for the user's given goals and problems. \
You need to integrate this information and provide the final conclusion in Chinese.
If there is information from Knowledge info, and the information can answer the question, \
you can use the Knowledge info information as much as possible to answer the question without using external tool results or creating your own content.
1. The information you search for comes from many sources and may be redundant.
2. When the information obtained from different tools conflicts, you should follow a certain priority (Knowledge info > Wiki > search) to resolve the conflict.
{current_date_and_time}
{memory}
Goal: {goal}
Generate helpful answers **in English** for users:
"""
def make_planning_prompt(agent_profile, goal, used_tools, memory, max_tokens_num, tokenizer, lang="en"):
tool_spec = make_tool_specification(used_tools, lang)
template = planning_prompt_template if lang == "zh" else planning_prompt_template_en
prompt = template.format(**{
"agent_name": agent_profile.name,
"agent_bio": agent_profile.bio,
"agent_instructions": agent_profile.instructions,
"max_iter_num": agent_profile.max_iter_num,
"tool_specification": tool_spec, | "current_date_and_time": get_current_time_and_date(lang), | 0 | 2023-11-13 03:37:02+00:00 | 4k |
EnVision-Research/LucidDreamer | scene/gaussian_model.py | [
{
"identifier": "inverse_sigmoid",
"path": "utils/general_utils.py",
"snippet": "def inverse_sigmoid(x):\n return torch.log(x/(1-x))"
},
{
"identifier": "get_expon_lr_func",
"path": "utils/general_utils.py",
"snippet": "def get_expon_lr_func(\n lr_init, lr_final, lr_delay_steps=0, ... | import torch
import numpy as np
import os
from utils.general_utils import inverse_sigmoid, get_expon_lr_func, build_rotation
from torch import nn
from utils.system_utils import mkdir_p
from plyfile import PlyData, PlyElement
from utils.sh_utils import RGB2SH,SH2RGB
from simple_knn._C import distCUDA2
from utils.graphics_utils import BasicPointCloud
from utils.general_utils import strip_symmetric, build_scaling_rotation | 3,525 |
print("Number of points at initialisation : ", fused_point_cloud.shape[0])
dist2 = torch.clamp_min(distCUDA2(torch.from_numpy(np.asarray(pcd.points)).float().cuda()), 0.0000001)
scales = torch.log(torch.sqrt(dist2))[...,None].repeat(1, 3)
rots = torch.zeros((fused_point_cloud.shape[0], 4), device="cuda")
rots[:, 0] = 1
opacities = inverse_sigmoid(0.1 * torch.ones((fused_point_cloud.shape[0], 1), dtype=torch.float, device="cuda"))
self._xyz = nn.Parameter(fused_point_cloud.requires_grad_(True))
self._features_dc = nn.Parameter(features[:,:,0:1].transpose(1, 2).contiguous().requires_grad_(True))
self._features_rest = nn.Parameter(features[:,:,1:].transpose(1, 2).contiguous().requires_grad_(True))
self._scaling = nn.Parameter(scales.requires_grad_(True))
self._rotation = nn.Parameter(rots.requires_grad_(True))
self._opacity = nn.Parameter(opacities.requires_grad_(True))
self._background = nn.Parameter(torch.zeros((3,1,1), device="cuda").requires_grad_(True))
self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device="cuda")
def training_setup(self, training_args):
self.percent_dense = training_args.percent_dense
self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
self.denom = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
l = [
{'params': [self._xyz], 'lr': training_args.position_lr_init * self.spatial_lr_scale, "name": "xyz"},
{'params': [self._features_dc], 'lr': training_args.feature_lr, "name": "f_dc"},
{'params': [self._features_rest], 'lr': training_args.feature_lr / 20.0, "name": "f_rest"},
{'params': [self._opacity], 'lr': training_args.opacity_lr, "name": "opacity"},
{'params': [self._scaling], 'lr': training_args.scaling_lr, "name": "scaling"},
{'params': [self._rotation], 'lr': training_args.rotation_lr, "name": "rotation"},
{'params': [self._background], 'lr': training_args.feature_lr, "name": "background"},
]
self.optimizer = torch.optim.Adam(l, lr=0.0, eps=1e-15)
self.xyz_scheduler_args = get_expon_lr_func(lr_init=training_args.position_lr_init*self.spatial_lr_scale,
lr_final=training_args.position_lr_final*self.spatial_lr_scale,
lr_delay_mult=training_args.position_lr_delay_mult,
max_steps=training_args.iterations)
self.rotation_scheduler_args = get_expon_lr_func(lr_init=training_args.rotation_lr,
lr_final=training_args.rotation_lr_final,
lr_delay_mult=training_args.position_lr_delay_mult,
max_steps=training_args.iterations)
self.scaling_scheduler_args = get_expon_lr_func(lr_init=training_args.scaling_lr,
lr_final=training_args.scaling_lr_final,
lr_delay_mult=training_args.position_lr_delay_mult,
max_steps=training_args.iterations)
self.feature_scheduler_args = get_expon_lr_func(lr_init=training_args.feature_lr,
lr_final=training_args.feature_lr_final,
lr_delay_mult=training_args.position_lr_delay_mult,
max_steps=training_args.iterations)
def update_learning_rate(self, iteration):
''' Learning rate scheduling per step '''
for param_group in self.optimizer.param_groups:
if param_group["name"] == "xyz":
lr = self.xyz_scheduler_args(iteration)
param_group['lr'] = lr
return lr
def update_feature_learning_rate(self, iteration):
''' Learning rate scheduling per step '''
for param_group in self.optimizer.param_groups:
if param_group["name"] == "f_dc":
lr = self.feature_scheduler_args(iteration)
param_group['lr'] = lr
return lr
def update_rotation_learning_rate(self, iteration):
''' Learning rate scheduling per step '''
for param_group in self.optimizer.param_groups:
if param_group["name"] == "rotation":
lr = self.rotation_scheduler_args(iteration)
param_group['lr'] = lr
return lr
def update_scaling_learning_rate(self, iteration):
''' Learning rate scheduling per step '''
for param_group in self.optimizer.param_groups:
if param_group["name"] == "scaling":
lr = self.scaling_scheduler_args(iteration)
param_group['lr'] = lr
return lr
def construct_list_of_attributes(self):
l = ['x', 'y', 'z', 'nx', 'ny', 'nz']
# All channels except the 3 DC
for i in range(self._features_dc.shape[1]*self._features_dc.shape[2]):
l.append('f_dc_{}'.format(i))
for i in range(self._features_rest.shape[1]*self._features_rest.shape[2]):
l.append('f_rest_{}'.format(i))
l.append('opacity')
for i in range(self._scaling.shape[1]):
l.append('scale_{}'.format(i))
for i in range(self._rotation.shape[1]):
l.append('rot_{}'.format(i))
return l
def save_ply(self, path):
mkdir_p(os.path.dirname(path))
xyz = self._xyz.detach().cpu().numpy()
normals = np.zeros_like(xyz)
f_dc = self._features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()
f_rest = self._features_rest.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()
opacities = self._opacity.detach().cpu().numpy()
scale = self._scaling.detach().cpu().numpy()
rotation = self._rotation.detach().cpu().numpy()
dtype_full = [(attribute, 'f4') for attribute in self.construct_list_of_attributes()]
elements = np.empty(xyz.shape[0], dtype=dtype_full)
attributes = np.concatenate((xyz, normals, f_dc, f_rest, opacities, scale, rotation), axis=1)
elements[:] = list(map(tuple, attributes))
el = PlyElement.describe(elements, 'vertex')
PlyData([el]).write(path)
| #
# Copyright (C) 2023, Inria
# GRAPHDECO research group, https://team.inria.fr/graphdeco
# All rights reserved.
#
# This software is free for non-commercial, research and evaluation use
# under the terms of the LICENSE.md file.
#
# For inquiries contact george.drettakis@inria.fr
#
# from .resnet import *
class GaussianModel:
def setup_functions(self):
def build_covariance_from_scaling_rotation(scaling, scaling_modifier, rotation):
L = build_scaling_rotation(scaling_modifier * scaling, rotation)
actual_covariance = L @ L.transpose(1, 2)
symm = strip_symmetric(actual_covariance)
return symm
self.scaling_activation = torch.exp
self.scaling_inverse_activation = torch.log
self.covariance_activation = build_covariance_from_scaling_rotation
self.opacity_activation = torch.sigmoid
self.inverse_opacity_activation = inverse_sigmoid
self.rotation_activation = torch.nn.functional.normalize
def __init__(self, sh_degree : int):
self.active_sh_degree = 0
self.max_sh_degree = sh_degree
self._xyz = torch.empty(0)
self._features_dc = torch.empty(0)
self._features_rest = torch.empty(0)
self._scaling = torch.empty(0)
self._rotation = torch.empty(0)
self._opacity = torch.empty(0)
self._background = torch.empty(0)
self.max_radii2D = torch.empty(0)
self.xyz_gradient_accum = torch.empty(0)
self.denom = torch.empty(0)
self.optimizer = None
self.percent_dense = 0
self.spatial_lr_scale = 0
self.setup_functions()
def capture(self):
return (
self.active_sh_degree,
self._xyz,
self._features_dc,
self._features_rest,
self._scaling,
self._rotation,
self._opacity,
self.max_radii2D,
self.xyz_gradient_accum,
self.denom,
self.optimizer.state_dict(),
self.spatial_lr_scale,
)
def restore(self, model_args, training_args):
(self.active_sh_degree,
self._xyz,
self._features_dc,
self._features_rest,
self._scaling,
self._rotation,
self._opacity,
self.max_radii2D,
xyz_gradient_accum,
denom,
opt_dict,
self.spatial_lr_scale) = model_args
self.training_setup(training_args)
self.xyz_gradient_accum = xyz_gradient_accum
self.denom = denom
self.optimizer.load_state_dict(opt_dict)
@property
def get_scaling(self):
return self.scaling_activation(self._scaling)
@property
def get_rotation(self):
return self.rotation_activation(self._rotation)
@property
def get_xyz(self):
return self._xyz
@property
def get_background(self):
return torch.sigmoid(self._background)
@property
def get_features(self):
features_dc = self._features_dc
features_rest = self._features_rest
return torch.cat((features_dc, features_rest), dim=1)
@property
def get_opacity(self):
return self.opacity_activation(self._opacity)
def get_covariance(self, scaling_modifier = 1):
return self.covariance_activation(self.get_scaling, scaling_modifier, self._rotation)
def oneupSHdegree(self):
if self.active_sh_degree < self.max_sh_degree:
self.active_sh_degree += 1
def create_from_pcd(self, pcd : BasicPointCloud, spatial_lr_scale : float):
self.spatial_lr_scale = spatial_lr_scale
fused_point_cloud = torch.tensor(np.asarray(pcd.points)).float().cuda()
fused_color = RGB2SH(torch.tensor(np.asarray(pcd.colors))).float().cuda() #RGB2SH(
features = torch.zeros((fused_color.shape[0], 3, (self.max_sh_degree + 1) ** 2)).float().cuda()
features[:, :3, 0 ] = fused_color
features[:, 3:, 1:] = 0.0
print("Number of points at initialisation : ", fused_point_cloud.shape[0])
dist2 = torch.clamp_min(distCUDA2(torch.from_numpy(np.asarray(pcd.points)).float().cuda()), 0.0000001)
scales = torch.log(torch.sqrt(dist2))[...,None].repeat(1, 3)
rots = torch.zeros((fused_point_cloud.shape[0], 4), device="cuda")
rots[:, 0] = 1
opacities = inverse_sigmoid(0.1 * torch.ones((fused_point_cloud.shape[0], 1), dtype=torch.float, device="cuda"))
self._xyz = nn.Parameter(fused_point_cloud.requires_grad_(True))
self._features_dc = nn.Parameter(features[:,:,0:1].transpose(1, 2).contiguous().requires_grad_(True))
self._features_rest = nn.Parameter(features[:,:,1:].transpose(1, 2).contiguous().requires_grad_(True))
self._scaling = nn.Parameter(scales.requires_grad_(True))
self._rotation = nn.Parameter(rots.requires_grad_(True))
self._opacity = nn.Parameter(opacities.requires_grad_(True))
self._background = nn.Parameter(torch.zeros((3,1,1), device="cuda").requires_grad_(True))
self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device="cuda")
def training_setup(self, training_args):
self.percent_dense = training_args.percent_dense
self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
self.denom = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
l = [
{'params': [self._xyz], 'lr': training_args.position_lr_init * self.spatial_lr_scale, "name": "xyz"},
{'params': [self._features_dc], 'lr': training_args.feature_lr, "name": "f_dc"},
{'params': [self._features_rest], 'lr': training_args.feature_lr / 20.0, "name": "f_rest"},
{'params': [self._opacity], 'lr': training_args.opacity_lr, "name": "opacity"},
{'params': [self._scaling], 'lr': training_args.scaling_lr, "name": "scaling"},
{'params': [self._rotation], 'lr': training_args.rotation_lr, "name": "rotation"},
{'params': [self._background], 'lr': training_args.feature_lr, "name": "background"},
]
self.optimizer = torch.optim.Adam(l, lr=0.0, eps=1e-15)
self.xyz_scheduler_args = get_expon_lr_func(lr_init=training_args.position_lr_init*self.spatial_lr_scale,
lr_final=training_args.position_lr_final*self.spatial_lr_scale,
lr_delay_mult=training_args.position_lr_delay_mult,
max_steps=training_args.iterations)
self.rotation_scheduler_args = get_expon_lr_func(lr_init=training_args.rotation_lr,
lr_final=training_args.rotation_lr_final,
lr_delay_mult=training_args.position_lr_delay_mult,
max_steps=training_args.iterations)
self.scaling_scheduler_args = get_expon_lr_func(lr_init=training_args.scaling_lr,
lr_final=training_args.scaling_lr_final,
lr_delay_mult=training_args.position_lr_delay_mult,
max_steps=training_args.iterations)
self.feature_scheduler_args = get_expon_lr_func(lr_init=training_args.feature_lr,
lr_final=training_args.feature_lr_final,
lr_delay_mult=training_args.position_lr_delay_mult,
max_steps=training_args.iterations)
def update_learning_rate(self, iteration):
''' Learning rate scheduling per step '''
for param_group in self.optimizer.param_groups:
if param_group["name"] == "xyz":
lr = self.xyz_scheduler_args(iteration)
param_group['lr'] = lr
return lr
def update_feature_learning_rate(self, iteration):
''' Learning rate scheduling per step '''
for param_group in self.optimizer.param_groups:
if param_group["name"] == "f_dc":
lr = self.feature_scheduler_args(iteration)
param_group['lr'] = lr
return lr
def update_rotation_learning_rate(self, iteration):
''' Learning rate scheduling per step '''
for param_group in self.optimizer.param_groups:
if param_group["name"] == "rotation":
lr = self.rotation_scheduler_args(iteration)
param_group['lr'] = lr
return lr
def update_scaling_learning_rate(self, iteration):
''' Learning rate scheduling per step '''
for param_group in self.optimizer.param_groups:
if param_group["name"] == "scaling":
lr = self.scaling_scheduler_args(iteration)
param_group['lr'] = lr
return lr
def construct_list_of_attributes(self):
l = ['x', 'y', 'z', 'nx', 'ny', 'nz']
# All channels except the 3 DC
for i in range(self._features_dc.shape[1]*self._features_dc.shape[2]):
l.append('f_dc_{}'.format(i))
for i in range(self._features_rest.shape[1]*self._features_rest.shape[2]):
l.append('f_rest_{}'.format(i))
l.append('opacity')
for i in range(self._scaling.shape[1]):
l.append('scale_{}'.format(i))
for i in range(self._rotation.shape[1]):
l.append('rot_{}'.format(i))
return l
def save_ply(self, path):
mkdir_p(os.path.dirname(path))
xyz = self._xyz.detach().cpu().numpy()
normals = np.zeros_like(xyz)
f_dc = self._features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()
f_rest = self._features_rest.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()
opacities = self._opacity.detach().cpu().numpy()
scale = self._scaling.detach().cpu().numpy()
rotation = self._rotation.detach().cpu().numpy()
dtype_full = [(attribute, 'f4') for attribute in self.construct_list_of_attributes()]
elements = np.empty(xyz.shape[0], dtype=dtype_full)
attributes = np.concatenate((xyz, normals, f_dc, f_rest, opacities, scale, rotation), axis=1)
elements[:] = list(map(tuple, attributes))
el = PlyElement.describe(elements, 'vertex')
PlyData([el]).write(path) | np.savetxt(os.path.join(os.path.split(path)[0],"point_cloud_rgb.txt"),np.concatenate((xyz, SH2RGB(f_dc)), axis=1)) | 5 | 2023-11-18 08:05:50+00:00 | 4k |
VRSEN/agency-swarm | agency_swarm/tools/browsing/SelectDropdown.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 json
from pydantic import Field
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from agency_swarm.tools import BaseTool
from agency_swarm.tools.browsing.util import get_b64_screenshot
from agency_swarm.tools.browsing.util import get_web_driver, set_web_driver
from agency_swarm.tools.browsing.util.highlights import highlight_elements_with_labels
from agency_swarm.util import get_openai_client | 2,335 |
class SelectDropdown(BaseTool):
"""
This tool selects an option in a dropdown on the current web page based on the description of that element and which option to select.
"""
description: str = Field(
..., description="Description of which option to select and for which dropdown on the page, clearly stated in natural langauge.",
examples=["Select Germany option in the 'Country' dropdown."]
)
def run(self):
wd = get_web_driver()
client = get_openai_client()
wd = highlight_elements_with_labels(wd, 'select')
|
class SelectDropdown(BaseTool):
"""
This tool selects an option in a dropdown on the current web page based on the description of that element and which option to select.
"""
description: str = Field(
..., description="Description of which option to select and for which dropdown on the page, clearly stated in natural langauge.",
examples=["Select Germany option in the 'Country' dropdown."]
)
def run(self):
wd = get_web_driver()
client = get_openai_client()
wd = highlight_elements_with_labels(wd, 'select')
| screenshot = get_b64_screenshot(wd) | 1 | 2023-11-16 02:29:26+00:00 | 4k |
resemble-ai/resemble-enhance | resemble_enhance/enhancer/lcfm/lcfm.py | [
{
"identifier": "CFM",
"path": "resemble_enhance/enhancer/lcfm/cfm.py",
"snippet": "class CFM(nn.Module):\n \"\"\"\n This mixin is for general diffusion models.\n\n ψ0 stands for the gaussian noise, and ψ1 is the data point.\n\n Here we follow the CFM style:\n The generation process (... | import logging
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from enum import Enum
from torch import Tensor, nn
from .cfm import CFM
from .irmae import IRMAE, IRMAEOutput
from ...utils.train_loop import TrainLoop | 2,245 |
logger = logging.getLogger(__name__)
def freeze_(module):
for p in module.parameters():
p.requires_grad_(False)
class LCFM(nn.Module):
class Mode(Enum):
AE = "ae"
|
logger = logging.getLogger(__name__)
def freeze_(module):
for p in module.parameters():
p.requires_grad_(False)
class LCFM(nn.Module):
class Mode(Enum):
AE = "ae" | CFM = "cfm" | 0 | 2023-11-15 08:15:51+00:00 | 4k |
PKU-YuanGroup/Chat-UniVi | visualization.py | [
{
"identifier": "CLIPVisionTower",
"path": "ChatUniVi/model/multimodal_encoder/clip_encoder.py",
"snippet": "class CLIPVisionTower(nn.Module):\n def __init__(self, vision_tower, args=None, delay_load=False):\n super().__init__()\n\n self.is_loaded = False\n\n self.vision_tower_na... | import numpy as np
import math
import os
import torch
from PIL import Image
from ChatUniVi.model.multimodal_encoder.clip_encoder import CLIPVisionTower
from ChatUniVi.model.cluster import CTM, TCBlock | 2,188 |
def split(image, patch_size=14, idx=None):
img = np.asarray(image, dtype=np.uint8).copy()
h, w, _ = img.shape
horizontal_lines = [i for i in range(patch_size, h, patch_size)]
vertical_lines = [i for i in range(patch_size, w, patch_size)]
for i in horizontal_lines:
for j in range(w):
img[i, j, :] = 0
for j in vertical_lines:
for i in range(h):
img[i, j, :] = 0
image = Image.fromarray(img, 'RGB')
return image
def merge(image, token_dict, patch_size=14, alpha=0.2, line_color=np.array([200, 200, 200])):
img = np.asarray(image, dtype=np.uint8).copy()
h, w, _ = img.shape
patch_num_h, patch_num_w = w // patch_size, w // patch_size
color_map = {}
idx = token_dict["idx_token"].tolist()[0]
for id, i in enumerate(idx):
color_map[i] = color_map[i] if i in color_map else {"id": [], "color": []}
color_map[i]["id"].append(id)
for _h in range(patch_size):
for _w in range(patch_size):
color_map[i]["color"].append(img[_h + patch_size * math.floor(id / patch_num_w),
_w + patch_size * (id % patch_num_h)])
for i in color_map:
color_map[i]["color"] = np.mean(np.stack(color_map[i]["color"], axis=0), axis=0)
for id in color_map[i]["id"]:
for _h in range(patch_size):
for _w in range(patch_size):
color = img[_h + patch_size * math.floor(id / patch_num_w), _w + patch_size * (
id % patch_num_h)] * alpha + color_map[i]["color"] * (1 - alpha)
img[_h + patch_size * math.floor(id / patch_num_w), _w + patch_size * (id % patch_num_h)] = color
for id, i in enumerate(idx):
if math.floor(id / patch_num_w) > 0:
if idx[id - patch_num_w] != i:
for _w in range(patch_size * (id % patch_num_h), patch_size * (id % patch_num_h + 1)):
img[patch_size * math.floor(id / patch_num_w), _w, :] = line_color
if (id % patch_num_h) > 0:
if idx[id - 1] != i:
for _h in range(patch_size * math.floor(id / patch_num_w), patch_size * (math.floor(id / patch_num_w) + 1)):
img[_h, patch_size * (id % patch_num_h), :] = line_color
image = Image.fromarray(img, 'RGB')
return image
if __name__ == '__main__':
image_path = "figures/COCO_val2014_000000214293.jpg"
clip_vit_14_path = ${openai_clip_path}
output_file = "figures"
if not os.path.exists(output_file):
os.makedirs(output_file)
vision_tower = CLIPVisionTower(clip_vit_14_path)
image = Image.open(os.path.join(image_path)).resize((224, 224))
|
def split(image, patch_size=14, idx=None):
img = np.asarray(image, dtype=np.uint8).copy()
h, w, _ = img.shape
horizontal_lines = [i for i in range(patch_size, h, patch_size)]
vertical_lines = [i for i in range(patch_size, w, patch_size)]
for i in horizontal_lines:
for j in range(w):
img[i, j, :] = 0
for j in vertical_lines:
for i in range(h):
img[i, j, :] = 0
image = Image.fromarray(img, 'RGB')
return image
def merge(image, token_dict, patch_size=14, alpha=0.2, line_color=np.array([200, 200, 200])):
img = np.asarray(image, dtype=np.uint8).copy()
h, w, _ = img.shape
patch_num_h, patch_num_w = w // patch_size, w // patch_size
color_map = {}
idx = token_dict["idx_token"].tolist()[0]
for id, i in enumerate(idx):
color_map[i] = color_map[i] if i in color_map else {"id": [], "color": []}
color_map[i]["id"].append(id)
for _h in range(patch_size):
for _w in range(patch_size):
color_map[i]["color"].append(img[_h + patch_size * math.floor(id / patch_num_w),
_w + patch_size * (id % patch_num_h)])
for i in color_map:
color_map[i]["color"] = np.mean(np.stack(color_map[i]["color"], axis=0), axis=0)
for id in color_map[i]["id"]:
for _h in range(patch_size):
for _w in range(patch_size):
color = img[_h + patch_size * math.floor(id / patch_num_w), _w + patch_size * (
id % patch_num_h)] * alpha + color_map[i]["color"] * (1 - alpha)
img[_h + patch_size * math.floor(id / patch_num_w), _w + patch_size * (id % patch_num_h)] = color
for id, i in enumerate(idx):
if math.floor(id / patch_num_w) > 0:
if idx[id - patch_num_w] != i:
for _w in range(patch_size * (id % patch_num_h), patch_size * (id % patch_num_h + 1)):
img[patch_size * math.floor(id / patch_num_w), _w, :] = line_color
if (id % patch_num_h) > 0:
if idx[id - 1] != i:
for _h in range(patch_size * math.floor(id / patch_num_w), patch_size * (math.floor(id / patch_num_w) + 1)):
img[_h, patch_size * (id % patch_num_h), :] = line_color
image = Image.fromarray(img, 'RGB')
return image
if __name__ == '__main__':
image_path = "figures/COCO_val2014_000000214293.jpg"
clip_vit_14_path = ${openai_clip_path}
output_file = "figures"
if not os.path.exists(output_file):
os.makedirs(output_file)
vision_tower = CLIPVisionTower(clip_vit_14_path)
image = Image.open(os.path.join(image_path)).resize((224, 224))
| ctm0 = CTM(sample_ratio=64, embed_dim=1024, dim_out=1024, k=32) | 1 | 2023-11-13 11:52:56+00:00 | 4k |
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 | 2,395 | + "Abstract: "
+ paper_entry.abstract[:4000]
)
return new_str
def batched(items, batch_size):
# takes a list and returns a list of list with batch_size
return [items[i : i + batch_size] for i in range(0, len(items), batch_size)]
def filter_papers_by_title(
papers: List[Paper], base_prompt: str, criterion: str
) -> List[Paper]:
filter_postfix = "Please identify any papers that you are absolutely sure your friend will not enjoy, formatted as a list of arxiv ids like [ID1, ID2, ID3..]"
batches_of_papers = batched(papers, 20)
final_list = []
for batch in batches_of_papers:
papers_string = "".join([paper_to_titles(paper) for paper in batch])
full_prompt = (
base_prompt + "\n " + criterion + "\n" + papers_string + filter_postfix
)
completion = call_chatgpt(full_prompt, "gpt-4")
cost = calc_price("gpt-4", completion.usage)
out_text = completion.choices[0].message.content
try:
filtered_set = set(json.loads(out_text))
for paper in batch:
if paper.arxiv_id not in filtered_set:
final_list.append(paper)
except Exception as ex:
print("Exception happened " + str(ex))
print("Failed to parse LM output as list " + out_text)
print(completion)
continue
return final_list, cost
def paper_to_titles(paper_entry: Paper) -> str:
return "ArXiv ID: " + paper_entry.arxiv_id + " Title: " + paper_entry.title + "\n"
def run_on_batch(
paper_batch, base_prompt, criterion, postfix_prompt, openai_client, config
):
batch_str = [paper_to_string(paper) for paper in paper_batch]
full_prompt = "\n".join(
[
base_prompt,
criterion + "\n",
"\n\n".join(batch_str) + "\n",
postfix_prompt,
]
)
json_dicts, cost = run_and_parse_chatgpt(full_prompt, openai_client, config)
return json_dicts, cost
def filter_by_gpt(
all_authors, papers, config, openai_client, all_papers, selected_papers, sort_dict
):
# deal with config parsing
with open("configs/base_prompt.txt", "r") as f:
base_prompt = f.read()
with open("configs/paper_topics.txt", "r") as f:
criterion = f.read()
with open("configs/postfix_prompt.txt", "r") as f:
postfix_prompt = f.read()
all_cost = 0
if config["SELECTION"].getboolean("run_openai"):
# filter first by hindex of authors to reduce costs.
paper_list = filter_papers_by_hindex(all_authors, papers, config)
if config["OUTPUT"].getboolean("debug_messages"):
print(str(len(paper_list)) + " papers after hindex filtering")
cost = 0
# paper_list, cost = filter_papers_by_title(paper_list, base_prompt, criterion)
if config["OUTPUT"].getboolean("debug_messages"):
print(
str(len(paper_list))
+ " papers after title filtering with cost of $"
+ str(cost)
)
all_cost += cost
# batch the remaining papers and invoke GPT
batch_of_papers = batched(paper_list, int(config["SELECTION"]["batch_size"]))
scored_batches = []
for batch in tqdm(batch_of_papers):
scored_in_batch = []
json_dicts, cost = run_on_batch(
batch, base_prompt, criterion, postfix_prompt, openai_client, config
)
all_cost += cost
for jdict in json_dicts:
if (
int(jdict["RELEVANCE"])
>= int(config["FILTERING"]["relevance_cutoff"])
and jdict["NOVELTY"] >= int(config["FILTERING"]["novelty_cutoff"])
and jdict["ARXIVID"] in all_papers
):
selected_papers[jdict["ARXIVID"]] = {
**dataclasses.asdict(all_papers[jdict["ARXIVID"]]),
**jdict,
}
## take the max of author match and gpt score
sort_dict[jdict["ARXIVID"]] = max(
jdict["RELEVANCE"] + jdict["NOVELTY"],
sort_dict.get(jdict["ARXIVID"], 0),
)
scored_in_batch.append(
{
**dataclasses.asdict(all_papers[jdict["ARXIVID"]]),
**jdict,
}
)
scored_batches.append(scored_in_batch)
if config["OUTPUT"].getboolean("dump_debug_file"):
with open(
config["OUTPUT"]["output_path"] + "gpt_paper_batches.debug.json", "w"
) as outfile:
|
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:
# renders each paper into a string to be processed by GPT
new_str = (
"ArXiv ID: "
+ paper_entry.arxiv_id
+ "\n"
+ "Title: "
+ paper_entry.title
+ "\n"
+ "Authors: "
+ " and ".join(paper_entry.authors)
+ "\n"
+ "Abstract: "
+ paper_entry.abstract[:4000]
)
return new_str
def batched(items, batch_size):
# takes a list and returns a list of list with batch_size
return [items[i : i + batch_size] for i in range(0, len(items), batch_size)]
def filter_papers_by_title(
papers: List[Paper], base_prompt: str, criterion: str
) -> List[Paper]:
filter_postfix = "Please identify any papers that you are absolutely sure your friend will not enjoy, formatted as a list of arxiv ids like [ID1, ID2, ID3..]"
batches_of_papers = batched(papers, 20)
final_list = []
for batch in batches_of_papers:
papers_string = "".join([paper_to_titles(paper) for paper in batch])
full_prompt = (
base_prompt + "\n " + criterion + "\n" + papers_string + filter_postfix
)
completion = call_chatgpt(full_prompt, "gpt-4")
cost = calc_price("gpt-4", completion.usage)
out_text = completion.choices[0].message.content
try:
filtered_set = set(json.loads(out_text))
for paper in batch:
if paper.arxiv_id not in filtered_set:
final_list.append(paper)
except Exception as ex:
print("Exception happened " + str(ex))
print("Failed to parse LM output as list " + out_text)
print(completion)
continue
return final_list, cost
def paper_to_titles(paper_entry: Paper) -> str:
return "ArXiv ID: " + paper_entry.arxiv_id + " Title: " + paper_entry.title + "\n"
def run_on_batch(
paper_batch, base_prompt, criterion, postfix_prompt, openai_client, config
):
batch_str = [paper_to_string(paper) for paper in paper_batch]
full_prompt = "\n".join(
[
base_prompt,
criterion + "\n",
"\n\n".join(batch_str) + "\n",
postfix_prompt,
]
)
json_dicts, cost = run_and_parse_chatgpt(full_prompt, openai_client, config)
return json_dicts, cost
def filter_by_gpt(
all_authors, papers, config, openai_client, all_papers, selected_papers, sort_dict
):
# deal with config parsing
with open("configs/base_prompt.txt", "r") as f:
base_prompt = f.read()
with open("configs/paper_topics.txt", "r") as f:
criterion = f.read()
with open("configs/postfix_prompt.txt", "r") as f:
postfix_prompt = f.read()
all_cost = 0
if config["SELECTION"].getboolean("run_openai"):
# filter first by hindex of authors to reduce costs.
paper_list = filter_papers_by_hindex(all_authors, papers, config)
if config["OUTPUT"].getboolean("debug_messages"):
print(str(len(paper_list)) + " papers after hindex filtering")
cost = 0
# paper_list, cost = filter_papers_by_title(paper_list, base_prompt, criterion)
if config["OUTPUT"].getboolean("debug_messages"):
print(
str(len(paper_list))
+ " papers after title filtering with cost of $"
+ str(cost)
)
all_cost += cost
# batch the remaining papers and invoke GPT
batch_of_papers = batched(paper_list, int(config["SELECTION"]["batch_size"]))
scored_batches = []
for batch in tqdm(batch_of_papers):
scored_in_batch = []
json_dicts, cost = run_on_batch(
batch, base_prompt, criterion, postfix_prompt, openai_client, config
)
all_cost += cost
for jdict in json_dicts:
if (
int(jdict["RELEVANCE"])
>= int(config["FILTERING"]["relevance_cutoff"])
and jdict["NOVELTY"] >= int(config["FILTERING"]["novelty_cutoff"])
and jdict["ARXIVID"] in all_papers
):
selected_papers[jdict["ARXIVID"]] = {
**dataclasses.asdict(all_papers[jdict["ARXIVID"]]),
**jdict,
}
## take the max of author match and gpt score
sort_dict[jdict["ARXIVID"]] = max(
jdict["RELEVANCE"] + jdict["NOVELTY"],
sort_dict.get(jdict["ARXIVID"], 0),
)
scored_in_batch.append(
{
**dataclasses.asdict(all_papers[jdict["ARXIVID"]]),
**jdict,
}
)
scored_batches.append(scored_in_batch)
if config["OUTPUT"].getboolean("dump_debug_file"):
with open(
config["OUTPUT"]["output_path"] + "gpt_paper_batches.debug.json", "w"
) as outfile: | json.dump(scored_batches, outfile, cls=EnhancedJSONEncoder, indent=4) | 1 | 2023-11-13 15:19:38+00:00 | 4k |
BobaZooba/xllm | tests/unit/collators/test_completion.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": "CompletionCollator",
"path": "src/... | from typing import Optional
from torch import Tensor
from transformers import PreTrainedTokenizer
from src.xllm import enums
from src.xllm.collators.completion import CompletionCollator
from tests.helpers.dummy_data import DATA
import pytest | 2,698 | # 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.
@pytest.mark.parametrize("prefix_end", [None, ":"])
def test_completion_collator(llama_tokenizer: PreTrainedTokenizer, prefix_end: Optional[str]):
collator = CompletionCollator(tokenizer=llama_tokenizer, max_length=128, prefix_end=prefix_end)
batch = collator(DATA)
for _key, value in batch.items():
assert isinstance(value, Tensor)
| # 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.
@pytest.mark.parametrize("prefix_end", [None, ":"])
def test_completion_collator(llama_tokenizer: PreTrainedTokenizer, prefix_end: Optional[str]):
collator = CompletionCollator(tokenizer=llama_tokenizer, max_length=128, prefix_end=prefix_end)
batch = collator(DATA)
for _key, value in batch.items():
assert isinstance(value, Tensor)
| condition_result = (batch[enums.Transformers.labels][:, :2] == llama_tokenizer.pad_token_id).unique() | 0 | 2023-11-10 17:55:03+00:00 | 4k |
banodoco/Steerable-Motion | imports/AdvancedControlNet/weight_nodes.py | [
{
"identifier": "TimestepKeyframeImport",
"path": "imports/AdvancedControlNet/control.py",
"snippet": "class TimestepKeyframeImport:\n def __init__(self,\n start_percent: float = 0.0,\n strength: float = 1.0,\n interpolation: str = StrengthInterpolation... | from torch import Tensor
from .control import TimestepKeyframeImport, TimestepKeyframeGroupImport, ControlWeightsImport, get_properly_arranged_t2i_weights, linear_conversion
from .logger import logger
import torch | 1,814 |
WEIGHTS_RETURN_NAMES = ("CN_WEIGHTS", "TK_SHORTCUT")
class DefaultWeightsImport:
@classmethod
def INPUT_TYPES(s):
return {
}
RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
RETURN_NAMES = WEIGHTS_RETURN_NAMES
FUNCTION = "load_weights"
CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights"
def load_weights(self):
weights = ControlWeightsImport.default()
|
WEIGHTS_RETURN_NAMES = ("CN_WEIGHTS", "TK_SHORTCUT")
class DefaultWeightsImport:
@classmethod
def INPUT_TYPES(s):
return {
}
RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
RETURN_NAMES = WEIGHTS_RETURN_NAMES
FUNCTION = "load_weights"
CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights"
def load_weights(self):
weights = ControlWeightsImport.default() | return (weights, TimestepKeyframeGroupImport.default(TimestepKeyframeImport(control_weights=weights))) | 1 | 2023-11-11 01:26:26+00:00 | 4k |
x0rzavi/github-readme-terminal | gifos/gifos.py | [
{
"identifier": "ConvertAnsiEscape",
"path": "gifos/utils/convert_ansi_escape.py",
"snippet": "class ConvertAnsiEscape:\n \"\"\"A class for converting ANSI escape codes to color values.\"\"\"\n\n __color_scheme = gifos_settings.get(\"general\", {}).get(\"color_scheme\")\n\n @staticmethod\n d... | import os
import random
import re
import sys
from math import ceil
from pathlib import Path
from shutil import rmtree
from icecream import ic
from PIL import Image, ImageDraw, ImageFont
from gifos.utils.convert_ansi_escape import ConvertAnsiEscape
from gifos.utils.load_config import gifos_settings | 2,826 | # TODO:
# [] Documentation
# [] proper file paths
# [] incremental text effect
# [] Better implementations for non monospace fonts
# [] Support all ANSI escape sequence forms
# [] Optimization + better code quality
# [] Test cases
# [] GIF maker implementation
# [] Scriptable input file
frame_base_name = gifos_settings.get("files", {}).get("frame_base_name") or "frame_"
frame_folder_name = gifos_settings.get("files", {}).get("frame_folder_name") or "./frames"
output_gif_name = gifos_settings.get("files", {}).get("output_gif_name") or "output"
try:
os.remove(output_gif_name + ".gif")
except Exception:
pass
rmtree(frame_folder_name, ignore_errors=True)
os.mkdir(frame_folder_name)
font_path = Path(__file__).parent / "fonts"
class Terminal:
"""A class to represent a terminal.
This class represents a terminal with a specified width, height, padding, and font.
Attributes:
width: The width of the terminal.
height: The height of the terminal.
xpad: The horizontal padding of the terminal.
ypad: The vertical padding of the terminal.
font_file: The file path of the font to use for the terminal. Defaults to "gohufont-uni-14.pil".
font_size: The size of the font to use for the terminal. Defaults to 16.
line_spacing: The line spacing to use for the terminal. Defaults to 4.
curr_row: The current row of the cursor in terminal.
curr_col: The current column of the cursor in terminal.
num_rows: The number of rows in the terminal.
num_cols: The number of columns in the terminal.
image_col: The column number of the last image pasted in the terminal.
Methods:
set_txt_color: Set the text color to be used.
set_bg_color: Set the background color to be used.
set_font: Set the font to be used.
toggle_show_cursor: Toggle the visibility of the cursor.
toggle_blink_cursor: Toggle the blinking of the cursor.
save_frame: Save the current frame of the terminal.
clear_frame: Clear the current frame of the terminal.
clone_frame: Clone the current frame of the terminal.
cursor_to_box: Move the cursor to a specified box (coordinate) in the terminal.
gen_text: Generate text on the terminal.
gen_typing_text: Generate text on the terminal as if it is being typed.
set_prompt: Set the prompt text to be used.
gen_prompt: Generate the prompt text on the terminal.
scroll_up: Scroll up the terminal.
delete_row: Delete a row in the terminal.
paste_image: Paste an image on the terminal.
set_fps: Set the FPS of the GIF to be generated.
gen_gif: Generate the GIF from the frames.
"""
def __init__(
self,
width: int,
height: int,
xpad: int,
ypad: int,
font_file: str = f"{font_path}/gohufont-uni-14.pil",
font_size: int = 16,
line_spacing: int = 4,
) -> None:
"""Initialize a Terminal object.
:param width: The width of the terminal.
:type width: int
:param height: The height of the terminal.
:type height: int
:param xpad: The horizontal padding of the terminal.
:type xpad: int
:param ypad: The vertical padding of the terminal.
:type ypad: int
:param font_file: The file path of the font to use for the terminal.
:type font_file: str, optional
:param font_size: The size of the font to use for the terminal. Defaults to 16.
:type font_size: int, optional
:param line_spacing: The line spacing to use for the terminal. Defaults to 4.
:type line_spacing: int, optional
"""
ic.configureOutput(includeContext=True)
self.__width = width
self.__height = height
self.__xpad = xpad
self.__ypad = ypad
self.__font_file = font_file
self.__font_size = font_size
self.__debug = gifos_settings.get("general", {}).get("debug") or False
if not self.__debug:
ic.disable()
| # TODO:
# [] Documentation
# [] proper file paths
# [] incremental text effect
# [] Better implementations for non monospace fonts
# [] Support all ANSI escape sequence forms
# [] Optimization + better code quality
# [] Test cases
# [] GIF maker implementation
# [] Scriptable input file
frame_base_name = gifos_settings.get("files", {}).get("frame_base_name") or "frame_"
frame_folder_name = gifos_settings.get("files", {}).get("frame_folder_name") or "./frames"
output_gif_name = gifos_settings.get("files", {}).get("output_gif_name") or "output"
try:
os.remove(output_gif_name + ".gif")
except Exception:
pass
rmtree(frame_folder_name, ignore_errors=True)
os.mkdir(frame_folder_name)
font_path = Path(__file__).parent / "fonts"
class Terminal:
"""A class to represent a terminal.
This class represents a terminal with a specified width, height, padding, and font.
Attributes:
width: The width of the terminal.
height: The height of the terminal.
xpad: The horizontal padding of the terminal.
ypad: The vertical padding of the terminal.
font_file: The file path of the font to use for the terminal. Defaults to "gohufont-uni-14.pil".
font_size: The size of the font to use for the terminal. Defaults to 16.
line_spacing: The line spacing to use for the terminal. Defaults to 4.
curr_row: The current row of the cursor in terminal.
curr_col: The current column of the cursor in terminal.
num_rows: The number of rows in the terminal.
num_cols: The number of columns in the terminal.
image_col: The column number of the last image pasted in the terminal.
Methods:
set_txt_color: Set the text color to be used.
set_bg_color: Set the background color to be used.
set_font: Set the font to be used.
toggle_show_cursor: Toggle the visibility of the cursor.
toggle_blink_cursor: Toggle the blinking of the cursor.
save_frame: Save the current frame of the terminal.
clear_frame: Clear the current frame of the terminal.
clone_frame: Clone the current frame of the terminal.
cursor_to_box: Move the cursor to a specified box (coordinate) in the terminal.
gen_text: Generate text on the terminal.
gen_typing_text: Generate text on the terminal as if it is being typed.
set_prompt: Set the prompt text to be used.
gen_prompt: Generate the prompt text on the terminal.
scroll_up: Scroll up the terminal.
delete_row: Delete a row in the terminal.
paste_image: Paste an image on the terminal.
set_fps: Set the FPS of the GIF to be generated.
gen_gif: Generate the GIF from the frames.
"""
def __init__(
self,
width: int,
height: int,
xpad: int,
ypad: int,
font_file: str = f"{font_path}/gohufont-uni-14.pil",
font_size: int = 16,
line_spacing: int = 4,
) -> None:
"""Initialize a Terminal object.
:param width: The width of the terminal.
:type width: int
:param height: The height of the terminal.
:type height: int
:param xpad: The horizontal padding of the terminal.
:type xpad: int
:param ypad: The vertical padding of the terminal.
:type ypad: int
:param font_file: The file path of the font to use for the terminal.
:type font_file: str, optional
:param font_size: The size of the font to use for the terminal. Defaults to 16.
:type font_size: int, optional
:param line_spacing: The line spacing to use for the terminal. Defaults to 4.
:type line_spacing: int, optional
"""
ic.configureOutput(includeContext=True)
self.__width = width
self.__height = height
self.__xpad = xpad
self.__ypad = ypad
self.__font_file = font_file
self.__font_size = font_size
self.__debug = gifos_settings.get("general", {}).get("debug") or False
if not self.__debug:
ic.disable()
| self.__txt_color = self.__def_txt_color = ConvertAnsiEscape.convert("39").data | 0 | 2023-11-17 06:21:18+00:00 | 4k |
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,978 |
# 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(
"[yellow]Whats up!?[/], how can I help you being productive today :rocket:?"
)
console.print(
"\t[1] :clipboard: [green]Create new Task[/]"
+ 2 * "\t"
+ "[2] :clockwise_vertical_arrows: [bold cornflower_blue]Update/Check Task[/]"
)
console.print(
"\t[3] :bookmark_tabs: [bold yellow]Change Kanban Board[/]"
+ "\t"
+ "[4] :magnifying_glass_tilted_left: [bold blue]Show Task Details[/]"
)
console.print(
"\t[5] :cross_mark: [red]Delete Kanban Board[/]"
+ "\t"
+ "[6] :hammer_and_wrench: [grey69]Show Current Settings[/]"
)
action = IntPrompt.ask(
prompt="Choose wisely :books:",
choices=[
"1",
"2",
"3",
"4",
"5",
"6",
],
show_choices=False,
)
return action
# Action 1: New Task
def input_create_new_task() -> dict:
title = Prompt.ask(
prompt="[1/5] Add Task Title",
)
description = Prompt.ask(
prompt="[2/5] Add Task Description",
show_default=True,
default="",
)
tag = Prompt.ask(
prompt="[3/5] Add a Tag",
show_default=True,
default="ETC",
)
while True:
due_date = Prompt.ask(
prompt="[4/5] Add a Due Date (YYYY-MM-DD)",
show_default=True,
default="",
)
if not due_date or check_due_date_format(date_str=due_date):
break
else:
console.print(
f":warning: '{due_date}' has [red]not[/] "
+ "the right format YYYY-MM-DD"
)
console.print(f"\t[1] {COLOR_DICT['Ready']}")
console.print(f"\t[2] {COLOR_DICT['Doing']}")
status = IntPrompt.ask(
prompt="[5/5] Status of Task",
show_choices=False,
choices=["1", "2"],
show_default=True,
default="1",
)
new_task = {
"Title": title,
"Description": description,
"Status": "Ready" if str(status) == "1" else "Doing",
"Tag": tag.upper(),
|
# 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(
"[yellow]Whats up!?[/], how can I help you being productive today :rocket:?"
)
console.print(
"\t[1] :clipboard: [green]Create new Task[/]"
+ 2 * "\t"
+ "[2] :clockwise_vertical_arrows: [bold cornflower_blue]Update/Check Task[/]"
)
console.print(
"\t[3] :bookmark_tabs: [bold yellow]Change Kanban Board[/]"
+ "\t"
+ "[4] :magnifying_glass_tilted_left: [bold blue]Show Task Details[/]"
)
console.print(
"\t[5] :cross_mark: [red]Delete Kanban Board[/]"
+ "\t"
+ "[6] :hammer_and_wrench: [grey69]Show Current Settings[/]"
)
action = IntPrompt.ask(
prompt="Choose wisely :books:",
choices=[
"1",
"2",
"3",
"4",
"5",
"6",
],
show_choices=False,
)
return action
# Action 1: New Task
def input_create_new_task() -> dict:
title = Prompt.ask(
prompt="[1/5] Add Task Title",
)
description = Prompt.ask(
prompt="[2/5] Add Task Description",
show_default=True,
default="",
)
tag = Prompt.ask(
prompt="[3/5] Add a Tag",
show_default=True,
default="ETC",
)
while True:
due_date = Prompt.ask(
prompt="[4/5] Add a Due Date (YYYY-MM-DD)",
show_default=True,
default="",
)
if not due_date or check_due_date_format(date_str=due_date):
break
else:
console.print(
f":warning: '{due_date}' has [red]not[/] "
+ "the right format YYYY-MM-DD"
)
console.print(f"\t[1] {COLOR_DICT['Ready']}")
console.print(f"\t[2] {COLOR_DICT['Doing']}")
status = IntPrompt.ask(
prompt="[5/5] Status of Task",
show_choices=False,
choices=["1", "2"],
show_default=True,
default="1",
)
new_task = {
"Title": title,
"Description": description,
"Status": "Ready" if str(status) == "1" else "Doing",
"Tag": tag.upper(), | "Creation_Date": current_time_to_str(), | 6 | 2023-11-11 14:43:55+00:00 | 4k |
AMAAI-Lab/mustango | audioldm/latent_diffusion/ddpm.py | [
{
"identifier": "exists",
"path": "audioldm/utils.py",
"snippet": "def exists(x):\n return x is not None"
},
{
"identifier": "default",
"path": "audioldm/utils.py",
"snippet": "def default(val, d):\n if exists(val):\n return val\n return d() if isfunction(d) else d"
},
... | import sys
import os
import torch
import torch.nn as nn
import numpy as np
import soundfile as sf
import os
from contextlib import contextmanager
from functools import partial
from tqdm import tqdm
from audioldm.utils import exists, default, count_params, instantiate_from_config
from audioldm.latent_diffusion.ema import LitEma
from audioldm.latent_diffusion.util import (
make_beta_schedule,
extract_into_tensor,
noise_like,
) | 3,317 | log_every_t=100,
clip_denoised=True,
linear_start=1e-4,
linear_end=2e-2,
cosine_s=8e-3,
given_betas=None,
original_elbo_weight=0.0,
v_posterior=0.0, # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
l_simple_weight=1.0,
conditioning_key=None,
parameterization="eps", # all assuming fixed variance schedules
scheduler_config=None,
use_positional_encodings=False,
learn_logvar=False,
logvar_init=0.0,
):
super().__init__()
assert parameterization in [
"eps",
"x0",
], 'currently only supporting "eps" and "x0"'
self.parameterization = parameterization
self.state = None
# print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode")
self.cond_stage_model = None
self.clip_denoised = clip_denoised
self.log_every_t = log_every_t
self.first_stage_key = first_stage_key
self.latent_t_size = latent_t_size
self.latent_f_size = latent_f_size
self.channels = channels
self.use_positional_encodings = use_positional_encodings
self.model = DiffusionWrapper(unet_config, conditioning_key)
count_params(self.model, verbose=True)
self.use_ema = use_ema
if self.use_ema:
self.model_ema = LitEma(self.model)
# print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
self.use_scheduler = scheduler_config is not None
if self.use_scheduler:
self.scheduler_config = scheduler_config
self.v_posterior = v_posterior
self.original_elbo_weight = original_elbo_weight
self.l_simple_weight = l_simple_weight
if monitor is not None:
self.monitor = monitor
self.register_schedule(
given_betas=given_betas,
beta_schedule=beta_schedule,
timesteps=timesteps,
linear_start=linear_start,
linear_end=linear_end,
cosine_s=cosine_s,
)
self.loss_type = loss_type
self.learn_logvar = learn_logvar
self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,))
if self.learn_logvar:
self.logvar = nn.Parameter(self.logvar, requires_grad=True)
else:
self.logvar = nn.Parameter(self.logvar, requires_grad=False)
self.logger_save_dir = None
self.logger_project = None
self.logger_version = None
self.label_indices_total = None
# To avoid the system cannot find metric value for checkpoint
self.metrics_buffer = {
"val/kullback_leibler_divergence_sigmoid": 15.0,
"val/kullback_leibler_divergence_softmax": 10.0,
"val/psnr": 0.0,
"val/ssim": 0.0,
"val/inception_score_mean": 1.0,
"val/inception_score_std": 0.0,
"val/kernel_inception_distance_mean": 0.0,
"val/kernel_inception_distance_std": 0.0,
"val/frechet_inception_distance": 133.0,
"val/frechet_audio_distance": 32.0,
}
self.initial_learning_rate = None
def get_log_dir(self):
if (
self.logger_save_dir is None
and self.logger_project is None
and self.logger_version is None
):
return os.path.join(
self.logger.save_dir, self.logger._project, self.logger.version
)
else:
return os.path.join(
self.logger_save_dir, self.logger_project, self.logger_version
)
def set_log_dir(self, save_dir, project, version):
self.logger_save_dir = save_dir
self.logger_project = project
self.logger_version = version
def register_schedule(
self,
given_betas=None,
beta_schedule="linear",
timesteps=1000,
linear_start=1e-4,
linear_end=2e-2,
cosine_s=8e-3,
):
if exists(given_betas):
betas = given_betas
else:
| """
wild mixture of
https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py
https://github.com/CompVis/taming-transformers
-- merci
"""
__conditioning_keys__ = {"concat": "c_concat", "crossattn": "c_crossattn", "adm": "y"}
def disabled_train(self, mode=True):
"""Overwrite model.train with this function to make sure train/eval mode
does not change anymore."""
return self
def uniform_on_device(r1, r2, shape, device):
return (r1 - r2) * torch.rand(*shape, device=device) + r2
class DiffusionWrapper(nn.Module):
def __init__(self, diff_model_config, conditioning_key):
super().__init__()
self.diffusion_model = instantiate_from_config(diff_model_config)
self.conditioning_key = conditioning_key
assert self.conditioning_key in [
None,
"concat",
"crossattn",
"hybrid",
"adm",
"film",
]
def forward(
self, x, t, c_concat: list = None, c_crossattn: list = None, c_film: list = None
):
x = x.contiguous()
t = t.contiguous()
if self.conditioning_key is None:
out = self.diffusion_model(x, t)
elif self.conditioning_key == "concat":
xc = torch.cat([x] + c_concat, dim=1)
out = self.diffusion_model(xc, t)
elif self.conditioning_key == "crossattn":
cc = torch.cat(c_crossattn, 1)
out = self.diffusion_model(x, t, context=cc)
elif self.conditioning_key == "hybrid":
xc = torch.cat([x] + c_concat, dim=1)
cc = torch.cat(c_crossattn, 1)
out = self.diffusion_model(xc, t, context=cc)
elif (
self.conditioning_key == "film"
): # The condition is assumed to be a global token, which wil pass through a linear layer and added with the time embedding for the FILM
cc = c_film[0].squeeze(1) # only has one token
out = self.diffusion_model(x, t, y=cc)
elif self.conditioning_key == "adm":
cc = c_crossattn[0]
out = self.diffusion_model(x, t, y=cc)
else:
raise NotImplementedError()
return out
class DDPM(nn.Module):
# classic DDPM with Gaussian diffusion, in image space
def __init__(
self,
unet_config,
timesteps=1000,
beta_schedule="linear",
loss_type="l2",
ckpt_path=None,
ignore_keys=[],
load_only_unet=False,
monitor="val/loss",
use_ema=True,
first_stage_key="image",
latent_t_size=256,
latent_f_size=16,
channels=3,
log_every_t=100,
clip_denoised=True,
linear_start=1e-4,
linear_end=2e-2,
cosine_s=8e-3,
given_betas=None,
original_elbo_weight=0.0,
v_posterior=0.0, # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
l_simple_weight=1.0,
conditioning_key=None,
parameterization="eps", # all assuming fixed variance schedules
scheduler_config=None,
use_positional_encodings=False,
learn_logvar=False,
logvar_init=0.0,
):
super().__init__()
assert parameterization in [
"eps",
"x0",
], 'currently only supporting "eps" and "x0"'
self.parameterization = parameterization
self.state = None
# print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode")
self.cond_stage_model = None
self.clip_denoised = clip_denoised
self.log_every_t = log_every_t
self.first_stage_key = first_stage_key
self.latent_t_size = latent_t_size
self.latent_f_size = latent_f_size
self.channels = channels
self.use_positional_encodings = use_positional_encodings
self.model = DiffusionWrapper(unet_config, conditioning_key)
count_params(self.model, verbose=True)
self.use_ema = use_ema
if self.use_ema:
self.model_ema = LitEma(self.model)
# print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
self.use_scheduler = scheduler_config is not None
if self.use_scheduler:
self.scheduler_config = scheduler_config
self.v_posterior = v_posterior
self.original_elbo_weight = original_elbo_weight
self.l_simple_weight = l_simple_weight
if monitor is not None:
self.monitor = monitor
self.register_schedule(
given_betas=given_betas,
beta_schedule=beta_schedule,
timesteps=timesteps,
linear_start=linear_start,
linear_end=linear_end,
cosine_s=cosine_s,
)
self.loss_type = loss_type
self.learn_logvar = learn_logvar
self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,))
if self.learn_logvar:
self.logvar = nn.Parameter(self.logvar, requires_grad=True)
else:
self.logvar = nn.Parameter(self.logvar, requires_grad=False)
self.logger_save_dir = None
self.logger_project = None
self.logger_version = None
self.label_indices_total = None
# To avoid the system cannot find metric value for checkpoint
self.metrics_buffer = {
"val/kullback_leibler_divergence_sigmoid": 15.0,
"val/kullback_leibler_divergence_softmax": 10.0,
"val/psnr": 0.0,
"val/ssim": 0.0,
"val/inception_score_mean": 1.0,
"val/inception_score_std": 0.0,
"val/kernel_inception_distance_mean": 0.0,
"val/kernel_inception_distance_std": 0.0,
"val/frechet_inception_distance": 133.0,
"val/frechet_audio_distance": 32.0,
}
self.initial_learning_rate = None
def get_log_dir(self):
if (
self.logger_save_dir is None
and self.logger_project is None
and self.logger_version is None
):
return os.path.join(
self.logger.save_dir, self.logger._project, self.logger.version
)
else:
return os.path.join(
self.logger_save_dir, self.logger_project, self.logger_version
)
def set_log_dir(self, save_dir, project, version):
self.logger_save_dir = save_dir
self.logger_project = project
self.logger_version = version
def register_schedule(
self,
given_betas=None,
beta_schedule="linear",
timesteps=1000,
linear_start=1e-4,
linear_end=2e-2,
cosine_s=8e-3,
):
if exists(given_betas):
betas = given_betas
else: | betas = make_beta_schedule( | 5 | 2023-11-14 23:29:31+00:00 | 4k |
lxmusics/lx-music-api-server-python | main.py | [
{
"identifier": "config",
"path": "common/config.py",
"snippet": "def get_data_connection():\ndef get_cache_connection():\ndef handle_default_config():\ndef load_data():\ndef save_data(config_data):\ndef getCache(module, key):\ndef updateCache(module, key, data):\ndef resetRequestTime(ip):\ndef updateRe... | import sys
import ujson as json
import threading
import traceback
import modules
import asyncio
import aiohttp
import time
import concurrent
from common import config
from common import lxsecurity
from common import log
from common import Httpx
from common import variable
from common import scheduler
from common import lx_script
from aiohttp.web import Response | 2,009 |
if ((sys.version_info.major == 3 and sys.version_info.minor < 6) or sys.version_info.major == 2):
print('Python版本过低,请使用Python 3.6+ ')
sys.exit(1)
def handleResult(dic, status = 200):
return Response(body = json.dumps(dic, indent=2, ensure_ascii=False), content_type='application/json', status = status)
logger = log.log("main")
aiologger = log.log('aiohttp_web')
stopEvent = None
if (sys.version_info.minor < 8 and sys.version_info.major == 3):
logger.warning('您使用的Python版本已经停止更新,不建议继续使用')
stopEvent = concurrent.futures._base.CancelledError
else:
stopEvent = asyncio.exceptions.CancelledError
def start_checkcn_thread():
threading.Thread(target=Httpx.checkcn).start()
# check request info before start
async def handle_before_request(app, handler):
async def handle_request(request):
try:
# nginx proxy header
if (request.headers.get("X-Real-IP")):
request.remote_addr = request.headers.get("X-Real-IP")
else:
request.remote_addr = request.remote
# check ip
if (config.check_ip_banned(request.remote_addr)):
return handleResult({"code": 1, "msg": "您的IP已被封禁", "data": None}, 403)
# check global rate limit
if (
(time.time() - config.getRequestTime('global'))
<
(config.read_config("security.rate_limit.global"))
):
return handleResult({"code": 5, "msg": "全局限速", "data": None}, 429)
if (
(time.time() - config.getRequestTime(request.remote_addr))
<
(config.read_config("security.rate_limit.ip"))
):
return handleResult({"code": 5, "msg": "IP限速", "data": None}, 429)
# update request time
config.updateRequestTime('global')
config.updateRequestTime(request.remote_addr)
# check host
if (config.read_config("security.allowed_host.enable")):
if request.host.split(":")[0] not in config.read_config("security.allowed_host.list"):
if config.read_config("security.allowed_host.blacklist.enable"):
config.ban_ip(request.remote_addr, int(config.read_config("security.allowed_host.blacklist.length")))
return handleResult({'code': 6, 'msg': '未找到您所请求的资源', 'data': None}, 404)
resp = await handler(request)
if (isinstance(resp, str)):
resp = Response(body = resp, content_type='text/plain', status = 200)
elif (isinstance(resp, dict)):
resp = handleResult(resp)
elif (not isinstance(resp, Response)):
resp = Response(body = str(resp), content_type='text/plain', status = 200)
aiologger.info(f'{request.remote_addr} - {request.method} "{request.path}", {resp.status}')
return resp
except:
logger.error(traceback.format_exc())
return {"code": 4, "msg": "内部服务器错误", "data": None}
return handle_request
async def main(request):
return handleResult({"code": 0, "msg": "success", "data": None})
async def handle(request):
method = request.match_info.get('method')
source = request.match_info.get('source')
songId = request.match_info.get('songId')
quality = request.match_info.get('quality')
if (config.read_config("security.key.enable") and request.host.split(':')[0] not in config.read_config('security.whitelist_host')):
if (request.headers.get("X-Request-Key")) != config.read_config("security.key.value"):
if (config.read_config("security.key.ban")):
config.ban_ip(request.remote_addr)
return handleResult({"code": 1, "msg": "key验证失败", "data": None}, 403)
if (config.read_config('security.check_lxm.enable') and request.host.split(':')[0] not in config.read_config('security.whitelist_host')):
lxm = request.headers.get('lxm')
if (not lxsecurity.checklxmheader(lxm, request.url)):
if (config.read_config('security.lxm_ban.enable')):
config.ban_ip(request.remote_addr)
return handleResult({"code": 1, "msg": "lxm请求头验证失败", "data": None}, 403)
try:
query = dict(request.query)
if (method in dir(modules) and query == {}):
return handleResult(await getattr(modules, method)(source, songId, quality))
elif ((method + '_with_query') in dir(modules) and query != {}):
return handleResult(await getattr(modules, method + '_with_query')(source, songId, quality, query))
else:
if (query == {}):
return handleResult(await modules.other(method, source, songId, quality))
else:
return handleResult(await modules.other_with_query(method, source, songId, quality, query))
except:
logger.error(traceback.format_exc())
return handleResult({'code': 4, 'msg': '内部服务器错误', 'data': None}, 500)
async def handle_404(request):
return handleResult({'code': 6, 'msg': '未找到您所请求的资源', 'data': None}, 404)
app = aiohttp.web.Application(middlewares=[handle_before_request])
# mainpage
app.router.add_get('/', main)
# api
app.router.add_get('/{method}/{source}/{songId}/{quality}', handle)
app.router.add_get('/{method}/{source}/{songId}', handle)
if (config.read_config('common.allow_download_script')):
| #!/usr/bin/env python3
# ----------------------------------------
# - mode: python -
# - author: helloplhm-qwq -
# - name: main.py -
# - project: lx-music-api-server -
# - license: MIT -
# ----------------------------------------
# This file is part of the "lx-music-api-server" project.
if ((sys.version_info.major == 3 and sys.version_info.minor < 6) or sys.version_info.major == 2):
print('Python版本过低,请使用Python 3.6+ ')
sys.exit(1)
def handleResult(dic, status = 200):
return Response(body = json.dumps(dic, indent=2, ensure_ascii=False), content_type='application/json', status = status)
logger = log.log("main")
aiologger = log.log('aiohttp_web')
stopEvent = None
if (sys.version_info.minor < 8 and sys.version_info.major == 3):
logger.warning('您使用的Python版本已经停止更新,不建议继续使用')
stopEvent = concurrent.futures._base.CancelledError
else:
stopEvent = asyncio.exceptions.CancelledError
def start_checkcn_thread():
threading.Thread(target=Httpx.checkcn).start()
# check request info before start
async def handle_before_request(app, handler):
async def handle_request(request):
try:
# nginx proxy header
if (request.headers.get("X-Real-IP")):
request.remote_addr = request.headers.get("X-Real-IP")
else:
request.remote_addr = request.remote
# check ip
if (config.check_ip_banned(request.remote_addr)):
return handleResult({"code": 1, "msg": "您的IP已被封禁", "data": None}, 403)
# check global rate limit
if (
(time.time() - config.getRequestTime('global'))
<
(config.read_config("security.rate_limit.global"))
):
return handleResult({"code": 5, "msg": "全局限速", "data": None}, 429)
if (
(time.time() - config.getRequestTime(request.remote_addr))
<
(config.read_config("security.rate_limit.ip"))
):
return handleResult({"code": 5, "msg": "IP限速", "data": None}, 429)
# update request time
config.updateRequestTime('global')
config.updateRequestTime(request.remote_addr)
# check host
if (config.read_config("security.allowed_host.enable")):
if request.host.split(":")[0] not in config.read_config("security.allowed_host.list"):
if config.read_config("security.allowed_host.blacklist.enable"):
config.ban_ip(request.remote_addr, int(config.read_config("security.allowed_host.blacklist.length")))
return handleResult({'code': 6, 'msg': '未找到您所请求的资源', 'data': None}, 404)
resp = await handler(request)
if (isinstance(resp, str)):
resp = Response(body = resp, content_type='text/plain', status = 200)
elif (isinstance(resp, dict)):
resp = handleResult(resp)
elif (not isinstance(resp, Response)):
resp = Response(body = str(resp), content_type='text/plain', status = 200)
aiologger.info(f'{request.remote_addr} - {request.method} "{request.path}", {resp.status}')
return resp
except:
logger.error(traceback.format_exc())
return {"code": 4, "msg": "内部服务器错误", "data": None}
return handle_request
async def main(request):
return handleResult({"code": 0, "msg": "success", "data": None})
async def handle(request):
method = request.match_info.get('method')
source = request.match_info.get('source')
songId = request.match_info.get('songId')
quality = request.match_info.get('quality')
if (config.read_config("security.key.enable") and request.host.split(':')[0] not in config.read_config('security.whitelist_host')):
if (request.headers.get("X-Request-Key")) != config.read_config("security.key.value"):
if (config.read_config("security.key.ban")):
config.ban_ip(request.remote_addr)
return handleResult({"code": 1, "msg": "key验证失败", "data": None}, 403)
if (config.read_config('security.check_lxm.enable') and request.host.split(':')[0] not in config.read_config('security.whitelist_host')):
lxm = request.headers.get('lxm')
if (not lxsecurity.checklxmheader(lxm, request.url)):
if (config.read_config('security.lxm_ban.enable')):
config.ban_ip(request.remote_addr)
return handleResult({"code": 1, "msg": "lxm请求头验证失败", "data": None}, 403)
try:
query = dict(request.query)
if (method in dir(modules) and query == {}):
return handleResult(await getattr(modules, method)(source, songId, quality))
elif ((method + '_with_query') in dir(modules) and query != {}):
return handleResult(await getattr(modules, method + '_with_query')(source, songId, quality, query))
else:
if (query == {}):
return handleResult(await modules.other(method, source, songId, quality))
else:
return handleResult(await modules.other_with_query(method, source, songId, quality, query))
except:
logger.error(traceback.format_exc())
return handleResult({'code': 4, 'msg': '内部服务器错误', 'data': None}, 500)
async def handle_404(request):
return handleResult({'code': 6, 'msg': '未找到您所请求的资源', 'data': None}, 404)
app = aiohttp.web.Application(middlewares=[handle_before_request])
# mainpage
app.router.add_get('/', main)
# api
app.router.add_get('/{method}/{source}/{songId}/{quality}', handle)
app.router.add_get('/{method}/{source}/{songId}', handle)
if (config.read_config('common.allow_download_script')): | app.router.add_get('/script', lx_script.generate_script_response) | 6 | 2023-11-10 13:16:30+00:00 | 4k |
ai-forever/Kandinsky-3 | kandinsky3/model/unet.py | [
{
"identifier": "Identity",
"path": "kandinsky3/model/nn.py",
"snippet": "class Identity(nn.Module):\n def __init__(self, *args, **kwargs):\n super().__init__()\n\n @staticmethod\n def forward(x, *args, **kwargs):\n return x"
},
{
"identifier": "Attention",
"path": "ka... | import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange
from .nn import Identity, Attention, SinusoidalPosEmb, ConditionalGroupNorm
from .utils import exist, set_default_item, set_default_layer | 1,757 |
class Block(nn.Module):
def __init__(self, in_channels, out_channels, time_embed_dim, kernel_size=3, norm_groups=32, up_resolution=None):
super().__init__()
self.group_norm = ConditionalGroupNorm(norm_groups, in_channels, time_embed_dim)
self.activation = nn.SiLU()
self.up_sample = set_default_layer(
exist(up_resolution) and up_resolution,
nn.ConvTranspose2d, (in_channels, in_channels), {'kernel_size': 2, 'stride': 2}
)
padding = set_default_item(kernel_size == 1, 0, 1)
self.projection = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, padding=padding)
self.down_sample = set_default_layer(
exist(up_resolution) and not up_resolution,
nn.Conv2d, (out_channels, out_channels), {'kernel_size': 2, 'stride': 2}
)
def forward(self, x, time_embed):
x = self.group_norm(x, time_embed)
x = self.activation(x)
x = self.up_sample(x)
x = self.projection(x)
x = self.down_sample(x)
return x
class ResNetBlock(nn.Module):
def __init__(
self, in_channels, out_channels, time_embed_dim, norm_groups=32, compression_ratio=2, up_resolutions=4*[None]
):
super().__init__()
kernel_sizes = [1, 3, 3, 1]
hidden_channel = max(in_channels, out_channels) // compression_ratio
hidden_channels = [(in_channels, hidden_channel)] + [(hidden_channel, hidden_channel)] * 2 + [(hidden_channel, out_channels)]
self.resnet_blocks = nn.ModuleList([
Block(in_channel, out_channel, time_embed_dim, kernel_size, norm_groups, up_resolution)
for (in_channel, out_channel), kernel_size, up_resolution in zip(hidden_channels, kernel_sizes, up_resolutions)
])
self.shortcut_up_sample = set_default_layer(
True in up_resolutions,
nn.ConvTranspose2d, (in_channels, in_channels), {'kernel_size': 2, 'stride': 2}
)
self.shortcut_projection = set_default_layer(
in_channels != out_channels,
nn.Conv2d, (in_channels, out_channels), {'kernel_size': 1}
)
self.shortcut_down_sample = set_default_layer(
False in up_resolutions,
nn.Conv2d, (out_channels, out_channels), {'kernel_size': 2, 'stride': 2}
)
def forward(self, x, time_embed):
out = x
for resnet_block in self.resnet_blocks:
out = resnet_block(out, time_embed)
x = self.shortcut_up_sample(x)
x = self.shortcut_projection(x)
x = self.shortcut_down_sample(x)
x = x + out
return x
class AttentionPolling(nn.Module):
def __init__(self, num_channels, context_dim, head_dim=64):
super().__init__()
|
class Block(nn.Module):
def __init__(self, in_channels, out_channels, time_embed_dim, kernel_size=3, norm_groups=32, up_resolution=None):
super().__init__()
self.group_norm = ConditionalGroupNorm(norm_groups, in_channels, time_embed_dim)
self.activation = nn.SiLU()
self.up_sample = set_default_layer(
exist(up_resolution) and up_resolution,
nn.ConvTranspose2d, (in_channels, in_channels), {'kernel_size': 2, 'stride': 2}
)
padding = set_default_item(kernel_size == 1, 0, 1)
self.projection = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, padding=padding)
self.down_sample = set_default_layer(
exist(up_resolution) and not up_resolution,
nn.Conv2d, (out_channels, out_channels), {'kernel_size': 2, 'stride': 2}
)
def forward(self, x, time_embed):
x = self.group_norm(x, time_embed)
x = self.activation(x)
x = self.up_sample(x)
x = self.projection(x)
x = self.down_sample(x)
return x
class ResNetBlock(nn.Module):
def __init__(
self, in_channels, out_channels, time_embed_dim, norm_groups=32, compression_ratio=2, up_resolutions=4*[None]
):
super().__init__()
kernel_sizes = [1, 3, 3, 1]
hidden_channel = max(in_channels, out_channels) // compression_ratio
hidden_channels = [(in_channels, hidden_channel)] + [(hidden_channel, hidden_channel)] * 2 + [(hidden_channel, out_channels)]
self.resnet_blocks = nn.ModuleList([
Block(in_channel, out_channel, time_embed_dim, kernel_size, norm_groups, up_resolution)
for (in_channel, out_channel), kernel_size, up_resolution in zip(hidden_channels, kernel_sizes, up_resolutions)
])
self.shortcut_up_sample = set_default_layer(
True in up_resolutions,
nn.ConvTranspose2d, (in_channels, in_channels), {'kernel_size': 2, 'stride': 2}
)
self.shortcut_projection = set_default_layer(
in_channels != out_channels,
nn.Conv2d, (in_channels, out_channels), {'kernel_size': 1}
)
self.shortcut_down_sample = set_default_layer(
False in up_resolutions,
nn.Conv2d, (out_channels, out_channels), {'kernel_size': 2, 'stride': 2}
)
def forward(self, x, time_embed):
out = x
for resnet_block in self.resnet_blocks:
out = resnet_block(out, time_embed)
x = self.shortcut_up_sample(x)
x = self.shortcut_projection(x)
x = self.shortcut_down_sample(x)
x = x + out
return x
class AttentionPolling(nn.Module):
def __init__(self, num_channels, context_dim, head_dim=64):
super().__init__() | self.attention = Attention(context_dim, num_channels, context_dim, head_dim) | 1 | 2023-11-13 10:16:04+00:00 | 4k |
spfrommer/torchexplorer | torchexplorer/render/layout.py | [
{
"identifier": "utils",
"path": "torchexplorer/utils.py",
"snippet": "def iter_not_none(iterable: Iterable[Any]) -> Iterator[Any]:\ndef enum_not_none(iterable: Iterable[Any]) -> Iterator[tuple[int, Any]]:\ndef interleave(l1: list[Any], l2: list[Any]) -> list[Any]:\ndef list_add(l1: list[float], l2: lis... | import copy
import html
import json
import string
import numpy as np
import networkx as nx
from typing import Optional, Union
from subprocess import Popen, PIPE
from torchexplorer import utils
from torchexplorer import core
from torchexplorer.components.tooltip import Tooltip
from torchexplorer.core import ModuleInvocationHistograms, ModuleInvocationStructure
from torchexplorer.structure.structure import is_input_node, is_io_node
from torchexplorer.render.structs import (
EdgeLayout, TooltipLayout, NodeLayout
) | 2,536 | from __future__ import annotations
def layout(
structure: ModuleInvocationStructure, cache: Optional[dict] = None
| from __future__ import annotations
def layout(
structure: ModuleInvocationStructure, cache: Optional[dict] = None | ) -> tuple[NodeLayout, dict]: | 9 | 2023-11-13 05:56:04+00:00 | 4k |
namin/llm-verified-with-monte-carlo-tree-search | run_ppo_block.py | [
{
"identifier": "Node",
"path": "montecarlo/node.py",
"snippet": "class Node:\n def __init__(self, state):\n self.state = state\n self.win_value = 0\n self.policy_value = None\n self.visits = 0\n self.parent = None\n self.children = []\n self.expanded ... | import ppo
import torch
from montecarlo.node import Node
from montecarlo.montecarlo import MonteCarlo
from lang import score_func, can_be_solution, find_largest_new_block
from prompts import prompt, expansion_count, min_lines, check_func
from common import limit_depth, max_completion_depth
from cmdline import args | 1,991 |
n_iter = args.n_iter
# n_iter = 10
class GenNode:
def __init__(self, text, gens):
self.text = text
self.gens = gens
def reinforce(gens, reward):
rewards = [torch.tensor(reward)]
for query_tensors, response_tensors in gens:
ppo.trainer_step(query_tensors, response_tensors, rewards)
def generate_complete(old_text, montecarlo, gens, current_completion_depth=1):
if current_completion_depth >= max_completion_depth:
return None
(text, gen) = ppo.generate(old_text)
score = score_func(text)
if score is None or score < 0:
code = find_largest_new_block(old_text, text)
print("Found code block:", code)
if code is not None:
text = text[0 : text.index("```")] + "```\n" + code # hack
score = 1.0
# fallthrough
else:
if score is None:
gens.append(gen)
return generate_complete(
text, montecarlo, gens, current_completion_depth + 1
)
else:
reinforce([gen], score)
return None
else:
gens.append(gen)
reinforce(gens, score)
node = Node(GenNode(text, gens))
|
n_iter = args.n_iter
# n_iter = 10
class GenNode:
def __init__(self, text, gens):
self.text = text
self.gens = gens
def reinforce(gens, reward):
rewards = [torch.tensor(reward)]
for query_tensors, response_tensors in gens:
ppo.trainer_step(query_tensors, response_tensors, rewards)
def generate_complete(old_text, montecarlo, gens, current_completion_depth=1):
if current_completion_depth >= max_completion_depth:
return None
(text, gen) = ppo.generate(old_text)
score = score_func(text)
if score is None or score < 0:
code = find_largest_new_block(old_text, text)
print("Found code block:", code)
if code is not None:
text = text[0 : text.index("```")] + "```\n" + code # hack
score = 1.0
# fallthrough
else:
if score is None:
gens.append(gen)
return generate_complete(
text, montecarlo, gens, current_completion_depth + 1
)
else:
reinforce([gen], score)
return None
else:
gens.append(gen)
reinforce(gens, score)
node = Node(GenNode(text, gens)) | if can_be_solution(text, min_lines, check_func): | 3 | 2023-11-11 19:56:04+00:00 | 4k |
BraveGroup/Drive-WM | src/diffusers/utils/testing_utils.py | [
{
"identifier": "BACKENDS_MAPPING",
"path": "src/diffusers/utils/import_utils.py",
"snippet": "BACKENDS_MAPPING = OrderedDict(\n [\n (\"bs4\", (is_bs4_available, BS4_IMPORT_ERROR)),\n (\"flax\", (is_flax_available, FLAX_IMPORT_ERROR)),\n (\"inflect\", (is_inflect_available, INFLE... | import functools
import importlib
import inspect
import io
import logging
import multiprocessing
import os
import random
import re
import struct
import sys
import tempfile
import time
import unittest
import urllib.parse
import numpy as np
import PIL.Image
import PIL.ImageOps
import requests
import torch
import cv2
from contextlib import contextmanager
from distutils.util import strtobool
from io import BytesIO, StringIO
from pathlib import Path
from typing import List, Optional, Union
from numpy.linalg import norm
from packaging import version
from .import_utils import (
BACKENDS_MAPPING,
is_compel_available,
is_flax_available,
is_note_seq_available,
is_onnx_available,
is_opencv_available,
is_peft_available,
is_torch_available,
is_torch_version,
is_torchsde_available,
is_transformers_available,
)
from .logging import get_logger
from _pytest.config import create_terminal_writer | 2,548 |
tensor_str = str(tensor.detach().cpu().flatten().to(torch.float32)).replace("\n", "")
# format is usually:
# expected_slice = np.array([-0.5713, -0.3018, -0.9814, 0.04663, -0.879, 0.76, -1.734, 0.1044, 1.161])
output_str = tensor_str.replace("tensor", f"{expected_tensor_name} = np.array")
test_file, test_class, test_fn = test_name.split("::")
test_fn = test_fn.split()[0]
with open(filename, "a") as f:
print(";".join([test_file, test_class, test_fn, output_str]), file=f)
def get_tests_dir(append_path=None):
"""
Args:
append_path: optional path to append to the tests dir path
Return:
The full path to the `tests` dir, so that the tests can be invoked from anywhere. Optionally `append_path` is
joined after the `tests` dir the former is provided.
"""
# this function caller's __file__
caller__file__ = inspect.stack()[1][1]
tests_dir = os.path.abspath(os.path.dirname(caller__file__))
while not tests_dir.endswith("tests"):
tests_dir = os.path.dirname(tests_dir)
if append_path:
return os.path.join(tests_dir, append_path)
else:
return tests_dir
def parse_flag_from_env(key, default=False):
try:
value = os.environ[key]
except KeyError:
# KEY isn't set, default to `default`.
_value = default
else:
# KEY is set, convert it to True or False.
try:
_value = strtobool(value)
except ValueError:
# More values are supported, but let's keep the message simple.
raise ValueError(f"If set, {key} must be yes or no.")
return _value
_run_slow_tests = parse_flag_from_env("RUN_SLOW", default=False)
_run_nightly_tests = parse_flag_from_env("RUN_NIGHTLY", default=False)
def floats_tensor(shape, scale=1.0, rng=None, name=None):
"""Creates a random float32 tensor"""
if rng is None:
rng = global_rng
total_dims = 1
for dim in shape:
total_dims *= dim
values = []
for _ in range(total_dims):
values.append(rng.random() * scale)
return torch.tensor(data=values, dtype=torch.float).view(shape).contiguous()
def slow(test_case):
"""
Decorator marking a test as slow.
Slow tests are skipped by default. Set the RUN_SLOW environment variable to a truthy value to run them.
"""
return unittest.skipUnless(_run_slow_tests, "test is slow")(test_case)
def nightly(test_case):
"""
Decorator marking a test that runs nightly in the diffusers CI.
Slow tests are skipped by default. Set the RUN_NIGHTLY environment variable to a truthy value to run them.
"""
return unittest.skipUnless(_run_nightly_tests, "test is nightly")(test_case)
def require_torch(test_case):
"""
Decorator marking a test that requires PyTorch. These tests are skipped when PyTorch isn't installed.
"""
return unittest.skipUnless(is_torch_available(), "test requires PyTorch")(test_case)
def require_torch_2(test_case):
"""
Decorator marking a test that requires PyTorch 2. These tests are skipped when it isn't installed.
"""
return unittest.skipUnless(is_torch_available() and is_torch_version(">=", "2.0.0"), "test requires PyTorch 2")(
test_case
)
def require_torch_gpu(test_case):
"""Decorator marking a test that requires CUDA and PyTorch."""
return unittest.skipUnless(is_torch_available() and torch_device == "cuda", "test requires PyTorch+CUDA")(
test_case
)
def skip_mps(test_case):
"""Decorator marking a test to skip if torch_device is 'mps'"""
return unittest.skipUnless(torch_device != "mps", "test requires non 'mps' device")(test_case)
def require_flax(test_case):
"""
Decorator marking a test that requires JAX & Flax. These tests are skipped when one / both are not installed
"""
|
global_rng = random.Random()
logger = get_logger(__name__)
_required_peft_version = is_peft_available() and version.parse(
version.parse(importlib.metadata.version("peft")).base_version
) > version.parse("0.5")
_required_transformers_version = is_transformers_available() and version.parse(
version.parse(importlib.metadata.version("transformers")).base_version
) > version.parse("4.33")
USE_PEFT_BACKEND = _required_peft_version and _required_transformers_version
if is_torch_available():
if "DIFFUSERS_TEST_DEVICE" in os.environ:
torch_device = os.environ["DIFFUSERS_TEST_DEVICE"]
try:
# try creating device to see if provided device is valid
_ = torch.device(torch_device)
except RuntimeError as e:
raise RuntimeError(
f"Unknown testing device specified by environment variable `DIFFUSERS_TEST_DEVICE`: {torch_device}"
) from e
logger.info(f"torch_device overrode to {torch_device}")
else:
torch_device = "cuda" if torch.cuda.is_available() else "cpu"
is_torch_higher_equal_than_1_12 = version.parse(
version.parse(torch.__version__).base_version
) >= version.parse("1.12")
if is_torch_higher_equal_than_1_12:
# Some builds of torch 1.12 don't have the mps backend registered. See #892 for more details
mps_backend_registered = hasattr(torch.backends, "mps")
torch_device = "mps" if (mps_backend_registered and torch.backends.mps.is_available()) else torch_device
def torch_all_close(a, b, *args, **kwargs):
if not is_torch_available():
raise ValueError("PyTorch needs to be installed to use this function.")
if not torch.allclose(a, b, *args, **kwargs):
assert False, f"Max diff is absolute {(a - b).abs().max()}. Diff tensor is {(a - b).abs()}."
return True
def numpy_cosine_similarity_distance(a, b):
similarity = np.dot(a, b) / (norm(a) * norm(b))
distance = 1.0 - similarity.mean()
return distance
def print_tensor_test(tensor, filename="test_corrections.txt", expected_tensor_name="expected_slice"):
test_name = os.environ.get("PYTEST_CURRENT_TEST")
if not torch.is_tensor(tensor):
tensor = torch.from_numpy(tensor)
tensor_str = str(tensor.detach().cpu().flatten().to(torch.float32)).replace("\n", "")
# format is usually:
# expected_slice = np.array([-0.5713, -0.3018, -0.9814, 0.04663, -0.879, 0.76, -1.734, 0.1044, 1.161])
output_str = tensor_str.replace("tensor", f"{expected_tensor_name} = np.array")
test_file, test_class, test_fn = test_name.split("::")
test_fn = test_fn.split()[0]
with open(filename, "a") as f:
print(";".join([test_file, test_class, test_fn, output_str]), file=f)
def get_tests_dir(append_path=None):
"""
Args:
append_path: optional path to append to the tests dir path
Return:
The full path to the `tests` dir, so that the tests can be invoked from anywhere. Optionally `append_path` is
joined after the `tests` dir the former is provided.
"""
# this function caller's __file__
caller__file__ = inspect.stack()[1][1]
tests_dir = os.path.abspath(os.path.dirname(caller__file__))
while not tests_dir.endswith("tests"):
tests_dir = os.path.dirname(tests_dir)
if append_path:
return os.path.join(tests_dir, append_path)
else:
return tests_dir
def parse_flag_from_env(key, default=False):
try:
value = os.environ[key]
except KeyError:
# KEY isn't set, default to `default`.
_value = default
else:
# KEY is set, convert it to True or False.
try:
_value = strtobool(value)
except ValueError:
# More values are supported, but let's keep the message simple.
raise ValueError(f"If set, {key} must be yes or no.")
return _value
_run_slow_tests = parse_flag_from_env("RUN_SLOW", default=False)
_run_nightly_tests = parse_flag_from_env("RUN_NIGHTLY", default=False)
def floats_tensor(shape, scale=1.0, rng=None, name=None):
"""Creates a random float32 tensor"""
if rng is None:
rng = global_rng
total_dims = 1
for dim in shape:
total_dims *= dim
values = []
for _ in range(total_dims):
values.append(rng.random() * scale)
return torch.tensor(data=values, dtype=torch.float).view(shape).contiguous()
def slow(test_case):
"""
Decorator marking a test as slow.
Slow tests are skipped by default. Set the RUN_SLOW environment variable to a truthy value to run them.
"""
return unittest.skipUnless(_run_slow_tests, "test is slow")(test_case)
def nightly(test_case):
"""
Decorator marking a test that runs nightly in the diffusers CI.
Slow tests are skipped by default. Set the RUN_NIGHTLY environment variable to a truthy value to run them.
"""
return unittest.skipUnless(_run_nightly_tests, "test is nightly")(test_case)
def require_torch(test_case):
"""
Decorator marking a test that requires PyTorch. These tests are skipped when PyTorch isn't installed.
"""
return unittest.skipUnless(is_torch_available(), "test requires PyTorch")(test_case)
def require_torch_2(test_case):
"""
Decorator marking a test that requires PyTorch 2. These tests are skipped when it isn't installed.
"""
return unittest.skipUnless(is_torch_available() and is_torch_version(">=", "2.0.0"), "test requires PyTorch 2")(
test_case
)
def require_torch_gpu(test_case):
"""Decorator marking a test that requires CUDA and PyTorch."""
return unittest.skipUnless(is_torch_available() and torch_device == "cuda", "test requires PyTorch+CUDA")(
test_case
)
def skip_mps(test_case):
"""Decorator marking a test to skip if torch_device is 'mps'"""
return unittest.skipUnless(torch_device != "mps", "test requires non 'mps' device")(test_case)
def require_flax(test_case):
"""
Decorator marking a test that requires JAX & Flax. These tests are skipped when one / both are not installed
""" | return unittest.skipUnless(is_flax_available(), "test requires JAX & Flax")(test_case) | 2 | 2023-11-18 01:40:55+00:00 | 4k |
basnijholt/unidep | unidep/_dependencies_parsing.py | [
{
"identifier": "Platform",
"path": "unidep/platform_definitions.py",
"snippet": "VALID_SELECTORS = get_args(Selector)\nPEP508_MARKERS = {\n \"linux-64\": \"sys_platform == 'linux' and platform_machine == 'x86_64'\",\n \"linux-aarch64\": \"sys_platform == 'linux' and platform_machine == 'aarch64'\... | import hashlib
import os
import sys
import tomllib
import tomli as tomllib
import tomli_w
from collections import defaultdict
from pathlib import Path
from typing import TYPE_CHECKING, Any, NamedTuple
from ruamel.yaml import YAML
from ruamel.yaml.comments import CommentedMap, CommentedSeq
from unidep.platform_definitions import Platform, Spec, platforms_from_selector
from unidep.utils import (
dependencies_filename,
is_pip_installable,
parse_package_str,
selector_from_comment,
unidep_configured_in_toml,
warn,
)
from typing import Literal
from typing_extensions import Literal | 3,492 |
def _parse_dependency(
dependency: str,
dependencies: CommentedMap,
index_or_key: int | str,
which: Literal["conda", "pip", "both"],
identifier: int,
ignore_pins: list[str],
overwrite_pins: dict[str, str | None],
skip_dependencies: list[str],
) -> list[Spec]:
name, pin, selector = parse_package_str(dependency)
if name in ignore_pins:
pin = None
if name in skip_dependencies:
return []
if name in overwrite_pins:
pin = overwrite_pins[name]
comment = (
_extract_first_comment(dependencies, index_or_key)
if isinstance(dependencies, (CommentedMap, CommentedSeq))
else None
)
if comment and selector is None:
selector = selector_from_comment(comment)
identifier_hash = _identifier(identifier, selector)
if which == "both":
return [
Spec(name, "conda", pin, identifier_hash, selector),
Spec(name, "pip", pin, identifier_hash, selector),
]
return [Spec(name, which, pin, identifier_hash, selector)]
class ParsedRequirements(NamedTuple):
"""Requirements with comments."""
channels: list[str]
platforms: list[Platform]
requirements: dict[str, list[Spec]]
class Requirements(NamedTuple):
"""Requirements as CommentedSeq."""
# mypy doesn't support CommentedSeq[str], so we use list[str] instead.
channels: list[str] # actually a CommentedSeq[str]
conda: list[str] # actually a CommentedSeq[str]
pip: list[str] # actually a CommentedSeq[str]
def _parse_overwrite_pins(overwrite_pins: list[str]) -> dict[str, str | None]:
"""Parse overwrite pins."""
result = {}
for overwrite_pin in overwrite_pins:
pkg = parse_package_str(overwrite_pin)
result[pkg.name] = pkg.pin
return result
def _load(p: Path, yaml: YAML) -> dict[str, Any]:
if p.suffix == ".toml":
if not HAS_TOML: # pragma: no cover
msg = (
"❌ No toml support found in your Python installation."
" If you are using unidep from `pyproject.toml` and this"
" error occurs during installation, make sure you add"
'\n\n[build-system]\nrequires = [..., "unidep[toml]"]\n\n'
" Otherwise, please install it with `pip install tomli`."
)
raise ImportError(msg)
with p.open("rb") as f:
return tomllib.load(f)["tool"]["unidep"]
with p.open() as f:
return yaml.load(f)
def _get_local_dependencies(data: dict[str, Any]) -> list[str]:
"""Get `local_dependencies` from a `requirements.yaml` or `pyproject.toml` file."""
if "local_dependencies" in data:
return data["local_dependencies"]
if "includes" in data:
warn(
"⚠️ You are using `includes` in `requirements.yaml` or `pyproject.toml`"
" `[unidep.tool]` which is deprecated since 0.42.0 and has been renamed to"
" `local_dependencies`.",
category=DeprecationWarning,
stacklevel=2,
)
return data["includes"]
return []
def parse_requirements( # noqa: PLR0912
*paths: Path,
ignore_pins: list[str] | None = None,
overwrite_pins: list[str] | None = None,
skip_dependencies: list[str] | None = None,
verbose: bool = False,
) -> ParsedRequirements:
"""Parse a list of `requirements.yaml` or `pyproject.toml` files."""
ignore_pins = ignore_pins or []
skip_dependencies = skip_dependencies or []
overwrite_pins_map = _parse_overwrite_pins(overwrite_pins or [])
requirements: dict[str, list[Spec]] = defaultdict(list)
channels: set[str] = set()
platforms: set[Platform] = set()
datas = []
seen: set[Path] = set()
yaml = YAML(typ="rt")
for p in paths:
if verbose:
print(f"📄 Parsing `{p}`")
data = _load(p, yaml)
datas.append(data)
seen.add(p.resolve())
# Handle "local_dependencies" (or old name "includes", changed in 0.42.0)
for include in _get_local_dependencies(data):
try:
| """unidep - Unified Conda and Pip requirements management.
This module provides parsing of `requirements.yaml` and `pyproject.toml` files.
"""
from __future__ import annotations
if TYPE_CHECKING:
if sys.version_info >= (3, 8):
else: # pragma: no cover
try: # pragma: no cover
if sys.version_info >= (3, 11):
else:
HAS_TOML = True
except ImportError: # pragma: no cover
HAS_TOML = False
def find_requirements_files(
base_dir: str | Path = ".",
depth: int = 1,
*,
verbose: bool = False,
) -> list[Path]:
"""Scan a directory for `requirements.yaml` and `pyproject.toml` files."""
base_path = Path(base_dir)
found_files = []
# Define a helper function to recursively scan directories
def _scan_dir(path: Path, current_depth: int) -> None:
if verbose:
print(f"🔍 Scanning in `{path}` at depth {current_depth}")
if current_depth > depth:
return
for child in path.iterdir():
if child.is_dir():
_scan_dir(child, current_depth + 1)
elif child.name == "requirements.yaml":
found_files.append(child)
if verbose:
print(f'🔍 Found `"requirements.yaml"` at `{child}`')
elif child.name == "pyproject.toml" and unidep_configured_in_toml(child):
if verbose:
print(f'🔍 Found `"pyproject.toml"` with dependencies at `{child}`')
found_files.append(child)
_scan_dir(base_path, 0)
return sorted(found_files)
def _extract_first_comment(
commented_map: CommentedMap,
index_or_key: int | str,
) -> str | None:
"""Extract the first comment from a CommentedMap."""
comments = commented_map.ca.items.get(index_or_key, None)
if comments is None:
return None
comment_strings = next(
c.value.split("\n")[0].rstrip().lstrip() for c in comments if c is not None
)
if not comment_strings:
# empty string
return None
return "".join(comment_strings)
def _identifier(identifier: int, selector: str | None) -> str:
"""Return a unique identifier based on the comment."""
platforms = None if selector is None else tuple(platforms_from_selector(selector))
data_str = f"{identifier}-{platforms}"
# Hash using SHA256 and take the first 8 characters for a shorter hash
return hashlib.sha256(data_str.encode()).hexdigest()[:8]
def _parse_dependency(
dependency: str,
dependencies: CommentedMap,
index_or_key: int | str,
which: Literal["conda", "pip", "both"],
identifier: int,
ignore_pins: list[str],
overwrite_pins: dict[str, str | None],
skip_dependencies: list[str],
) -> list[Spec]:
name, pin, selector = parse_package_str(dependency)
if name in ignore_pins:
pin = None
if name in skip_dependencies:
return []
if name in overwrite_pins:
pin = overwrite_pins[name]
comment = (
_extract_first_comment(dependencies, index_or_key)
if isinstance(dependencies, (CommentedMap, CommentedSeq))
else None
)
if comment and selector is None:
selector = selector_from_comment(comment)
identifier_hash = _identifier(identifier, selector)
if which == "both":
return [
Spec(name, "conda", pin, identifier_hash, selector),
Spec(name, "pip", pin, identifier_hash, selector),
]
return [Spec(name, which, pin, identifier_hash, selector)]
class ParsedRequirements(NamedTuple):
"""Requirements with comments."""
channels: list[str]
platforms: list[Platform]
requirements: dict[str, list[Spec]]
class Requirements(NamedTuple):
"""Requirements as CommentedSeq."""
# mypy doesn't support CommentedSeq[str], so we use list[str] instead.
channels: list[str] # actually a CommentedSeq[str]
conda: list[str] # actually a CommentedSeq[str]
pip: list[str] # actually a CommentedSeq[str]
def _parse_overwrite_pins(overwrite_pins: list[str]) -> dict[str, str | None]:
"""Parse overwrite pins."""
result = {}
for overwrite_pin in overwrite_pins:
pkg = parse_package_str(overwrite_pin)
result[pkg.name] = pkg.pin
return result
def _load(p: Path, yaml: YAML) -> dict[str, Any]:
if p.suffix == ".toml":
if not HAS_TOML: # pragma: no cover
msg = (
"❌ No toml support found in your Python installation."
" If you are using unidep from `pyproject.toml` and this"
" error occurs during installation, make sure you add"
'\n\n[build-system]\nrequires = [..., "unidep[toml]"]\n\n'
" Otherwise, please install it with `pip install tomli`."
)
raise ImportError(msg)
with p.open("rb") as f:
return tomllib.load(f)["tool"]["unidep"]
with p.open() as f:
return yaml.load(f)
def _get_local_dependencies(data: dict[str, Any]) -> list[str]:
"""Get `local_dependencies` from a `requirements.yaml` or `pyproject.toml` file."""
if "local_dependencies" in data:
return data["local_dependencies"]
if "includes" in data:
warn(
"⚠️ You are using `includes` in `requirements.yaml` or `pyproject.toml`"
" `[unidep.tool]` which is deprecated since 0.42.0 and has been renamed to"
" `local_dependencies`.",
category=DeprecationWarning,
stacklevel=2,
)
return data["includes"]
return []
def parse_requirements( # noqa: PLR0912
*paths: Path,
ignore_pins: list[str] | None = None,
overwrite_pins: list[str] | None = None,
skip_dependencies: list[str] | None = None,
verbose: bool = False,
) -> ParsedRequirements:
"""Parse a list of `requirements.yaml` or `pyproject.toml` files."""
ignore_pins = ignore_pins or []
skip_dependencies = skip_dependencies or []
overwrite_pins_map = _parse_overwrite_pins(overwrite_pins or [])
requirements: dict[str, list[Spec]] = defaultdict(list)
channels: set[str] = set()
platforms: set[Platform] = set()
datas = []
seen: set[Path] = set()
yaml = YAML(typ="rt")
for p in paths:
if verbose:
print(f"📄 Parsing `{p}`")
data = _load(p, yaml)
datas.append(data)
seen.add(p.resolve())
# Handle "local_dependencies" (or old name "includes", changed in 0.42.0)
for include in _get_local_dependencies(data):
try: | requirements_path = dependencies_filename(p.parent / include).resolve() | 1 | 2023-11-16 04:23:01+00:00 | 4k |
BAAI-DCAI/SegVol | network/model.py | [
{
"identifier": "select_points",
"path": "utils/monai_inferers_utils.py",
"snippet": "def select_points(preds, num_positive_extra=4, num_negative_extra=0, fix_extra_point_num=None):\n spacial_dim = 3\n points = torch.zeros((0, 3))\n labels = torch.zeros((0))\n pos_thred = 0.9\n neg_thred ... | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import random
from transformers import AutoTokenizer, CLIPTextModel, CLIPTextConfig
from utils.monai_inferers_utils import select_points, generate_box
from utils.loss import BCELoss, BinaryDiceLoss
from torch.cuda.amp import autocast | 1,893 |
#%% set up model
class SegVol(nn.Module):
def __init__(self,
image_encoder,
mask_decoder,
prompt_encoder,
clip_ckpt,
roi_size,
patch_size,
test_mode=False,
):
super().__init__()
self.image_encoder = image_encoder
self.mask_decoder = mask_decoder
self.prompt_encoder = prompt_encoder
self.text_encoder = TextEncoder(clip_ckpt)
self.feat_shape = np.array(roi_size)/np.array(patch_size)
self.test_mode = test_mode
self.dice_loss = BinaryDiceLoss().cuda()
|
#%% set up model
class SegVol(nn.Module):
def __init__(self,
image_encoder,
mask_decoder,
prompt_encoder,
clip_ckpt,
roi_size,
patch_size,
test_mode=False,
):
super().__init__()
self.image_encoder = image_encoder
self.mask_decoder = mask_decoder
self.prompt_encoder = prompt_encoder
self.text_encoder = TextEncoder(clip_ckpt)
self.feat_shape = np.array(roi_size)/np.array(patch_size)
self.test_mode = test_mode
self.dice_loss = BinaryDiceLoss().cuda() | self.bce_loss = BCELoss().cuda() | 2 | 2023-11-10 08:25:37+00:00 | 4k |
xk-huang/segment-caption-anything | scripts/tools/build_annotation_db.py | [
{
"identifier": "Arguments",
"path": "src/arguments.py",
"snippet": "class Arguments:\n defaults: List[Any] = field(default_factory=lambda: defaults)\n\n training: SCASeq2SeqTrainingArguments = field(default_factory=lambda: SCASeq2SeqTrainingArguments(output_dir=\"?\"))\n\n # NOTE(xiaoke): to o... | import sys
import base64
import io
import json
import logging
import os
import os.path as osp
import datasets
import hydra
import numpy as np
import tqdm
import pycocotools.mask
import logging
import torch
import sqlite3
import json
from hydra.core.hydra_config import HydraConfig
from hydra.core.utils import configure_log
from omegaconf import DictConfig, OmegaConf
from PIL import Image
from utils.git_utils import TSVWriter
from src.arguments import Arguments, global_setup
from hydra.utils import instantiate
from transformers import set_seed, AutoTokenizer
from datasets import interleave_datasets, concatenate_datasets
from src.train import prepare_datasets
from torch.utils.data import IterableDataset, DataLoader
from itertools import islice | 2,852 | # TODO: extract images from refcoco series
sys.path.append(".")
logger = logging.getLogger(__name__)
@hydra.main(version_base="1.3", config_path="../../src/conf", config_name="conf")
def main(args: Arguments):
logger.warning(f"Turn no_cuda = True.")
args.training.no_cuda = True
# NOTE: ddp is initialized in _setup_devices class in `transformers/training_args.py`
| # TODO: extract images from refcoco series
sys.path.append(".")
logger = logging.getLogger(__name__)
@hydra.main(version_base="1.3", config_path="../../src/conf", config_name="conf")
def main(args: Arguments):
logger.warning(f"Turn no_cuda = True.")
args.training.no_cuda = True
# NOTE: ddp is initialized in _setup_devices class in `transformers/training_args.py` | args, training_args, _ = global_setup(args) | 1 | 2023-11-17 14:10:41+00:00 | 4k |
theroyallab/tabbyAPI | OAI/utils_oai.py | [
{
"identifier": "ChatCompletionMessage",
"path": "OAI/types/chat_completion.py",
"snippet": "class ChatCompletionMessage(BaseModel):\n role: Optional[str] = None\n content: Optional[str] = None"
},
{
"identifier": "ChatCompletionRespChoice",
"path": "OAI/types/chat_completion.py",
... | import pathlib
from typing import Optional
from OAI.types.chat_completion import (
ChatCompletionMessage,
ChatCompletionRespChoice,
ChatCompletionStreamChunk,
ChatCompletionResponse,
ChatCompletionStreamChoice,
)
from OAI.types.completion import CompletionResponse, CompletionRespChoice
from OAI.types.common import UsageStats
from OAI.types.lora import LoraList, LoraCard
from OAI.types.model import ModelList, ModelCard
from utils import unwrap | 1,604 | """ Utility functions for the OpenAI server. """
def create_completion_response(
text: str,
prompt_tokens: int,
completion_tokens: int,
model_name: Optional[str],
):
"""Create a completion response from the provided text."""
choice = CompletionRespChoice(finish_reason="Generated", text=text)
response = CompletionResponse(
choices=[choice],
model=unwrap(model_name, ""),
usage=UsageStats(
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
total_tokens=prompt_tokens + completion_tokens,
),
)
return response
def create_chat_completion_response(
text: str,
prompt_tokens: int,
completion_tokens: int,
model_name: Optional[str],
):
"""Create a chat completion response from the provided text."""
message = ChatCompletionMessage(role="assistant", content=text)
choice = ChatCompletionRespChoice(finish_reason="Generated", message=message)
response = ChatCompletionResponse(
choices=[choice],
model=unwrap(model_name, ""),
usage=UsageStats(
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
total_tokens=prompt_tokens + completion_tokens,
),
)
return response
def create_chat_completion_stream_chunk(
const_id: str,
text: Optional[str] = None,
model_name: Optional[str] = None,
finish_reason: Optional[str] = None,
):
"""Create a chat completion stream chunk from the provided text."""
if finish_reason:
message = {}
else:
message = ChatCompletionMessage(role="assistant", content=text)
# The finish reason can be None
choice = ChatCompletionStreamChoice(finish_reason=finish_reason, delta=message)
chunk = ChatCompletionStreamChunk(
id=const_id, choices=[choice], model=unwrap(model_name, "")
)
return chunk
def get_model_list(model_path: pathlib.Path, draft_model_path: Optional[str] = None):
"""Get the list of models from the provided path."""
# Convert the provided draft model path to a pathlib path for
# equality comparisons
if draft_model_path:
draft_model_path = pathlib.Path(draft_model_path).resolve()
model_card_list = ModelList()
for path in model_path.iterdir():
# Don't include the draft models path
if path.is_dir() and path != draft_model_path:
model_card = ModelCard(id=path.name)
model_card_list.data.append(model_card) # pylint: disable=no-member
return model_card_list
def get_lora_list(lora_path: pathlib.Path):
"""Get the list of Lora cards from the provided path."""
lora_list = LoraList()
for path in lora_path.iterdir():
if path.is_dir():
| """ Utility functions for the OpenAI server. """
def create_completion_response(
text: str,
prompt_tokens: int,
completion_tokens: int,
model_name: Optional[str],
):
"""Create a completion response from the provided text."""
choice = CompletionRespChoice(finish_reason="Generated", text=text)
response = CompletionResponse(
choices=[choice],
model=unwrap(model_name, ""),
usage=UsageStats(
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
total_tokens=prompt_tokens + completion_tokens,
),
)
return response
def create_chat_completion_response(
text: str,
prompt_tokens: int,
completion_tokens: int,
model_name: Optional[str],
):
"""Create a chat completion response from the provided text."""
message = ChatCompletionMessage(role="assistant", content=text)
choice = ChatCompletionRespChoice(finish_reason="Generated", message=message)
response = ChatCompletionResponse(
choices=[choice],
model=unwrap(model_name, ""),
usage=UsageStats(
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
total_tokens=prompt_tokens + completion_tokens,
),
)
return response
def create_chat_completion_stream_chunk(
const_id: str,
text: Optional[str] = None,
model_name: Optional[str] = None,
finish_reason: Optional[str] = None,
):
"""Create a chat completion stream chunk from the provided text."""
if finish_reason:
message = {}
else:
message = ChatCompletionMessage(role="assistant", content=text)
# The finish reason can be None
choice = ChatCompletionStreamChoice(finish_reason=finish_reason, delta=message)
chunk = ChatCompletionStreamChunk(
id=const_id, choices=[choice], model=unwrap(model_name, "")
)
return chunk
def get_model_list(model_path: pathlib.Path, draft_model_path: Optional[str] = None):
"""Get the list of models from the provided path."""
# Convert the provided draft model path to a pathlib path for
# equality comparisons
if draft_model_path:
draft_model_path = pathlib.Path(draft_model_path).resolve()
model_card_list = ModelList()
for path in model_path.iterdir():
# Don't include the draft models path
if path.is_dir() and path != draft_model_path:
model_card = ModelCard(id=path.name)
model_card_list.data.append(model_card) # pylint: disable=no-member
return model_card_list
def get_lora_list(lora_path: pathlib.Path):
"""Get the list of Lora cards from the provided path."""
lora_list = LoraList()
for path in lora_path.iterdir():
if path.is_dir(): | lora_card = LoraCard(id=path.name) | 9 | 2023-11-10 05:54:02+00:00 | 4k |
zorazrw/filco | get_inputs.py | [
{
"identifier": "has_answer",
"path": "eval.py",
"snippet": "def has_answer(text: str, answers: list[str]) -> float:\n \"\"\"Check if text contains any of the answers.\"\"\"\n return float(any([(ans.lower() in text.lower()) for ans in answers]))"
},
{
"identifier": "load_dataset",
"pat... | import argparse
from eval import has_answer
from utils import load_dataset, write_dataset | 2,291 |
# ICT Example Creation Functions
def get_ict_io(
example: dict,
in_context_examples: list[dict],
input_list: list[str],
output_list: list[str],
no_prefix: bool = False,
filter_criteria: str = "strinc",
n_contexts: int = 1,
num_sents: int = None,
threshold: float = None,
question_prefix: str = "question",
answer_prefix: str = "answer",
context_prefix: str = "context",
) -> tuple[str, str]:
"""Get input and output texts with in-context examples."""
ict_io_list = []
for example in in_context_examples:
itext, otext = get_example_io(
example,
input_list,
output_list,
n_contexts=n_contexts,
num_sents=num_sents,
threshold=threshold,
filter_criteria=filter_criteria,
question_prefix=question_prefix,
answer_prefix=answer_prefix,
context_prefix=context_prefix,
)
ict_io_list.append("\n".join([itext, otext]))
input_text, output_text = get_example_io(
example,
input_list,
output_list,
n_contexts=n_contexts,
num_sents=num_sents,
threshold=threshold,
filter_criteria=filter_criteria,
question_prefix=question_prefix,
answer_prefix=answer_prefix,
context_prefix=context_prefix,
)
if no_prefix:
prefix = ""
else:
input_text_list = []
for ii in input_list:
if (ii == "filtered") or (ii == "passage"):
input_text_list.append(context_prefix)
elif ii == "question":
input_text_list.append(question_prefix)
else:
input_text_list.append(ii)
output_text_list = []
for oo in output_list:
if oo == "filtered":
output_text_list.append(
f"most helpful sentence in the {context_prefix}"
)
elif oo == "answer":
if answer_prefix == "response":
output_text_list.append("response to the query")
elif answer_prefix == "judgement":
output_text_list.append("judgement to the claim")
else:
output_text_list.append("answer to the question")
if len(output_text_list) == 1:
prefix = f"Given the {input_text_list}, predict the {output_text_list[0]}."
else:
prefix = (
f"Given the {input_text_list}, "
f"predict the {output_text_list[0]} first, "
f"then predict the {output_text_list[1]}."
)
if question_prefix == "claim" and answer_prefix == "judgement":
prefix += (
"('SUPPORTS' or 'REFUTES')\n"
"If the 'context' does not provide enough information "
"to judge the claim, use your own knowledge instead."
)
full_input_text = "\n\n".join([prefix] + ict_io_list + [input_text])
return full_input_text.strip(), output_text.strip()
def main():
"""Run the main data processing function."""
dataset = load_dataset(args.dataset_path)
N = len(dataset)
def get_examples(index: int, n_examples: int) -> list[int]:
"""Get indices of in-context examples."""
indices = [(index - i - 1) % N for i in range(n_examples)]
return [dataset[i] for i in indices]
procset = []
for idx, ex in enumerate(dataset):
input_text, output_text = get_ict_io(
example=ex,
in_context_examples=get_examples(idx, args.n_examples),
input_list=args.input_list,
output_list=args.output_list,
no_prefix=args.no_prefix,
filter_criteria=args.filter_criteria,
n_contexts=args.n_contexts,
num_sents=args.num_sents,
threshold=args.threshold,
question_prefix=args.question_prefix,
answer_prefix=args.answer_prefix,
context_prefix=args.context_prefix,
)
procset.append({"input": input_text, "output": output_text})
| """Create I/O to Evaluate/Train Models.
Default I/O for Context Filtering: [i] question context [o] sent
Default I/O for Output Generation: [i] sent question [o] answer
"""
# Individual Components
QUESTION_PREFIX = "question"
ANSWER_PREFIX = "answer"
CONTEXT_PREFIX = "context"
prefix_format = "{}: {}"
def get_question(
example: dict,
question_prefix: str = QUESTION_PREFIX,
add_prefix: bool = True,
) -> str:
"""Get the question from the example."""
question = example["question"]
if add_prefix:
question = prefix_format.format(question_prefix, question)
return question
def get_context(
example: dict,
n_contexts: int = 1,
context_prefix: str = CONTEXT_PREFIX,
add_prefix: bool = True,
) -> str:
"""Get the context from the example."""
context_list = [ctx["text"] for ctx in example["ctxs"][:n_contexts]]
context = '\n'.join(context_list)
if add_prefix:
context = prefix_format.format(context_prefix, context)
return context
def get_sent(
example: dict,
n_contexts: int = 1,
criteria: str = "strinc",
num_sents: int = None,
threshold: float = None,
) -> str:
"""Get the best sentence from contexts."""
sentences = []
if threshold is None:
threshold = 0.0
for idx in range(n_contexts):
if criteria == "strinc":
for sent_dict in example["ctxs"][idx]["sentences"]:
if sent_dict[criteria] is True:
sentences.append(sent_dict["text"])
# break
else:
if num_sents is None:
num_sents = len(example["ctxs"][idx]["sentences"])
ctx_sents = sorted(
example["ctxs"][idx]["sentences"],
key=lambda x: -x[criteria]
)
sentences.extend([
s["text"] for s in ctx_sents[: num_sents]
if s[criteria] >= threshold
])
sent_text = " ".join(sentences)
return sent_text
def get_answer(
example: dict,
answer_prefix: str = ANSWER_PREFIX,
find_best: bool = True,
n_contexts: int = 1,
add_prefix: bool = True,
) -> str:
"""Find the answer index that best possibly in the context.
Using the top-1 retrieved context by default.
"""
if find_best:
for idx in range(n_contexts):
context = example["ctxs"][idx]["text"].lower()
answer_exists = [
has_answer(context, [ans.lower()]) for ans in example["answers"]
]
if any(answer_exists):
answer_text = example["answers"][answer_exists.index(True)]
break
else:
answer_text = example["answers"][0]
else:
answer_text = example["answers"][0]
if add_prefix:
answer_text = prefix_format.format(answer_prefix, answer_text)
return answer_text
# Example Creation Functions
def get_example_io(
example: dict,
input_list: list[str],
output_list: list[str],
n_contexts: int = 1,
num_sents: int = None,
threshold: float = None,
filter_criteria: str = "strinc",
question_prefix: str = "question",
answer_prefix: str = "answer",
context_prefix: str = "context",
) -> tuple[str, str]:
"""Get input and output texts for the given example."""
input_text_list, output_text_list = [], []
for inp in input_list:
if inp == "question":
input_text_list.append(
get_question(example, question_prefix=question_prefix)
)
elif inp == "passage":
input_text_list.append(get_context(example, n_contexts, context_prefix=context_prefix))
elif inp == "filtered":
sent = get_sent(
example=example,
n_contexts=n_contexts,
criteria=filter_criteria,
num_sents=num_sents,
threshold=threshold,
)
if not sent.strip():
sent = get_context(example, context_prefix=context_prefix)
else:
sent = prefix_format.format(CONTEXT_PREFIX, sent)
input_text_list.append(sent)
else:
raise ValueError(f"Invalid input type {inp}")
input_text = "\n".join(input_text_list)
for out in output_list:
if out == "answer":
output_text_list.append(
get_answer(
example,
answer_prefix=answer_prefix,
n_contexts=n_contexts,
)
)
elif out == "filtered":
output_text_list.append(
get_sent(
example=example,
n_contexts=n_contexts,
criteria=filter_criteria,
num_sents=num_sents,
threshold=threshold,
)
)
else:
raise ValueError(f"Invalid output type {out}")
output_text = "\n".join(output_text_list)
return input_text, output_text
# ICT Example Creation Functions
def get_ict_io(
example: dict,
in_context_examples: list[dict],
input_list: list[str],
output_list: list[str],
no_prefix: bool = False,
filter_criteria: str = "strinc",
n_contexts: int = 1,
num_sents: int = None,
threshold: float = None,
question_prefix: str = "question",
answer_prefix: str = "answer",
context_prefix: str = "context",
) -> tuple[str, str]:
"""Get input and output texts with in-context examples."""
ict_io_list = []
for example in in_context_examples:
itext, otext = get_example_io(
example,
input_list,
output_list,
n_contexts=n_contexts,
num_sents=num_sents,
threshold=threshold,
filter_criteria=filter_criteria,
question_prefix=question_prefix,
answer_prefix=answer_prefix,
context_prefix=context_prefix,
)
ict_io_list.append("\n".join([itext, otext]))
input_text, output_text = get_example_io(
example,
input_list,
output_list,
n_contexts=n_contexts,
num_sents=num_sents,
threshold=threshold,
filter_criteria=filter_criteria,
question_prefix=question_prefix,
answer_prefix=answer_prefix,
context_prefix=context_prefix,
)
if no_prefix:
prefix = ""
else:
input_text_list = []
for ii in input_list:
if (ii == "filtered") or (ii == "passage"):
input_text_list.append(context_prefix)
elif ii == "question":
input_text_list.append(question_prefix)
else:
input_text_list.append(ii)
output_text_list = []
for oo in output_list:
if oo == "filtered":
output_text_list.append(
f"most helpful sentence in the {context_prefix}"
)
elif oo == "answer":
if answer_prefix == "response":
output_text_list.append("response to the query")
elif answer_prefix == "judgement":
output_text_list.append("judgement to the claim")
else:
output_text_list.append("answer to the question")
if len(output_text_list) == 1:
prefix = f"Given the {input_text_list}, predict the {output_text_list[0]}."
else:
prefix = (
f"Given the {input_text_list}, "
f"predict the {output_text_list[0]} first, "
f"then predict the {output_text_list[1]}."
)
if question_prefix == "claim" and answer_prefix == "judgement":
prefix += (
"('SUPPORTS' or 'REFUTES')\n"
"If the 'context' does not provide enough information "
"to judge the claim, use your own knowledge instead."
)
full_input_text = "\n\n".join([prefix] + ict_io_list + [input_text])
return full_input_text.strip(), output_text.strip()
def main():
"""Run the main data processing function."""
dataset = load_dataset(args.dataset_path)
N = len(dataset)
def get_examples(index: int, n_examples: int) -> list[int]:
"""Get indices of in-context examples."""
indices = [(index - i - 1) % N for i in range(n_examples)]
return [dataset[i] for i in indices]
procset = []
for idx, ex in enumerate(dataset):
input_text, output_text = get_ict_io(
example=ex,
in_context_examples=get_examples(idx, args.n_examples),
input_list=args.input_list,
output_list=args.output_list,
no_prefix=args.no_prefix,
filter_criteria=args.filter_criteria,
n_contexts=args.n_contexts,
num_sents=args.num_sents,
threshold=args.threshold,
question_prefix=args.question_prefix,
answer_prefix=args.answer_prefix,
context_prefix=args.context_prefix,
)
procset.append({"input": input_text, "output": output_text})
| write_dataset(args.output_path, procset) | 2 | 2023-11-14 21:18:30+00:00 | 4k |
ShipBit/wingman-ai | gui/sections/context_runner.py | [
{
"identifier": "Icon",
"path": "gui/components/icon.py",
"snippet": "class Icon(ctk.CTkImage):\n def __init__(self, icon: str, size: int | tuple[int, int]=50, themed=True):\n if isinstance(size, int):\n size = (size, size)\n\n icon_dir = path.join(path.abspath(path.dirname(_... | import customtkinter as ctk
from gui.components.icon import Icon
from gui.components.wingmen_list import WingmenList
from services.printr import Printr | 3,145 |
printr = Printr()
class ContextRunner(ctk.CTkFrame):
def __init__(self, master, context="", **kwargs):
super().__init__(master, **kwargs)
self.core = master.core
self.core.load_context(context)
self.status_var = ctk.StringVar(self, "Inactive", "status")
tower = self.core.tower
auto_run = self.core.config_manager.gui_config.get("auto-run", "off") == "on"
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(3, weight=1)
context_title = (
context.title().replace("_", " ").strip() if context else "Default"
)
self.title = ctk.CTkLabel(
self,
text=context_title,
font=("TkHeadingFont", 20, "bold"),
text_color="#EB154D",
)
self.title.grid(row=0, column=0, padx=20, pady=10, sticky="w")
# TODO: Make this a component
self.status = ctk.CTkLabel(
self,
textvariable=self.status_var,
anchor="w",
fg_color=("grey70", "grey30"),
corner_radius=10,
width=65,
pady=3,
)
self.status.grid(row=0, column=0, padx=20, pady=10, sticky="e")
self.status_icon_active = Icon("state_active", 16, False)
self.status_icon_inactive = Icon("state_inactive", 16, False)
self.status_led = ctk.CTkLabel(
self, image=self.status_icon_inactive, text="", fg_color="transparent"
)
self.status_led.grid(row=0, column=0, padx=95, pady=10, sticky="e")
wingmen = []
if tower:
wingmen = tower.get_wingmen()
|
printr = Printr()
class ContextRunner(ctk.CTkFrame):
def __init__(self, master, context="", **kwargs):
super().__init__(master, **kwargs)
self.core = master.core
self.core.load_context(context)
self.status_var = ctk.StringVar(self, "Inactive", "status")
tower = self.core.tower
auto_run = self.core.config_manager.gui_config.get("auto-run", "off") == "on"
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(3, weight=1)
context_title = (
context.title().replace("_", " ").strip() if context else "Default"
)
self.title = ctk.CTkLabel(
self,
text=context_title,
font=("TkHeadingFont", 20, "bold"),
text_color="#EB154D",
)
self.title.grid(row=0, column=0, padx=20, pady=10, sticky="w")
# TODO: Make this a component
self.status = ctk.CTkLabel(
self,
textvariable=self.status_var,
anchor="w",
fg_color=("grey70", "grey30"),
corner_radius=10,
width=65,
pady=3,
)
self.status.grid(row=0, column=0, padx=20, pady=10, sticky="e")
self.status_icon_active = Icon("state_active", 16, False)
self.status_icon_inactive = Icon("state_inactive", 16, False)
self.status_led = ctk.CTkLabel(
self, image=self.status_icon_inactive, text="", fg_color="transparent"
)
self.status_led.grid(row=0, column=0, padx=95, pady=10, sticky="e")
wingmen = []
if tower:
wingmen = tower.get_wingmen() | self.wingmen_list = WingmenList(self, wingmen=wingmen) | 1 | 2023-11-15 09:36:06+00:00 | 4k |
OliverMao/FlaskAutoApiBuilder | Faab/FaabFunction.py | [
{
"identifier": "login_required",
"path": "Faab/FaabJWT.py",
"snippet": "def login_required(f):\n \"\"\"\n 使用functools模块的wraps装饰内部函数\n \"\"\"\n\n @functools.wraps(f)\n def wrapper(*args, **kwargs):\n try:\n if g.username == -1:\n # print('error1')\n ... | import json
import pandas as pd
import io
from functools import wraps
from flasgger import swag_from
from flask import request, g, send_file
from sqlalchemy import and_
from sqlalchemy.orm import class_mapper
from flask_sqlalchemy import SQLAlchemy
from Faab.FaabJWT import login_required
from Faab.extensions import db | 2,096 | return wrapper
# noinspection ALL
def check_request_turn(func):
# noinspection PyTypeChecker
@wraps(func)
def wrapper(self, *args, **kwargs):
form = request.json
need_update = form.get('need_update')
condition = form.get('condition')
for key, value in condition.items():
if key == "_Own":
continue
exists = self.check_parameter_exists(key)
if not exists:
return {'error': 'a参数错误', 'code': 11}
for key, value in need_update.items():
exists = self.check_parameter_exists(key)
if not exists:
return {'error': 'b参数错误', 'code': 10}
# noinspection PyCallingNonCallable
return func(self, *args, **kwargs)
return wrapper
def check_parameter_exists(self, parameter):
mapper = class_mapper(self.model)
return hasattr(mapper.column_attrs, parameter)
@swag_from('swag_config/get.yml')
def get(self):
params = dict(request.args)
_Not_Filter = False
if '_Not_Filter' in params:
_Not_Filter = json.loads(params.pop('_Not_Filter'))
if '_Own' in params:
name = params.get('_Own')
params[name] = g.username
params.pop('_Own')
if '_Pagination' not in params:
if '_Desc' not in params:
query = self.model.query.filter_by(is_delete=0)
else:
query = self.model.query.filter_by(is_delete=0).order_by(self.model.id.desc())
params.pop('_Desc')
filters = []
if '_Search' in params:
key = params.pop('_Search')
value = params.pop('_Search_value')
filters.append(getattr(self.model, key).like('%' + value + '%'))
for key, value in params.items():
filters.append(getattr(self.model, key) == value)
if _Not_Filter != False:
filters.append(getattr(self.model, _Not_Filter['key']) != _Not_Filter['value'])
if filters:
query = query.filter(and_(*filters))
lists = query.all()
return self.list_to_return(lists)
else:
params.pop('_Pagination')
page = int(params.pop('page'))
per_page = int(params.pop('per_page'))
if '_Desc' not in params:
query = self.model.query.filter_by(is_delete=0)
else:
query = self.model.query.filter_by(is_delete=0).order_by(self.model.id.desc())
params.pop('_Desc')
filters = []
if '_Search' in params:
key = params.pop('_Search')
value = params.pop('_Search_value')
filters.append(getattr(self.model, key).like('%' + value + '%'))
for key, value in params.items():
filters.append(getattr(self.model, key) == value)
if _Not_Filter != False:
filters.append(getattr(self.model, _Not_Filter['key']) != _Not_Filter['value'])
if filters:
query = query.filter(and_(*filters))
lists = query.paginate(page=page, per_page=per_page, error_out=False)
items = lists.items
has_next = lists.has_next
has_prev = lists.has_prev
total = lists.total
pages = lists.pages
return {'items': self.list_to_return(items), 'has_next': has_next, 'has_prev': has_prev, 'total': total,
'pages': pages}
@swag_from('swag_config/get_one.yml')
def get_one(self):
params = dict(request.args)
if '_Own' in params:
name = params.get('_Own')
params[name] = g.username
params.pop('_Own')
filters = []
query = self.model.query.filter_by(is_delete=0)
for key, value in params.items():
filters.append(getattr(self.model, key) == value)
if filters:
query = query.filter(and_(*filters))
item = query.first()
return self.one_to_return(item)
@swag_from('swag_config/post.yml')
def post(self):
sets = request.json
new_item = self.model()
for key, value in sets.items():
setattr(new_item, key, value)
try:
|
# ......
class AutoUrl:
def __init__(self, add_url_list):
for i in add_url_list:
AutoDB(i["model"], i["bp"], i["url_prefix"])
class AutoDB:
model = {}
bp = object
url_name = ""
def __init__(self, model, bp, url_name):
self.model = model
self.bp = bp
self.url_name = url_name
self.bp.add_url_rule('/' + url_name + '/get', endpoint=bp.name + url_name + 'get',
view_func=self.get,
methods=['GET'])
self.bp.add_url_rule('/' + url_name + '/get_one', endpoint=bp.name + url_name + 'get_one',
view_func=self.get_one,
methods=['GET'])
self.bp.add_url_rule('/' + url_name + '/post', endpoint=bp.name + url_name + 'post',
view_func=self.post,
methods=['POST'])
self.bp.add_url_rule('/' + url_name + '/delete/<int:one_or_list>/<int:true_del_or_false_del>',
endpoint=bp.name + url_name + 'delete', view_func=self.delete,
methods=['POST'])
self.bp.add_url_rule('/' + url_name + '/put', endpoint=bp.name + url_name + 'put',
view_func=self.put,
methods=['POST'])
self.bp.add_url_rule('/' + url_name + '/export', endpoint=bp.name + url_name + 'export',
view_func=self.export,
methods=['POST'])
def list_to_return(self, get_list):
"""
FuncName:列表转返回值
Parameter:查询出的结果
Return:Http返回值
"""
result = []
for item in get_list:
data = {}
for col in class_mapper(self.model).mapped_table.c:
value = str(getattr(item, col.name))
if value != 'None':
data[col.name] = value
else:
continue
result.append(data)
return result
def one_to_return(self, info):
"""
FuncName:单个数据转返回值
Parameter:查询出的结果
Return:Http返回值
"""
data = {}
if info:
for col in class_mapper(self.model).mapped_table.c:
value = str(getattr(info, col.name))
if value != 'None':
data[col.name] = value
else:
continue
return data
else:
return {}
# noinspection ALL
def check_request_delete(func):
# noinspection PyTypeChecker
@wraps(func)
def wrapper(self, *args, **kwargs):
params = request.json
for key, value in params.items():
exists = self.check_parameter_exists(key)
if not exists:
return {'error': '参数错误', 'code': 0}
# noinspection PyCallingNonCallable
return func(self, *args, **kwargs)
return wrapper
# noinspection ALL
def check_request_export(func):
# noinspection PyTypeChecker
@wraps(func)
def wrapper(self, *args, **kwargs):
form = request.json
need_export = form.get('need_export')
condition = form.get('condition')
for key, value in condition.items():
if key == "_Own" or key == "_Price":
continue
exists = self.check_parameter_exists(key)
if not exists:
return {'error': 'a参数错误', 'code': 11}
for key, value in need_export.items():
exists = self.check_parameter_exists(key)
if not exists:
return {'error': 'b参数错误', 'code': 10}
# noinspection PyCallingNonCallable
return func(self, *args, **kwargs)
return wrapper
# noinspection ALL
def check_request_turn(func):
# noinspection PyTypeChecker
@wraps(func)
def wrapper(self, *args, **kwargs):
form = request.json
need_update = form.get('need_update')
condition = form.get('condition')
for key, value in condition.items():
if key == "_Own":
continue
exists = self.check_parameter_exists(key)
if not exists:
return {'error': 'a参数错误', 'code': 11}
for key, value in need_update.items():
exists = self.check_parameter_exists(key)
if not exists:
return {'error': 'b参数错误', 'code': 10}
# noinspection PyCallingNonCallable
return func(self, *args, **kwargs)
return wrapper
def check_parameter_exists(self, parameter):
mapper = class_mapper(self.model)
return hasattr(mapper.column_attrs, parameter)
@swag_from('swag_config/get.yml')
def get(self):
params = dict(request.args)
_Not_Filter = False
if '_Not_Filter' in params:
_Not_Filter = json.loads(params.pop('_Not_Filter'))
if '_Own' in params:
name = params.get('_Own')
params[name] = g.username
params.pop('_Own')
if '_Pagination' not in params:
if '_Desc' not in params:
query = self.model.query.filter_by(is_delete=0)
else:
query = self.model.query.filter_by(is_delete=0).order_by(self.model.id.desc())
params.pop('_Desc')
filters = []
if '_Search' in params:
key = params.pop('_Search')
value = params.pop('_Search_value')
filters.append(getattr(self.model, key).like('%' + value + '%'))
for key, value in params.items():
filters.append(getattr(self.model, key) == value)
if _Not_Filter != False:
filters.append(getattr(self.model, _Not_Filter['key']) != _Not_Filter['value'])
if filters:
query = query.filter(and_(*filters))
lists = query.all()
return self.list_to_return(lists)
else:
params.pop('_Pagination')
page = int(params.pop('page'))
per_page = int(params.pop('per_page'))
if '_Desc' not in params:
query = self.model.query.filter_by(is_delete=0)
else:
query = self.model.query.filter_by(is_delete=0).order_by(self.model.id.desc())
params.pop('_Desc')
filters = []
if '_Search' in params:
key = params.pop('_Search')
value = params.pop('_Search_value')
filters.append(getattr(self.model, key).like('%' + value + '%'))
for key, value in params.items():
filters.append(getattr(self.model, key) == value)
if _Not_Filter != False:
filters.append(getattr(self.model, _Not_Filter['key']) != _Not_Filter['value'])
if filters:
query = query.filter(and_(*filters))
lists = query.paginate(page=page, per_page=per_page, error_out=False)
items = lists.items
has_next = lists.has_next
has_prev = lists.has_prev
total = lists.total
pages = lists.pages
return {'items': self.list_to_return(items), 'has_next': has_next, 'has_prev': has_prev, 'total': total,
'pages': pages}
@swag_from('swag_config/get_one.yml')
def get_one(self):
params = dict(request.args)
if '_Own' in params:
name = params.get('_Own')
params[name] = g.username
params.pop('_Own')
filters = []
query = self.model.query.filter_by(is_delete=0)
for key, value in params.items():
filters.append(getattr(self.model, key) == value)
if filters:
query = query.filter(and_(*filters))
item = query.first()
return self.one_to_return(item)
@swag_from('swag_config/post.yml')
def post(self):
sets = request.json
new_item = self.model()
for key, value in sets.items():
setattr(new_item, key, value)
try: | db.session.add(new_item) | 1 | 2023-11-10 09:25:44+00:00 | 4k |
mattyamonaca/LCM_i2i_PoC | config.py | [
{
"identifier": "get_pipe",
"path": "lcm.py",
"snippet": "def get_pipe(config):\n vae_model_path = config.vae_model_path.get()\n vae_model_path = vae_model_path.replace(\"\\\\\", \"/\")\n LoRA_model_path = config.LoRA_model_path.get()\n LoRA_model_path = LoRA_model_path.replace(\"\\\\\", \"/... | from diffusers.utils import load_image
from tkinter import ttk
from lcm import get_pipe, LCM_run
from capture import ScreenCapture
import tkinter as tk
import threading | 2,270 |
class ConfigWindow:
def __init__(self):
master = tk.Tk()
self.run_thread = None
self.running = False
self.master = master
master.title("Configuration")
master.geometry("400x500") # ウィンドウサイズを設定
master.attributes("-topmost", True) # ウィンドウサイズを最前列固定
style = ttk.Style()
style.configure("TLabel", font=("Arial", 12))
style.configure("TEntry", padding=5)
style.configure("TButton", padding=5, font=("Arial", 10))
# LCMモデル名
ttk.Label(master, text="LCMモデル名").grid(row=0, column=0, padx=10, pady=10, sticky="w")
self.lcm_model_name = tk.StringVar(value="latent-consistency/lcm-lora-sdv1-5")
ttk.Entry(master, textvariable=self.lcm_model_name, width=30).grid(row=0, column=1, padx=10, pady=10)
# 生成モデル名
ttk.Label(master, text="生成モデル名").grid(row=1, column=0, padx=10, pady=10, sticky="w")
self.generation_model_name = tk.StringVar(value="852wa/SDHK")
ttk.Entry(master, textvariable=self.generation_model_name, width=30).grid(row=1, column=1, padx=10, pady=10)
# vaeモデルパス
ttk.Label(master, text="vaeモデルパス").grid(row=2, column=0, padx=10, pady=10, sticky="w")
self.vae_model_path = tk.StringVar()
ttk.Entry(master, textvariable=self.vae_model_path, width=30).grid(row=2, column=1, padx=10, pady=10)
# LoRAモデルパス
ttk.Label(master, text="LoRAモデルパス").grid(row=3, column=0, padx=10, pady=10, sticky="w")
self.LoRA_model_path = tk.StringVar()
ttk.Entry(master, textvariable=self.LoRA_model_path, width=30).grid(row=3, column=1, padx=10, pady=10)
# LoRAstrength
ttk.Label(master, text="LoRAstrength").grid(row=4, column=0, padx=10, pady=10, sticky="w")
self.LoRAstrength = tk.StringVar(value=1.0)
ttk.Entry(master, textvariable=self.LoRAstrength, width=30).grid(row=4, column=1, padx=10, pady=10)
# プロンプト
ttk.Label(master, text="プロンプト").grid(row=5, column=0, padx=10, pady=10, sticky="w")
self.prompt = tk.StringVar()
ttk.Entry(master, textvariable=self.prompt, width=30).grid(row=5, column=1, padx=10, pady=10)
# strength
ttk.Label(master, text="strength").grid(row=6, column=0, padx=10, pady=10, sticky="w")
self.strength = tk.StringVar(value=0.75)
ttk.Entry(master, textvariable=self.strength, width=30).grid(row=6, column=1, padx=10, pady=10)
# num_inference_steps
ttk.Label(master, text="num_inference_steps").grid(row=7, column=0, padx=10, pady=10, sticky="w")
self.num_inference_steps = tk.StringVar(value=8)
ttk.Entry(master, textvariable=self.num_inference_steps, width=30).grid(row=7, column=1, padx=10, pady=10)
#画面キャプチャ
capture_button = ttk.Button(master, text="キャプチャ開始", command=self.capture_screen)
capture_button.grid(row=8, column=0, columnspan=2, padx=10, pady=10, sticky="ew")
#パラメータ更新
capture_button = ttk.Button(master, text="パラメータ更新", command=self.update_param)
capture_button.grid(row=9, column=0, columnspan=2, padx=10, pady=10, sticky="ew")
def update_param(self):
self.num_inference_steps_value = int(self.num_inference_steps.get())
self.strength_value = float(self.strength.get())
self.LoRAstrength_value = float(self.LoRAstrength.get())
def capture_screen(self):
if self.run_thread is not None:
self.running = False
self.run_thread.join()
|
class ConfigWindow:
def __init__(self):
master = tk.Tk()
self.run_thread = None
self.running = False
self.master = master
master.title("Configuration")
master.geometry("400x500") # ウィンドウサイズを設定
master.attributes("-topmost", True) # ウィンドウサイズを最前列固定
style = ttk.Style()
style.configure("TLabel", font=("Arial", 12))
style.configure("TEntry", padding=5)
style.configure("TButton", padding=5, font=("Arial", 10))
# LCMモデル名
ttk.Label(master, text="LCMモデル名").grid(row=0, column=0, padx=10, pady=10, sticky="w")
self.lcm_model_name = tk.StringVar(value="latent-consistency/lcm-lora-sdv1-5")
ttk.Entry(master, textvariable=self.lcm_model_name, width=30).grid(row=0, column=1, padx=10, pady=10)
# 生成モデル名
ttk.Label(master, text="生成モデル名").grid(row=1, column=0, padx=10, pady=10, sticky="w")
self.generation_model_name = tk.StringVar(value="852wa/SDHK")
ttk.Entry(master, textvariable=self.generation_model_name, width=30).grid(row=1, column=1, padx=10, pady=10)
# vaeモデルパス
ttk.Label(master, text="vaeモデルパス").grid(row=2, column=0, padx=10, pady=10, sticky="w")
self.vae_model_path = tk.StringVar()
ttk.Entry(master, textvariable=self.vae_model_path, width=30).grid(row=2, column=1, padx=10, pady=10)
# LoRAモデルパス
ttk.Label(master, text="LoRAモデルパス").grid(row=3, column=0, padx=10, pady=10, sticky="w")
self.LoRA_model_path = tk.StringVar()
ttk.Entry(master, textvariable=self.LoRA_model_path, width=30).grid(row=3, column=1, padx=10, pady=10)
# LoRAstrength
ttk.Label(master, text="LoRAstrength").grid(row=4, column=0, padx=10, pady=10, sticky="w")
self.LoRAstrength = tk.StringVar(value=1.0)
ttk.Entry(master, textvariable=self.LoRAstrength, width=30).grid(row=4, column=1, padx=10, pady=10)
# プロンプト
ttk.Label(master, text="プロンプト").grid(row=5, column=0, padx=10, pady=10, sticky="w")
self.prompt = tk.StringVar()
ttk.Entry(master, textvariable=self.prompt, width=30).grid(row=5, column=1, padx=10, pady=10)
# strength
ttk.Label(master, text="strength").grid(row=6, column=0, padx=10, pady=10, sticky="w")
self.strength = tk.StringVar(value=0.75)
ttk.Entry(master, textvariable=self.strength, width=30).grid(row=6, column=1, padx=10, pady=10)
# num_inference_steps
ttk.Label(master, text="num_inference_steps").grid(row=7, column=0, padx=10, pady=10, sticky="w")
self.num_inference_steps = tk.StringVar(value=8)
ttk.Entry(master, textvariable=self.num_inference_steps, width=30).grid(row=7, column=1, padx=10, pady=10)
#画面キャプチャ
capture_button = ttk.Button(master, text="キャプチャ開始", command=self.capture_screen)
capture_button.grid(row=8, column=0, columnspan=2, padx=10, pady=10, sticky="ew")
#パラメータ更新
capture_button = ttk.Button(master, text="パラメータ更新", command=self.update_param)
capture_button.grid(row=9, column=0, columnspan=2, padx=10, pady=10, sticky="ew")
def update_param(self):
self.num_inference_steps_value = int(self.num_inference_steps.get())
self.strength_value = float(self.strength.get())
self.LoRAstrength_value = float(self.LoRAstrength.get())
def capture_screen(self):
if self.run_thread is not None:
self.running = False
self.run_thread.join()
| self.screen_capture = ScreenCapture() | 2 | 2023-11-17 08:10:27+00:00 | 4k |
jeromeleong/mirrors-zhile-io-pandora | src/pandora/turbo/chat.py | [
{
"identifier": "Conversations",
"path": "src/pandora/turbo/base.py",
"snippet": "class Conversations:\n def __init__(self):\n self.__data = []\n\n def list(self, offset, limit):\n return len(self.__data), self.__data[offset: limit]\n\n def clear(self):\n self.__data = []\n... | import json
from datetime import datetime as dt
from os import getenv
from requests import Response
from .base import Conversations, UserPrompt, Prompt, SystemPrompt
from ..openai.api import ChatCompletion
from ..openai.token import gpt_num_tokens | 3,159 | return resp.json()
def clear_conversations(self, raw=False, token=None):
def __shadow():
self.__get_conversations(token).clear()
result = {
'success': True
}
return self.__wrap_response(result)
resp = __shadow()
if raw:
return resp
return resp.json()['success']
def del_conversation(self, conversation_id, raw=False, token=None):
def __shadow():
conversations = self.__get_conversations(token)
try:
conversation = conversations.guard_get(conversation_id)
except Exception as e:
return self.__out_error(str(e), 404)
conversations.delete(conversation)
result = {
'success': True
}
return self.__wrap_response(result)
resp = __shadow()
if raw:
return resp
if resp.status_code != 200:
raise Exception('delete conversation failed: ' + resp.json()['detail'])
return resp.json()['success']
def gen_conversation_title(self, conversation_id, model, message_id, raw=False, token=None):
def __shadow():
conversation = self.__get_conversations(token).get(conversation_id)
if not conversation:
return self.__out_error('Conversation not found', 404)
if 'New chat' != conversation.title:
message = {
'message': 'Conversation {} already has title \'{}\''.format(conversation_id, conversation.title)
}
return self.__wrap_response(message)
messages = conversation.get_messages_directly(message_id)
messages.append({'role': 'user', 'content': self.TITLE_PROMPT})
status, header, generator = self.api.request(self.get_access_token(token), model, messages, False)
last_ok, last = self.__get_completion(status, next(generator))
if not last_ok:
return self.__out_error(last['detail'], status)
conversation.set_title(last.strip('"'))
result = {
'title': conversation.title
}
return self.__wrap_response(result)
resp = __shadow()
if raw:
return resp
if resp.status_code != 200:
raise Exception('generate title failed: ' + resp.text)
return resp.json()['title']
def set_conversation_title(self, conversation_id, title, raw=False, token=None):
def __shadow():
try:
conversation = self.__get_conversations(token).guard_get(conversation_id)
except Exception as e:
return self.__out_error(str(e), 404)
conversation.set_title(title)
result = {
'success': True
}
return self.__wrap_response(result)
resp = __shadow()
if raw:
return resp
if resp.status_code != 200:
raise Exception('update conversation failed: ' + resp.json()['detail'])
return resp.json()['success']
def talk(self, content, model, message_id, parent_message_id, conversation_id=None, stream=True, token=None):
system_prompt = None
if conversation_id:
conversation = self.__get_conversations(token).get(conversation_id)
if not conversation:
return self.__out_error_stream('Conversation not found', 404)
parent = conversation.get_prompt(parent_message_id)
else:
conversation = self.__get_conversations(token).new()
| # -*- coding: utf-8 -*-
class TurboGPT:
DEFAULT_SYSTEM_PROMPT = 'You are ChatGPT, a large language model trained by OpenAI. ' \
'Answer as concisely as possible.\nKnowledge cutoff: 2021-09-01\n' \
'Current date: {}'.format(dt.now().strftime('%Y-%m-%d'))
TITLE_PROMPT = 'Generate a brief title for our conversation.'
MAX_TOKENS = {
'gpt-3.5-turbo': 4096,
'gpt-4': 8192,
'gpt-4-32k': 32768,
}
FAKE_TOKENS = {
'gpt-3.5-turbo': 8191,
'gpt-4': 4095,
'gpt-4-32k': 8195,
}
def __init__(self, api_keys: dict, proxy=None):
self.api_keys = api_keys
self.api_keys_key_list = list(api_keys)
self.default_api_keys_key = self.api_keys_key_list[0]
self.api = ChatCompletion(proxy)
self.conversations_map = {}
self.system_prompt = getenv('API_SYSTEM_PROMPT', self.DEFAULT_SYSTEM_PROMPT)
def __get_conversations(self, api_keys_key=None):
if api_keys_key is None:
api_keys_key = self.default_api_keys_key
if api_keys_key not in self.conversations_map:
self.conversations_map[api_keys_key] = Conversations()
return self.conversations_map[api_keys_key]
def __is_fake_api(self, token=None):
api_key = self.get_access_token(token)
return api_key.startswith('fk-') or api_key.startswith('pk-')
def get_access_token(self, token_key=None):
return self.api_keys[token_key or self.default_api_keys_key]
def list_token_keys(self):
return self.api_keys_key_list
def list_models(self, raw=False, token=None):
fake_api = self.__is_fake_api(token)
models = {
'models': [
{
'slug': 'gpt-3.5-turbo',
'max_tokens': self.FAKE_TOKENS['gpt-3.5-turbo'] if fake_api else self.MAX_TOKENS['gpt-3.5-turbo'],
'title': 'GPT-3.5',
'description': 'Turbo is the api model that powers ChatGPT',
'tags': []
},
{
'slug': 'gpt-4',
'max_tokens': self.FAKE_TOKENS['gpt-4'] if fake_api else self.MAX_TOKENS['gpt-4'],
'title': 'GPT-4',
'description': 'More capable than any GPT-3.5, able to do complex tasks, and optimized for chat',
'tags': []
},
{
'slug': 'gpt-4-32k',
'max_tokens': self.FAKE_TOKENS['gpt-4-32k'] if fake_api else self.MAX_TOKENS['gpt-4-32k'],
'title': 'GPT-4 32K',
'description': 'Same capabilities as the base gpt-4 mode but with 4x the context length',
'tags': []
}
]
}
if raw:
return self.__wrap_response(models)
return models['models']
def list_conversations(self, offset, limit, raw=False, token=None):
offset = int(offset)
limit = int(limit)
total, items = self.__get_conversations(token).list(offset, limit)
stripped = []
for item in items:
stripped.append({
'id': item.conversation_id,
'title': item.title,
'create_time': dt.utcfromtimestamp(item.create_time).isoformat(),
})
result = {'items': stripped, 'total': total, 'limit': limit, 'offset': offset}
if raw:
return self.__wrap_response(result)
return result
def get_conversation(self, conversation_id, raw=False, token=None):
def __shadow():
try:
conversation = self.__get_conversations(token).guard_get(conversation_id)
except Exception as e:
return self.__out_error(str(e), 404)
return self.__wrap_response(conversation.get_info())
resp = __shadow()
if raw:
return resp
if resp.status_code != 200:
raise Exception('get conversation failed: ' + resp.json()['detail'])
return resp.json()
def clear_conversations(self, raw=False, token=None):
def __shadow():
self.__get_conversations(token).clear()
result = {
'success': True
}
return self.__wrap_response(result)
resp = __shadow()
if raw:
return resp
return resp.json()['success']
def del_conversation(self, conversation_id, raw=False, token=None):
def __shadow():
conversations = self.__get_conversations(token)
try:
conversation = conversations.guard_get(conversation_id)
except Exception as e:
return self.__out_error(str(e), 404)
conversations.delete(conversation)
result = {
'success': True
}
return self.__wrap_response(result)
resp = __shadow()
if raw:
return resp
if resp.status_code != 200:
raise Exception('delete conversation failed: ' + resp.json()['detail'])
return resp.json()['success']
def gen_conversation_title(self, conversation_id, model, message_id, raw=False, token=None):
def __shadow():
conversation = self.__get_conversations(token).get(conversation_id)
if not conversation:
return self.__out_error('Conversation not found', 404)
if 'New chat' != conversation.title:
message = {
'message': 'Conversation {} already has title \'{}\''.format(conversation_id, conversation.title)
}
return self.__wrap_response(message)
messages = conversation.get_messages_directly(message_id)
messages.append({'role': 'user', 'content': self.TITLE_PROMPT})
status, header, generator = self.api.request(self.get_access_token(token), model, messages, False)
last_ok, last = self.__get_completion(status, next(generator))
if not last_ok:
return self.__out_error(last['detail'], status)
conversation.set_title(last.strip('"'))
result = {
'title': conversation.title
}
return self.__wrap_response(result)
resp = __shadow()
if raw:
return resp
if resp.status_code != 200:
raise Exception('generate title failed: ' + resp.text)
return resp.json()['title']
def set_conversation_title(self, conversation_id, title, raw=False, token=None):
def __shadow():
try:
conversation = self.__get_conversations(token).guard_get(conversation_id)
except Exception as e:
return self.__out_error(str(e), 404)
conversation.set_title(title)
result = {
'success': True
}
return self.__wrap_response(result)
resp = __shadow()
if raw:
return resp
if resp.status_code != 200:
raise Exception('update conversation failed: ' + resp.json()['detail'])
return resp.json()['success']
def talk(self, content, model, message_id, parent_message_id, conversation_id=None, stream=True, token=None):
system_prompt = None
if conversation_id:
conversation = self.__get_conversations(token).get(conversation_id)
if not conversation:
return self.__out_error_stream('Conversation not found', 404)
parent = conversation.get_prompt(parent_message_id)
else:
conversation = self.__get_conversations(token).new() | parent = conversation.add_prompt(Prompt(parent_message_id)) | 2 | 2023-11-12 10:31:05+00:00 | 4k |
leeyuentuen/polestar_api | custom_components/polestar_api/polestar.py | [
{
"identifier": "PolestarApiException",
"path": "custom_components/polestar_api/pypolestar/exception.py",
"snippet": "class PolestarApiException(Exception):\n \"\"\"Base class for exceptions in this module.\"\"\""
},
{
"identifier": "PolestarAuthException",
"path": "custom_components/pole... | from datetime import datetime, timedelta
from urllib3 import disable_warnings
from homeassistant.core import HomeAssistant
from homeassistant.util.unit_system import METRIC_SYSTEM, UnitSystem
from .pypolestar.exception import PolestarApiException, PolestarAuthException
from .pypolestar.polestar import PolestarApi
import logging
import httpx | 2,185 | """Polestar API for Polestar integration."""
POST_HEADER_JSON = {"Content-Type": "application/json"}
_LOGGER = logging.getLogger(__name__)
class Polestar:
"""Polestar EV integration."""
def __init__(self,
hass: HomeAssistant,
username: str,
password: str
) -> None:
self.id = None
self.name = "Polestar "
| """Polestar API for Polestar integration."""
POST_HEADER_JSON = {"Content-Type": "application/json"}
_LOGGER = logging.getLogger(__name__)
class Polestar:
"""Polestar EV integration."""
def __init__(self,
hass: HomeAssistant,
username: str,
password: str
) -> None:
self.id = None
self.name = "Polestar " | self.polestarApi = PolestarApi(username, password) | 2 | 2023-11-17 21:24:36+00:00 | 4k |
dubverse-ai/MahaTTS | tts.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 torch,glob
from maha_tts import load_diffuser,load_models,infer_tts,config
from scipy.io.wavfile import write | 1,667 |
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Using:',device)
text = 'Printing, in the only sense with which we are at present concerned, differs from most if not from all the arts and crafts represented in the Exhibition.'
langauge = 'english'
|
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Using:',device)
text = 'Printing, in the only sense with which we are at present concerned, differs from most if not from all the arts and crafts represented in the Exhibition.'
langauge = 'english' | language = torch.tensor(config.lang_index[langauge]).to(device).unsqueeze(0) | 0 | 2023-11-16 09:44:54+00:00 | 4k |
wjun0830/CGDETR | cg_detr/start_end_dataset.py | [
{
"identifier": "load_jsonl",
"path": "utils/basic_utils.py",
"snippet": "def load_jsonl(filename):\n with open(filename, \"r\") as f:\n return [json.loads(l.strip(\"\\n\")) for l in f.readlines()]"
},
{
"identifier": "l2_normalize_np_array",
"path": "utils/basic_utils.py",
"sn... | import torch
import numpy as np
import random
import logging
import torch.nn as nn
from torch.utils.data import Dataset
from tqdm import tqdm
from os.path import join, exists
from utils.basic_utils import load_jsonl, l2_normalize_np_array
from utils.tensor_utils import pad_sequences_1d
from cg_detr.span_utils import span_xx_to_cxw
from torchtext import vocab | 2,769 | 'train': ['kLxoNp-UchI', 'NyBmCxDoHJU', 'jcoYJXDG9sw', '-esJrBWj2d8'],
'val': ['E11zDS9XGzg']
},
'FM': {
'train': ['_xMr-HKMfVA', 'byxOvuiIJV0', 'VuWGsYPqAX8', 'xmEERLqJ2kU'],
'val': ['JKpqYvAdIsw']
},
'GA': {
'train': ['xxdtq8mxegs', 'i3wAGJaaktw', '0tmA_C6XwfM', '3eYKfiOEJNs'],
'val': ['Bhxk-O1Y7Ho']
},
'MS': {
'train': ['Hl-__g2gn_A', 'WG0MBPpPC6I', 'LRw_obCPUt0', '37rzWOQsNIw'],
'val': ['Yi4Ij2NM7U4']
},
'PK': {
'train': ['GsAD1KT1xo8', 'XkqCExn6_Us', 'b626MiF1ew4', 'PJrm840pAUI'],
'val': ['cjibtmSLxQ4']
},
'PR': {
'train': ['RBCABdttQmI', 'z_6gVvQb2d0', '4wU_LUjG5Ic', '91IHQYk1IQM'],
'val': ['fWutDQy1nnY']
},
'VT': {
'train': ['gzDbaEs1Rlg', 'XzYM3PfTM4w', '98MoyGZKHXc', 'AwmHb44_ouw'],
'val': ['J0nA4VgnoCo']
},
'VU': {
'train': ['akI8YFjEmUw', 'HT5vyqe0Xaw', 'vdmoEJ5YbrQ', 'xwqBXPGE9pQ'],
'val': ['sTEELN-vY30']
}
}
class StartEndDataset(Dataset):
Q_FEAT_TYPES = ["pooler_output", "last_hidden_state"]
"""One line in data loaded from data_path."
{
"qid": 7803,
"query": "Man in gray top walks from outside to inside.",
"duration": 150,
"vid": "RoripwjYFp8_360.0_510.0",
"relevant_clip_ids": [13, 14, 15, 16, 17],
"relevant_windows": [[26, 36]]
}
"""
def __init__(self, dset_name, data_path, v_feat_dirs, q_feat_dir,
q_feat_type="last_hidden_state",
max_q_l=32, max_v_l=75, data_ratio=1.0, ctx_mode="video",
normalize_v=True, normalize_t=True, load_labels=True,
clip_len=2, max_windows=5, span_loss_type="l1", txt_drop_ratio=0,
dset_domain=None):
self.dset_name = dset_name
self.data_path = data_path
self.data_ratio = data_ratio
self.v_feat_dirs = v_feat_dirs \
if isinstance(v_feat_dirs, list) else [v_feat_dirs]
self.q_feat_dir = q_feat_dir
self.q_feat_type = q_feat_type
if max_v_l == -1:
max_v_l = 100000000
if max_q_l == -1:
max_q_l = 100
self.max_q_l = max_q_l
self.max_v_l = max_v_l
self.ctx_mode = ctx_mode
self.use_tef = "tef" in ctx_mode
self.use_video = "video" in ctx_mode
self.normalize_t = normalize_t
self.normalize_v = normalize_v
self.load_labels = load_labels
self.clip_len = clip_len
self.max_windows = max_windows # maximum number of windows to use as labels
self.span_loss_type = span_loss_type
self.txt_drop_ratio = txt_drop_ratio
if "val" in data_path or "test" in data_path:
assert txt_drop_ratio == 0
# checks
assert q_feat_type in self.Q_FEAT_TYPES
# data
self.data = self.load_data()
# load specific domain data for tvsum dataset
if self.dset_name in ['tvsum', 'tvsum_sfc']:
target_domain = dset_domain
assert target_domain in ["BK", "BT", "DS", "FM", "GA", "MS", "PK", "PR", "VT", "VU"]
new_data = []
for d in self.data:
if target_domain == d['domain']:
new_data.append(d)
self.data = new_data
# load specific domain data for youtube-hl dataset
if self.dset_name == 'youtube_uni':
target_domain = dset_domain
assert target_domain in ["dog", "gymnastics", "parkour", "skating", "skiing", "surfing"]
new_data = []
for d in self.data:
if target_domain == d['domain']:
new_data.append(d)
self.data = new_data
self.use_glove = False
self.use_glove = 'vgg' in self.v_feat_dirs[0]
if self.dset_name == 'charadesSTA' and self.use_glove:
self.vocab = vocab.pretrained_aliases['glove.6B.300d']()
self.vocab.itos.extend(['<unk>'])
self.vocab.stoi['<unk>'] = self.vocab.vectors.shape[0]
self.vocab.vectors = torch.cat(
(self.vocab.vectors, torch.zeros(1, self.vocab.dim)), dim=0)
self.embedding = nn.Embedding.from_pretrained(self.vocab.vectors)
def load_data(self):
|
logger = logging.getLogger(__name__)
TVSUM_SPLITS = {
'BK': {
'train': ['WxtbjNsCQ8A', 'EE-bNr36nyA', 'oDXZc0tZe04', 'uGu_10sucQo'],
'val': ['Se3oxnaPsz0']
},
'BT': {
'train': ['eQu1rNs0an0', 'qqR6AEXwxoQ', 'EYqVtI9YWJA', 'iVt07TCkFM0'],
'val': ['JgHubY5Vw3Y']
},
'DS': {
'train': ['kLxoNp-UchI', 'NyBmCxDoHJU', 'jcoYJXDG9sw', '-esJrBWj2d8'],
'val': ['E11zDS9XGzg']
},
'FM': {
'train': ['_xMr-HKMfVA', 'byxOvuiIJV0', 'VuWGsYPqAX8', 'xmEERLqJ2kU'],
'val': ['JKpqYvAdIsw']
},
'GA': {
'train': ['xxdtq8mxegs', 'i3wAGJaaktw', '0tmA_C6XwfM', '3eYKfiOEJNs'],
'val': ['Bhxk-O1Y7Ho']
},
'MS': {
'train': ['Hl-__g2gn_A', 'WG0MBPpPC6I', 'LRw_obCPUt0', '37rzWOQsNIw'],
'val': ['Yi4Ij2NM7U4']
},
'PK': {
'train': ['GsAD1KT1xo8', 'XkqCExn6_Us', 'b626MiF1ew4', 'PJrm840pAUI'],
'val': ['cjibtmSLxQ4']
},
'PR': {
'train': ['RBCABdttQmI', 'z_6gVvQb2d0', '4wU_LUjG5Ic', '91IHQYk1IQM'],
'val': ['fWutDQy1nnY']
},
'VT': {
'train': ['gzDbaEs1Rlg', 'XzYM3PfTM4w', '98MoyGZKHXc', 'AwmHb44_ouw'],
'val': ['J0nA4VgnoCo']
},
'VU': {
'train': ['akI8YFjEmUw', 'HT5vyqe0Xaw', 'vdmoEJ5YbrQ', 'xwqBXPGE9pQ'],
'val': ['sTEELN-vY30']
}
}
class StartEndDataset(Dataset):
Q_FEAT_TYPES = ["pooler_output", "last_hidden_state"]
"""One line in data loaded from data_path."
{
"qid": 7803,
"query": "Man in gray top walks from outside to inside.",
"duration": 150,
"vid": "RoripwjYFp8_360.0_510.0",
"relevant_clip_ids": [13, 14, 15, 16, 17],
"relevant_windows": [[26, 36]]
}
"""
def __init__(self, dset_name, data_path, v_feat_dirs, q_feat_dir,
q_feat_type="last_hidden_state",
max_q_l=32, max_v_l=75, data_ratio=1.0, ctx_mode="video",
normalize_v=True, normalize_t=True, load_labels=True,
clip_len=2, max_windows=5, span_loss_type="l1", txt_drop_ratio=0,
dset_domain=None):
self.dset_name = dset_name
self.data_path = data_path
self.data_ratio = data_ratio
self.v_feat_dirs = v_feat_dirs \
if isinstance(v_feat_dirs, list) else [v_feat_dirs]
self.q_feat_dir = q_feat_dir
self.q_feat_type = q_feat_type
if max_v_l == -1:
max_v_l = 100000000
if max_q_l == -1:
max_q_l = 100
self.max_q_l = max_q_l
self.max_v_l = max_v_l
self.ctx_mode = ctx_mode
self.use_tef = "tef" in ctx_mode
self.use_video = "video" in ctx_mode
self.normalize_t = normalize_t
self.normalize_v = normalize_v
self.load_labels = load_labels
self.clip_len = clip_len
self.max_windows = max_windows # maximum number of windows to use as labels
self.span_loss_type = span_loss_type
self.txt_drop_ratio = txt_drop_ratio
if "val" in data_path or "test" in data_path:
assert txt_drop_ratio == 0
# checks
assert q_feat_type in self.Q_FEAT_TYPES
# data
self.data = self.load_data()
# load specific domain data for tvsum dataset
if self.dset_name in ['tvsum', 'tvsum_sfc']:
target_domain = dset_domain
assert target_domain in ["BK", "BT", "DS", "FM", "GA", "MS", "PK", "PR", "VT", "VU"]
new_data = []
for d in self.data:
if target_domain == d['domain']:
new_data.append(d)
self.data = new_data
# load specific domain data for youtube-hl dataset
if self.dset_name == 'youtube_uni':
target_domain = dset_domain
assert target_domain in ["dog", "gymnastics", "parkour", "skating", "skiing", "surfing"]
new_data = []
for d in self.data:
if target_domain == d['domain']:
new_data.append(d)
self.data = new_data
self.use_glove = False
self.use_glove = 'vgg' in self.v_feat_dirs[0]
if self.dset_name == 'charadesSTA' and self.use_glove:
self.vocab = vocab.pretrained_aliases['glove.6B.300d']()
self.vocab.itos.extend(['<unk>'])
self.vocab.stoi['<unk>'] = self.vocab.vectors.shape[0]
self.vocab.vectors = torch.cat(
(self.vocab.vectors, torch.zeros(1, self.vocab.dim)), dim=0)
self.embedding = nn.Embedding.from_pretrained(self.vocab.vectors)
def load_data(self): | datalist = load_jsonl(self.data_path) | 0 | 2023-11-10 12:45:25+00:00 | 4k |
WCGKING/KINGUSERBOT | Branded/plugins/pmguard.py | [
{
"identifier": "approve",
"path": "Branded/modules/data.py",
"snippet": "async def approve(user_ud: int):\n pm = await is_approved()\n pm.append(user_ud)\n await permitdb.update_one(\n {'permit': 'protection'},\n {\n '$set': {\n 'users': pm\n ... | import asyncio
from pyrogram import Client, filters
from pyrogram.enums import ChatType
from pyrogram.types import *
from .. import *
from ..modules.data import approve, disapprove, is_approved | 1,611 |
DEFAULT = """
WELCOME....
ʜɪ, ᴛʜɪꜱ ɪꜱ ᴛʜᴇ ᴋᴇᴇᴘᴇʀ ᴏꜰ ᴘʀɪᴠᴀᴛᴇ ᴍᴇꜱꜱᴀɢᴇꜱ. ᴅᴏɴ'ᴛ ꜱᴘᴀᴍ ʏᴀ ᴏʀ ɪ'ʟʟ ʙʟᴏᴄᴋ ʏᴏᴜ. ᴡᴀɪᴛ ᴜɴᴛɪʟ ᴍʏ ᴍᴀꜱᴛᴇʀ ʀᴇᴄᴇɪᴠᴇꜱ ʏᴏᴜʀ ᴍᴇꜱꜱᴀɢᴇ.ɪ ᴀᴍ ᴀɴ ᴀᴅᴠᴀɴᴄᴇᴅ ᴀɴᴅ sᴜᴘᴇʀғᴀsᴛ ᴜꜱᴇʀʙᴏᴛ ᴡɪᴛʜ 24x7 ᴀᴄᴛɪᴠᴇ » ғᴏʀ ᴛᴇʟᴇɢʀᴀᴍ ɪᴅ
"""
@app.on_message(
(
filters.private
& filters.incoming
& ~filters.service
& ~filters.me
& ~filters.bot
& ~filters.via_bot
)
)
async def pmpermit_func(client: Client, message: Message):
user_ = message.from_user
approved = await is_approved()
pmper = var.PMPERMIT
if pmper == str(False):
return True
if user_.is_bot:
return
if user_.is_self:
return
if user_.is_contact:
return
if user_.is_verified:
return
if user_.is_scam:
await message.reply_text("Imposter Detected!\nAutomatic Blocking!!!")
await client.block_user(user_.id)
return
if user_.is_support:
return
if user_.id in approved:
return
limits = var.PERMIT_LIMIT
async for m in client.get_chat_history(user_.id, limit=limits):
if m.reply_markup:
await m.delete()
if str(user_.id) in flood:
flood[str(user_.id)] += 1
else:
flood[str(user_.id)] = 1
if flood[str(user_.id)] > limits:
await message.reply_text("Spammer Detected!\nAutomatic Blocking User!!!")
if str(user_.id) in OLD_MSG:
OLD_MSG.pop(str(user_.id))
flood.update({user_.id: 0})
return await client.block_user(user_.id)
getmsg = Config.PERMIT_MSG
pm_message = DEFAULT if not getmsg else getmsg
msg_dlt = await client.send_message(
user_.id,
MSG_PERMIT.format(pm_message, flood[str(user_.id)], limits),
)
if str(user_.id) in OLD_MSG:
try:
await OLD_MSG[str(user_.id)].delete()
except BaseException:
pass
OLD_MSG[str(user_.id)] = msg_dlt
@app.on_message(commandx(["approve", "a"]))
async def pm_approve(client: Client, message: Message):
permit = await is_approved()
if message.reply_to_message:
reply = message.reply_to_message
replied_user = reply.from_user
if replied_user.is_self:
await message.edit("You can't do that to yourself.")
return
uid = replied_user.id
if uid in permit:
return await message.reply("This user already exists in the database.")
await approve(uid)
xnxx = await message.reply("Your message was received.")
if str(uid) in OLD_MSG and str(uid) in flood:
await OLD_MSG[str(uid)].delete()
flood[str(uid)] = 0
await asyncio.sleep(3)
await xnxx.delete()
else:
aname = message.chat
if not aname.type == ChatType.PRIVATE:
await message.reply(
"You're not currently in PM and you haven't replied to someone's messages."
)
return
uid = aname.id
if uid in permit:
return await message.reply("This user already exists in the database")
await approve(uid)
xnxx = await message.reply("Your message was received.")
try:
if str(uid) in OLD_MSG and str(uid) in flood:
await OLD_MSG[str(uid)].delete()
flood[str(uid)] = 0
except BaseException:
pass
await asyncio.sleep(3)
await xnxx.delete()
@app.on_message(commandx(["disapprove", "da"]))
async def pm_disapprove(client: Client, message: Message):
permit = await is_approved()
if message.reply_to_message:
reply = message.reply_to_message
replied_user = reply.from_user
if replied_user.is_self:
await message.reply("You can't do that to yourself.")
return
uid = replied_user.id
if uid not in permit:
return await message.reply("User does not exist in database.")
|
MSG_PERMIT = """
PM_SECURITY BRANDED-USERBOT
{}
await message.reply_photo="https://te.legra.ph/file/11cfa74175b590014bd16.jpg"
▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂
⍟ You have {}/{} warning!!!
"""
DEFAULT = """
WELCOME....
ʜɪ, ᴛʜɪꜱ ɪꜱ ᴛʜᴇ ᴋᴇᴇᴘᴇʀ ᴏꜰ ᴘʀɪᴠᴀᴛᴇ ᴍᴇꜱꜱᴀɢᴇꜱ. ᴅᴏɴ'ᴛ ꜱᴘᴀᴍ ʏᴀ ᴏʀ ɪ'ʟʟ ʙʟᴏᴄᴋ ʏᴏᴜ. ᴡᴀɪᴛ ᴜɴᴛɪʟ ᴍʏ ᴍᴀꜱᴛᴇʀ ʀᴇᴄᴇɪᴠᴇꜱ ʏᴏᴜʀ ᴍᴇꜱꜱᴀɢᴇ.ɪ ᴀᴍ ᴀɴ ᴀᴅᴠᴀɴᴄᴇᴅ ᴀɴᴅ sᴜᴘᴇʀғᴀsᴛ ᴜꜱᴇʀʙᴏᴛ ᴡɪᴛʜ 24x7 ᴀᴄᴛɪᴠᴇ » ғᴏʀ ᴛᴇʟᴇɢʀᴀᴍ ɪᴅ
"""
@app.on_message(
(
filters.private
& filters.incoming
& ~filters.service
& ~filters.me
& ~filters.bot
& ~filters.via_bot
)
)
async def pmpermit_func(client: Client, message: Message):
user_ = message.from_user
approved = await is_approved()
pmper = var.PMPERMIT
if pmper == str(False):
return True
if user_.is_bot:
return
if user_.is_self:
return
if user_.is_contact:
return
if user_.is_verified:
return
if user_.is_scam:
await message.reply_text("Imposter Detected!\nAutomatic Blocking!!!")
await client.block_user(user_.id)
return
if user_.is_support:
return
if user_.id in approved:
return
limits = var.PERMIT_LIMIT
async for m in client.get_chat_history(user_.id, limit=limits):
if m.reply_markup:
await m.delete()
if str(user_.id) in flood:
flood[str(user_.id)] += 1
else:
flood[str(user_.id)] = 1
if flood[str(user_.id)] > limits:
await message.reply_text("Spammer Detected!\nAutomatic Blocking User!!!")
if str(user_.id) in OLD_MSG:
OLD_MSG.pop(str(user_.id))
flood.update({user_.id: 0})
return await client.block_user(user_.id)
getmsg = Config.PERMIT_MSG
pm_message = DEFAULT if not getmsg else getmsg
msg_dlt = await client.send_message(
user_.id,
MSG_PERMIT.format(pm_message, flood[str(user_.id)], limits),
)
if str(user_.id) in OLD_MSG:
try:
await OLD_MSG[str(user_.id)].delete()
except BaseException:
pass
OLD_MSG[str(user_.id)] = msg_dlt
@app.on_message(commandx(["approve", "a"]))
async def pm_approve(client: Client, message: Message):
permit = await is_approved()
if message.reply_to_message:
reply = message.reply_to_message
replied_user = reply.from_user
if replied_user.is_self:
await message.edit("You can't do that to yourself.")
return
uid = replied_user.id
if uid in permit:
return await message.reply("This user already exists in the database.")
await approve(uid)
xnxx = await message.reply("Your message was received.")
if str(uid) in OLD_MSG and str(uid) in flood:
await OLD_MSG[str(uid)].delete()
flood[str(uid)] = 0
await asyncio.sleep(3)
await xnxx.delete()
else:
aname = message.chat
if not aname.type == ChatType.PRIVATE:
await message.reply(
"You're not currently in PM and you haven't replied to someone's messages."
)
return
uid = aname.id
if uid in permit:
return await message.reply("This user already exists in the database")
await approve(uid)
xnxx = await message.reply("Your message was received.")
try:
if str(uid) in OLD_MSG and str(uid) in flood:
await OLD_MSG[str(uid)].delete()
flood[str(uid)] = 0
except BaseException:
pass
await asyncio.sleep(3)
await xnxx.delete()
@app.on_message(commandx(["disapprove", "da"]))
async def pm_disapprove(client: Client, message: Message):
permit = await is_approved()
if message.reply_to_message:
reply = message.reply_to_message
replied_user = reply.from_user
if replied_user.is_self:
await message.reply("You can't do that to yourself.")
return
uid = replied_user.id
if uid not in permit:
return await message.reply("User does not exist in database.") | await disapprove(uid) | 1 | 2023-11-14 13:24:26+00:00 | 4k |
kudelskisecurity/fuzzomatic | fuzzomatic/approaches/functions.py | [
{
"identifier": "prompts",
"path": "fuzzomatic/tools/prompts.py",
"snippet": "def load_file_contents(path):\ndef readme_prompt(readme):\ndef fix_prompt(code_snippet, error):\ndef example_prompt(example_code):\ndef unit_test_prompt(test_source_code, use_statements):\ndef unit_test_prompt_with_additional_... | from jinja2 import Template
from fuzzomatic.tools import prompts
from fuzzomatic.approaches.common import llm_attempt_fix_error
from fuzzomatic.tools.cargo_doc import parse_cargo_doc_json, generate_cargo_doc_json
from fuzzomatic.tools.constants import DEFAULT_TARGET_NAME
from fuzzomatic.tools.utils import write_fuzz_target, build_target
import fuzzomatic.tools.utils | 3,437 | }
function_args = f[2]
template_path = str_template_path
extra_args = {}
if len(function_args) == 1:
try:
function_arg_type = function_args[0]
template_path = template_paths[function_arg_type]
except KeyError:
byte_array_length_template_path = (
"templates/fuzz_target/fuzz_target_byte_array_length.j2"
)
if type(function_arg_type) == tuple:
if function_arg_type[0] == "&array":
primitive_type = function_arg_type[1]
size = function_arg_type[2]
if primitive_type == "u8":
template_path = byte_array_length_template_path
extra_args = dict(array_length=size)
elif function_arg_type != "unknown":
# try the primitive type template
template_path = primitive_template_path
elif len(function_args) > 1:
template_path = "templates/fuzz_target/multiple_args/base.j2"
literal_args = []
struct_lifetime_needed = False
for arg in function_args:
if type(arg) == tuple and arg[0] == "&array":
primitive_type = arg[1]
size = arg[2]
struct_type = f"[{primitive_type}; {size}]"
call_prefix = "&"
literal_args.append((struct_type, call_prefix))
else:
if arg.startswith("&"):
struct_lifetime_needed = True
struct_type = arg.replace("&", "&'a ")
call_prefix = ""
literal_args.append((struct_type, call_prefix))
print("Literal args:")
print(literal_args)
extra_args = dict(
args=literal_args, struct_lifetime_needed=struct_lifetime_needed
)
success, fuzz_target_path = try_with_template(
template_path, codebase_dir, target_name, f, crate_name, extra_args
)
if success:
return True, fuzz_target_path
return False, None
def try_with_template(
template_path, codebase_dir, target_name, f, crate_name, extra_args
):
path = f[0]
function_name = f[1]
arg_type = f[2]
print(f"{arg_type=}")
if len(arg_type) == 1:
arg_type = arg_type[0]
import_path = ""
if len(path) > 0:
import_path += "::"
import_path += "::".join(path)
elif len(path) == 0:
import_path += f"::{function_name}"
usage_path = ""
if len(path) > 0:
usage_path = path[-1] + "::"
usage_path += function_name
print(f"{import_path=}")
print(f"{usage_path=}")
t = Template(prompts.load_file_contents(template_path))
fuzz_target_code = t.render(
crate_name=crate_name,
function_name=function_name,
import_path=import_path,
usage_path=usage_path,
arg_type=arg_type,
**extra_args,
)
fuzz_target_path = write_fuzz_target(fuzz_target_code, codebase_dir, target_name)
success, error, built_code = build_target(codebase_dir, target_name)
print("Generated code:")
print("-" * 10)
print(built_code)
print("-" * 10)
if success:
return True, fuzz_target_path
else:
print("Failed to build target")
print("Error:")
print(error)
# ask LLM to fix the code
fix_success, error = llm_attempt_fix_error(
codebase_dir, target_name, built_code, error
)
if fix_success:
return True, fuzz_target_path
return False, None
def find_target_functions_via_cargo_doc(codebase_dir, root_codebase_dir=None):
json_path = generate_cargo_doc_json(
codebase_dir, root_codebase_dir=root_codebase_dir
)
if json_path is not None:
print(f"Using cargo doc file: {json_path}")
|
def try_functions_approach(
codebase_dir,
target_name=DEFAULT_TARGET_NAME,
root_codebase_dir=None,
args=None,
**_kwargs,
):
functions = find_target_functions_via_cargo_doc(
codebase_dir, root_codebase_dir=root_codebase_dir
)
if functions is None:
print("Failed to detect functions")
return
ordered_functions = score_functions(functions)
print(f"{len(ordered_functions)} functions detected")
print("Detected target functions:")
for f in ordered_functions:
print(f)
max_functions = 8 # try max N functions
max_negative_score_functions = 2
negative_score_functions = 0
for f in ordered_functions[:max_functions]:
path = f[0]
function_name = f[1]
score = f[3]
# skip functions matching deny list
if args is not None and args.functions_denylist is not None:
skip_function = False
fully_qualified_function_name = "::".join(path)
if len(fully_qualified_function_name) > 0:
fully_qualified_function_name += "::"
fully_qualified_function_name += function_name
for word in args.functions_denylist:
if word in fully_qualified_function_name:
skip_function = True
if skip_function:
print(
f"Skipping function {fully_qualified_function_name} "
f"because of deny list: {args.functions_denylist}"
)
continue
print("Attempting function:")
print(f)
if score <= 0:
negative_score_functions += 1
success, fuzz_target_path = try_function(f, codebase_dir, target_name)
if success:
yield fuzz_target_path
if negative_score_functions >= max_negative_score_functions:
break
def score_functions(functions):
interesting_function_names = ["parse", "load", "read", "str", "eval"]
# order functions by most interesting first
ordered_functions = []
for f in functions:
function_name = f[1]
args = f[2]
priority = 0
is_name_interesting = False
for pattern in interesting_function_names:
if pattern in function_name:
is_name_interesting = True
if len(args) == 1:
arg_type = args[0]
if arg_type == "&str":
priority = 100
elif arg_type == "&[u8]":
priority = 100
elif arg_type == "String":
priority = 100
elif arg_type == "bool":
priority = 0
elif arg_type == "unknown":
priority = 10
elif type(arg_type) == tuple and arg_type[0] == "&array":
priority = 100
elif is_name_interesting:
priority = 100
if args[0] == "self":
priority = -15
elif args[0] == "self":
# functions with "self" as first argument
priority = -50
else:
priority = 50
elif len(args) > 1:
known_types = 0
for arg in args:
if arg != "unknown":
known_types += 1
if known_types == len(args):
priority = 30
if "&str" in args or "&[u8]" in args or "String" in args:
priority = 75
if any(type(arg) == tuple and arg[0] == "&array" for arg in args):
priority = 75
else:
# functions with multiple arguments where not all types are known
priority = -10
if args[0] == "self":
# functions with "self" as first argument
priority = -50
else:
# skip functions with no arguments
priority = -100
# give low priority to functions that are likely to load something by filename
if "file" in function_name and arg_type == "&str":
priority = 0
augmented_function = [*f, priority]
ordered_functions.append(augmented_function)
ordered_functions = sorted(ordered_functions, key=lambda x: x[3], reverse=True)
return ordered_functions
def try_function(f, codebase_dir, target_name):
crate_name = fuzzomatic.tools.utils.detect_crate_name(codebase_dir)
str_template_path = "templates/fuzz_target/fuzz_target_str.j2"
string_template_path = "templates/fuzz_target/fuzz_target_string.j2"
byte_slice_template_path = "templates/fuzz_target/fuzz_target_byte_array.j2"
primitive_template_path = "templates/fuzz_target/fuzz_target_primitive.j2"
bool_template_path = "templates/fuzz_target/fuzz_target_bool.j2"
template_paths = {
"&str": str_template_path,
"String": string_template_path,
"&[u8]": byte_slice_template_path,
"bool": bool_template_path,
"unknown": str_template_path,
}
function_args = f[2]
template_path = str_template_path
extra_args = {}
if len(function_args) == 1:
try:
function_arg_type = function_args[0]
template_path = template_paths[function_arg_type]
except KeyError:
byte_array_length_template_path = (
"templates/fuzz_target/fuzz_target_byte_array_length.j2"
)
if type(function_arg_type) == tuple:
if function_arg_type[0] == "&array":
primitive_type = function_arg_type[1]
size = function_arg_type[2]
if primitive_type == "u8":
template_path = byte_array_length_template_path
extra_args = dict(array_length=size)
elif function_arg_type != "unknown":
# try the primitive type template
template_path = primitive_template_path
elif len(function_args) > 1:
template_path = "templates/fuzz_target/multiple_args/base.j2"
literal_args = []
struct_lifetime_needed = False
for arg in function_args:
if type(arg) == tuple and arg[0] == "&array":
primitive_type = arg[1]
size = arg[2]
struct_type = f"[{primitive_type}; {size}]"
call_prefix = "&"
literal_args.append((struct_type, call_prefix))
else:
if arg.startswith("&"):
struct_lifetime_needed = True
struct_type = arg.replace("&", "&'a ")
call_prefix = ""
literal_args.append((struct_type, call_prefix))
print("Literal args:")
print(literal_args)
extra_args = dict(
args=literal_args, struct_lifetime_needed=struct_lifetime_needed
)
success, fuzz_target_path = try_with_template(
template_path, codebase_dir, target_name, f, crate_name, extra_args
)
if success:
return True, fuzz_target_path
return False, None
def try_with_template(
template_path, codebase_dir, target_name, f, crate_name, extra_args
):
path = f[0]
function_name = f[1]
arg_type = f[2]
print(f"{arg_type=}")
if len(arg_type) == 1:
arg_type = arg_type[0]
import_path = ""
if len(path) > 0:
import_path += "::"
import_path += "::".join(path)
elif len(path) == 0:
import_path += f"::{function_name}"
usage_path = ""
if len(path) > 0:
usage_path = path[-1] + "::"
usage_path += function_name
print(f"{import_path=}")
print(f"{usage_path=}")
t = Template(prompts.load_file_contents(template_path))
fuzz_target_code = t.render(
crate_name=crate_name,
function_name=function_name,
import_path=import_path,
usage_path=usage_path,
arg_type=arg_type,
**extra_args,
)
fuzz_target_path = write_fuzz_target(fuzz_target_code, codebase_dir, target_name)
success, error, built_code = build_target(codebase_dir, target_name)
print("Generated code:")
print("-" * 10)
print(built_code)
print("-" * 10)
if success:
return True, fuzz_target_path
else:
print("Failed to build target")
print("Error:")
print(error)
# ask LLM to fix the code
fix_success, error = llm_attempt_fix_error(
codebase_dir, target_name, built_code, error
)
if fix_success:
return True, fuzz_target_path
return False, None
def find_target_functions_via_cargo_doc(codebase_dir, root_codebase_dir=None):
json_path = generate_cargo_doc_json(
codebase_dir, root_codebase_dir=root_codebase_dir
)
if json_path is not None:
print(f"Using cargo doc file: {json_path}") | functions = parse_cargo_doc_json(json_path) | 2 | 2023-11-14 09:52:59+00:00 | 4k |
muyuworks/myla | tests/myla/vectorstores/faiss_group_test.py | [
{
"identifier": "FAISSGroup",
"path": "myla/vectorstores/faiss_group.py",
"snippet": "class FAISSGroup(VectorStore):\n def __init__(self, path: str, embeddings: Embeddings = None) -> None:\n self._path = path\n self._embeddings = embeddings\n self._faiss = _import_faiss()\n\n ... | import os
import shutil
import unittest
from myla.vectorstores.faiss_group import FAISSGroup
from myla.utils import random_id, sha256 | 2,848 |
here = os.path.abspath(os.path.dirname(__file__))
class FAISSGroupTests(unittest.TestCase):
def setUp(self) -> None:
self._vectors = [
[0, 0],
[1, 1],
[2, 2],
[3, 3],
[4, 4]
]
self._records = [
{
'id': 0,
'gid': 'g0',
},
{
'id': 1,
'gid': 'g0',
},
{
'id': 2,
'gid': 'g2',
},
{
'id': 3,
'gid': 'g3',
},
{
'id': 4,
}
]
self._data = os.path.abspath(os.path.join(here, os.pardir, os.pardir, 'data', random_id()))
def tearDown(self) -> None:
if os.path.exists(self._data):
shutil.rmtree(self._data)
pass
def test_create_collection(self):
vs = FAISSGroup(path=self._data)
vs.create_collection(collection='col')
def test_add(self):
vs = FAISSGroup(path=self._data)
vs.create_collection(collection='col')
vs.add(collection='col', records=self._records, vectors=self._vectors, group_by='gid')
self.assertIsNotNone(vs._data.get('col'))
self.assertEqual(vs._data.get('col'), self._records)
self.assertIsNotNone(vs._indexes.get('col'))
self.assertIsNotNone(vs._ids.get('col'))
self.assertEqual(len(vs._indexes.get('col')), 4)
self.assertEqual(len(vs._ids.get('col')), 4)
self.assertEqual(vs._indexes.get('col').keys(), vs._ids.get('col').keys())
gids = list(vs._indexes.get('col').keys())
gids.sort()
gids_1 = []
for r in self._records:
|
here = os.path.abspath(os.path.dirname(__file__))
class FAISSGroupTests(unittest.TestCase):
def setUp(self) -> None:
self._vectors = [
[0, 0],
[1, 1],
[2, 2],
[3, 3],
[4, 4]
]
self._records = [
{
'id': 0,
'gid': 'g0',
},
{
'id': 1,
'gid': 'g0',
},
{
'id': 2,
'gid': 'g2',
},
{
'id': 3,
'gid': 'g3',
},
{
'id': 4,
}
]
self._data = os.path.abspath(os.path.join(here, os.pardir, os.pardir, 'data', random_id()))
def tearDown(self) -> None:
if os.path.exists(self._data):
shutil.rmtree(self._data)
pass
def test_create_collection(self):
vs = FAISSGroup(path=self._data)
vs.create_collection(collection='col')
def test_add(self):
vs = FAISSGroup(path=self._data)
vs.create_collection(collection='col')
vs.add(collection='col', records=self._records, vectors=self._vectors, group_by='gid')
self.assertIsNotNone(vs._data.get('col'))
self.assertEqual(vs._data.get('col'), self._records)
self.assertIsNotNone(vs._indexes.get('col'))
self.assertIsNotNone(vs._ids.get('col'))
self.assertEqual(len(vs._indexes.get('col')), 4)
self.assertEqual(len(vs._ids.get('col')), 4)
self.assertEqual(vs._indexes.get('col').keys(), vs._ids.get('col').keys())
gids = list(vs._indexes.get('col').keys())
gids.sort()
gids_1 = []
for r in self._records: | gids_1.append(sha256(r.get('gid', '').encode()).hex()) | 2 | 2023-11-15 01:05:03+00:00 | 4k |
AdmTal/music-graphs | music_graphs.py | [
{
"identifier": "generate_music_graph",
"path": "src/generate_music_graph.py",
"snippet": "def generate_music_graph(\n midi_file_path,\n default_theme_file_path,\n theme_file_path,\n output_path,\n soundfont_file,\n):\n theme = Theme(theme_file_path, default_theme_file_path)\n track... | import os
import click
from src.generate_music_graph import generate_music_graph
from src.midi_stuff import SOUND_FONT_FILE
from src.theme_stuff import DARK_THEME_FILE, LIGHT_THEME_FILE | 2,122 |
def get_filename_without_extension(path):
filename_with_extension = os.path.basename(path)
filename_without_extension, _ = os.path.splitext(filename_with_extension)
return filename_without_extension
@click.command()
@click.option(
"--midi",
required=True,
type=click.Path(exists=True),
help="Path to a MIDI file.",
)
@click.option(
"--theme",
type=click.Path(exists=True),
help="Path to a YAML theme file.",
)
@click.option(
"--dark",
type=bool,
help="True if dark theme should be the used.",
default=False,
is_flag=True,
)
@click.option(
"--output_filename",
type=click.Path(),
help="Output filename (path).",
default=None,
)
@click.option(
"--soundfont_file",
type=click.Path(),
help="Path to a Soundfont file",
default=SOUND_FONT_FILE,
)
def main(midi, theme, output_filename, soundfont_file, dark):
default_theme_file = LIGHT_THEME_FILE
if dark:
default_theme_file = DARK_THEME_FILE
if not theme:
theme = default_theme_file
if not output_filename:
output_filename = get_filename_without_extension(midi)
|
def get_filename_without_extension(path):
filename_with_extension = os.path.basename(path)
filename_without_extension, _ = os.path.splitext(filename_with_extension)
return filename_without_extension
@click.command()
@click.option(
"--midi",
required=True,
type=click.Path(exists=True),
help="Path to a MIDI file.",
)
@click.option(
"--theme",
type=click.Path(exists=True),
help="Path to a YAML theme file.",
)
@click.option(
"--dark",
type=bool,
help="True if dark theme should be the used.",
default=False,
is_flag=True,
)
@click.option(
"--output_filename",
type=click.Path(),
help="Output filename (path).",
default=None,
)
@click.option(
"--soundfont_file",
type=click.Path(),
help="Path to a Soundfont file",
default=SOUND_FONT_FILE,
)
def main(midi, theme, output_filename, soundfont_file, dark):
default_theme_file = LIGHT_THEME_FILE
if dark:
default_theme_file = DARK_THEME_FILE
if not theme:
theme = default_theme_file
if not output_filename:
output_filename = get_filename_without_extension(midi)
| generate_music_graph( | 0 | 2023-11-17 17:56:04+00:00 | 4k |
FISHers6/CodeLearn-Agent | codelearn/project/project_manager.py | [
{
"identifier": "LOCAL_PROJECT_PATH",
"path": "codelearn/base.py",
"snippet": "LOCAL_PROJECT_PATH = os.path.join(BASE_PROJECT_PATH, \"projects\")"
},
{
"identifier": "Indexer",
"path": "codelearn/index/indexer.py",
"snippet": "class Indexer(ABC):\n @abstractmethod\n def index(self,... | import asyncio
import os
import time
import uuid
from typing import Any, Dict, List, Optional
from openai import Embedding
from codelearn.base import LOCAL_PROJECT_PATH
from codelearn.index.indexer import Indexer, Metadata
from codelearn.loader.loader import ProjectLoader
from datetime import datetime, timedelta
from codelearn.project.project import Project
from codelearn.retrieval.retriever import RetrieveResults, Retriever
from codelearn.splitter.splitter import Splitter
from codelearn.storage.project_storage import ProjectStorageManager
from codelearn.storage.vector import VectorStoreBase
from codelearn.utils.clearn_task_queue import AsyncQueue, async_cleanup, sync_cleanup
from codelearn.base import LOCAL_PROJECT_PATH | 1,734 |
class ProjectManager:
PROJECT_UPDATE_THRESHOLD = 30 * 24 * 60 * 60
def __init__(self,
loaders: Dict[str, ProjectLoader],
splitters: Dict[str, Splitter],
|
class ProjectManager:
PROJECT_UPDATE_THRESHOLD = 30 * 24 * 60 * 60
def __init__(self,
loaders: Dict[str, ProjectLoader],
splitters: Dict[str, Splitter], | indexers: Dict[str, Indexer], | 1 | 2023-11-12 13:13:30+00:00 | 4k |
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,705 |
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)
dataset_list.append(dataset)
return dataset_list
def _get_evaluator(self, framework):
if framework == 'pytorch':
return self._pytorch_evaluator
else:
raise NameError("Unsupported evaluator")
def _remove_model_from_cache(self, framework, model_name):
def _format_name(name):
return name.lower().replace("-", "_")
try:
if framework == "pytorch":
cachedir = "/root/.cache/torch/checkpoints/"
downloaded_models = os.listdir(cachedir)
for dm in downloaded_models:
if _format_name(dm).startswith(_format_name(model_name)):
os.remove(os.path.join(cachedir, dm))
except:
pass
def __call__(self, models, dataset_names, *args, **kwargs):
"""
Wrapper call to _evaluate function.
Args:
models:
dataset_names:
*args:
**kwargs:
Returns:
"""
logging.info("Model evaluation.")
_datasets = self._get_datasets(dataset_names, *args, **kwargs)
for model_name in models:
datasets = _datasets
if model_name in [
"deit3_21k", "convnext_base_21k", "convnextv2_base",
"vit_clip", "convnext_clip"
]:
|
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)
dataset_list.append(dataset)
return dataset_list
def _get_evaluator(self, framework):
if framework == 'pytorch':
return self._pytorch_evaluator
else:
raise NameError("Unsupported evaluator")
def _remove_model_from_cache(self, framework, model_name):
def _format_name(name):
return name.lower().replace("-", "_")
try:
if framework == "pytorch":
cachedir = "/root/.cache/torch/checkpoints/"
downloaded_models = os.listdir(cachedir)
for dm in downloaded_models:
if _format_name(dm).startswith(_format_name(model_name)):
os.remove(os.path.join(cachedir, dm))
except:
pass
def __call__(self, models, dataset_names, *args, **kwargs):
"""
Wrapper call to _evaluate function.
Args:
models:
dataset_names:
*args:
**kwargs:
Returns:
"""
logging.info("Model evaluation.")
_datasets = self._get_datasets(dataset_names, *args, **kwargs)
for model_name in models:
datasets = _datasets
if model_name in [
"deit3_21k", "convnext_base_21k", "convnextv2_base",
"vit_clip", "convnext_clip"
]: | model, transform_val = load_model_transform( | 0 | 2023-11-15 22:22:06+00:00 | 4k |
shengliu66/ICV | tasks/base.py | [
{
"identifier": "hf_datasets_root",
"path": "anchor.py",
"snippet": ""
},
{
"identifier": "TokenizedForStyleRightPad",
"path": "tasks/loader.py",
"snippet": "class TokenizedForStyleRightPad(Dataset):\n def __init__(self, data, tok: PreTrainedTokenizer, prompt_fn, mode = 'eval', no_pad... | import json
import logging
import random
import re
import torch
import numpy as np
import datasets
from collections import defaultdict
from anchor import hf_datasets_root
from tasks.loader import TokenizedForStyleRightPad
from utils.rng_ctx import RandomContext, EmptyContext
from utils.pca import PCA
from utils.context_manager import modified_forward_context_manager, traced_forward_context_manager | 2,004 |
logger = logging.getLogger("task")
class BaseProbInference:
def __init__(self, prompt_version):
if prompt_version == "default":
self.prompt_version = self.default_prompt_version()
else:
self.prompt_version = prompt_version
self.raw_data_sample = None
self.raw_data_dev = None
self.can_be_stratified = False
self.num_base_shot = 1
self._rng_context = EmptyContext()
self._cached_prefix = None
self._cached_ex_list = None
self._cahced_selected_exemplar = None
self.shuffled_mapping = None
def default_prompt_version(self):
raise NotImplementedError
def set_seed(self, seed):
|
logger = logging.getLogger("task")
class BaseProbInference:
def __init__(self, prompt_version):
if prompt_version == "default":
self.prompt_version = self.default_prompt_version()
else:
self.prompt_version = prompt_version
self.raw_data_sample = None
self.raw_data_dev = None
self.can_be_stratified = False
self.num_base_shot = 1
self._rng_context = EmptyContext()
self._cached_prefix = None
self._cached_ex_list = None
self._cahced_selected_exemplar = None
self.shuffled_mapping = None
def default_prompt_version(self):
raise NotImplementedError
def set_seed(self, seed): | self._rng_context = RandomContext(seed=seed) | 2 | 2023-11-11 18:20:45+00:00 | 4k |
Mohamad-Hussein/speech-assistant | src/parent.py | [
{
"identifier": "service",
"path": "src/model_inference.py",
"snippet": "def service(queue, event):\n # Configure the logging settings\n logging.basicConfig(\n level=logging.DEBUG,\n format=\"%(asctime)s - %(levelname)s - %(message)s\",\n filename=join(\"logs\", \"model.log\")... | from time import time, sleep
from os.path import join
from shutil import copy
from multiprocessing import Process, Event, Pipe, Queue
from threading import Thread
from src.model_inference import service
from src.funcs import run_listener
from src.funcs import get_audio, create_sound_file, pcm_to_wav
from playsound import playsound
import logging
import traceback | 1,851 |
# Global variables
# -------------------------
# Change to true if you want to save audio to file called recording.wav
SAVE_AUDIO = False
# Create a logger instance
logger = logging.getLogger(__name__)
# Getting audio inputs
audio, stream_input = get_audio()
# No audio being recorded
stream_input.stop_stream()
# -------------------------
def start_recording(start_event, model_event, queue):
logger.info("sound-high played")
t0 = time()
# This line to wake device from sleep state
# Huge performance gain from Threading and playsound
sound1 = Thread(
target=playsound, args=(join("effects", "button-high.wav"),), name="play-sound1"
)
sound2 = Thread(
target=playsound, args=(join("effects", "button-low.wav"),), name="play-sound2"
)
# Start stream
stream_input.start_stream()
logger.debug(f"Get read: {stream_input.get_read_available()}")
if not stream_input.is_active():
print("Stream is not active")
return
# Capturing audio
frames = []
try:
# Playing start sound
sound1.start()
logger.info(f"From start to capture: {time() - t0:.2f}s")
# Capturing audio
print("Capture STARTED")
while start_event.is_set():
data = stream_input.read(1024)
frames.append(data)
print("Capture FINISHED")
# Converting to wav
|
# Global variables
# -------------------------
# Change to true if you want to save audio to file called recording.wav
SAVE_AUDIO = False
# Create a logger instance
logger = logging.getLogger(__name__)
# Getting audio inputs
audio, stream_input = get_audio()
# No audio being recorded
stream_input.stop_stream()
# -------------------------
def start_recording(start_event, model_event, queue):
logger.info("sound-high played")
t0 = time()
# This line to wake device from sleep state
# Huge performance gain from Threading and playsound
sound1 = Thread(
target=playsound, args=(join("effects", "button-high.wav"),), name="play-sound1"
)
sound2 = Thread(
target=playsound, args=(join("effects", "button-low.wav"),), name="play-sound2"
)
# Start stream
stream_input.start_stream()
logger.debug(f"Get read: {stream_input.get_read_available()}")
if not stream_input.is_active():
print("Stream is not active")
return
# Capturing audio
frames = []
try:
# Playing start sound
sound1.start()
logger.info(f"From start to capture: {time() - t0:.2f}s")
# Capturing audio
print("Capture STARTED")
while start_event.is_set():
data = stream_input.read(1024)
frames.append(data)
print("Capture FINISHED")
# Converting to wav | sound_byte_wav = pcm_to_wav(b"".join(frames)) | 4 | 2023-11-12 01:20:50+00:00 | 4k |
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,843 |
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
if k == ":": return Separator.DYADIC
if is_nilad_array(k): return 0
raise Exception(f"{k} not handled in keyword_arity function.")
def arity_chain_repr(i: int) -> str:
if i in [Quick.QUICK, Quick.EACH, Quick.FLIP]: return "q"
if i in [Separator.MONADIC, Separator.DYADIC]: return "s"
return str(i)
def chain_arity_to_string(chain_arity: list[int]) -> str:
return "-".join([arity_chain_repr(e) for e in chain_arity])
def keyword_color(k: str):
if k in tokens.monadic: return Fore.GREEN
if k in tokens.dyadic: return Fore.BLUE
if k in tokens.quick: return Fore.RED
return Fore.WHITE
def colored_keywords(args, expr):
print(f"> {args} :: {' '.join(keyword_color(k) + k for k in expr.split())}")
def spaced_jelly_atoms(args, expr):
indent = " " * (2 + len(args) + 4)
spaced_jelly_atoms = " ".join(to_jelly(k).center(len(k)) for k in expr.split())
draw.cprint(indent + spaced_jelly_atoms, Fore.YELLOW, True)
def skip_trace(converted_expr: list[str], i: int) -> bool:
if converted_expr[i - 1] in list(tokens.separators.values()) + ["Œ", "œ"]:
return True
if i < len(converted_expr) and converted_expr[i] in tokens.quick.values():
return True
return False
if __name__ == "__main__":
init() # for colorama
print("🟢🟡🔴 Jello 🔴🟡🟢\n")
while True:
try:
user_input = prompt("> ",
completer=completer,
history=history,
reserve_space_for_menu=0,
complete_style=CompleteStyle.MULTI_COLUMN)
if user_input.strip().lower() == "q": break
if user_input.strip() == "?":
arity_notation.explain()
continue
clear_screen()
print("🟢🟡🔴 Jello 🔴🟡🟢\n")
if "::" not in user_input:
print(f"> {user_input}")
draw.cprint(" error: missing :: after args", Fore.RED, True)
continue
[args, expr] = [s.strip() for s in user_input.strip().split("::")] # should consist of keywords
colored_keywords(args, expr)
spaced_jelly_atoms(args, expr)
algorithm.advisor(expr)
expr = utils.remove_all(utils.split_keep_multiple_delimiters(expr, r" \(\)"), ["", " "])
args = args.split()
converted_expr = convert(expr)
| #!/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
if k == ":": return Separator.DYADIC
if is_nilad_array(k): return 0
raise Exception(f"{k} not handled in keyword_arity function.")
def arity_chain_repr(i: int) -> str:
if i in [Quick.QUICK, Quick.EACH, Quick.FLIP]: return "q"
if i in [Separator.MONADIC, Separator.DYADIC]: return "s"
return str(i)
def chain_arity_to_string(chain_arity: list[int]) -> str:
return "-".join([arity_chain_repr(e) for e in chain_arity])
def keyword_color(k: str):
if k in tokens.monadic: return Fore.GREEN
if k in tokens.dyadic: return Fore.BLUE
if k in tokens.quick: return Fore.RED
return Fore.WHITE
def colored_keywords(args, expr):
print(f"> {args} :: {' '.join(keyword_color(k) + k for k in expr.split())}")
def spaced_jelly_atoms(args, expr):
indent = " " * (2 + len(args) + 4)
spaced_jelly_atoms = " ".join(to_jelly(k).center(len(k)) for k in expr.split())
draw.cprint(indent + spaced_jelly_atoms, Fore.YELLOW, True)
def skip_trace(converted_expr: list[str], i: int) -> bool:
if converted_expr[i - 1] in list(tokens.separators.values()) + ["Œ", "œ"]:
return True
if i < len(converted_expr) and converted_expr[i] in tokens.quick.values():
return True
return False
if __name__ == "__main__":
init() # for colorama
print("🟢🟡🔴 Jello 🔴🟡🟢\n")
while True:
try:
user_input = prompt("> ",
completer=completer,
history=history,
reserve_space_for_menu=0,
complete_style=CompleteStyle.MULTI_COLUMN)
if user_input.strip().lower() == "q": break
if user_input.strip() == "?":
arity_notation.explain()
continue
clear_screen()
print("🟢🟡🔴 Jello 🔴🟡🟢\n")
if "::" not in user_input:
print(f"> {user_input}")
draw.cprint(" error: missing :: after args", Fore.RED, True)
continue
[args, expr] = [s.strip() for s in user_input.strip().split("::")] # should consist of keywords
colored_keywords(args, expr)
spaced_jelly_atoms(args, expr)
algorithm.advisor(expr)
expr = utils.remove_all(utils.split_keep_multiple_delimiters(expr, r" \(\)"), ["", " "])
args = args.split()
converted_expr = convert(expr) | chain_type = Chain.MONADIC if len(args) == 1 else Chain.DYADIC | 1 | 2023-11-18 17:34:06+00:00 | 4k |
davep/tinboard | tinboard/widgets/details.py | [
{
"identifier": "CopyBookmarkURL",
"path": "tinboard/messages/commands.py",
"snippet": "class CopyBookmarkURL(Command):\n \"\"\"Copy the URL for the bookmark to the clipboard.\"\"\""
},
{
"identifier": "EditBookmark",
"path": "tinboard/messages/commands.py",
"snippet": "class EditBook... | from webbrowser import open as open_url
from humanize import naturaltime
from textual import on
from textual.app import ComposeResult
from textual.binding import Binding
from textual.containers import VerticalScroll
from textual.message import Message
from textual.reactive import var
from textual.widgets import Label
from ..messages import (
CopyBookmarkURL,
EditBookmark,
ToggleBookmarkPublic,
ToggleBookmarkRead,
)
from .bookmarks import Bookmark
from .tags import InlineTags | 1,852 | """The details display widget."""
##############################################################################
# Python imports.
##############################################################################
# Humanize imports.
##############################################################################
# Textual imports.
##############################################################################
# Local imports.
##############################################################################
class Link(Label):
"""Widget for showing the link.
This is here mostly to work around the fact that a click action doesn't
propagate in the way you'd expect.
https://github.com/Textualize/textual/issues/3690
"""
class Visit(Message):
"""Message to indicate that the link should be visited."""
def action_visit(self) -> None:
"""Handle a UI request to visit the link."""
self.post_message(self.Visit())
##############################################################################
class Details(VerticalScroll):
"""A widget for displaying details of a bookmark."""
DEFAULT_CSS = """
Details {
scrollbar-gutter: stable;
.hidden {
visibility: hidden;
}
.empty {
display: none;
}
Label {
margin: 0 2 1 2;
width: 1fr;
color: $text;
}
#title {
background: $primary;
padding: 1 2 1 2;
text-align: center;
}
.detail {
background: $boost;
padding: 1 2 1 2;
}
#added-ish {
margin: 0 2 0 2;
padding: 1 2 0 2;
}
#added-exact {
margin: 0 2 1 2;
padding: 0 2 1 2;
text-align: right;
color: $text-muted;
text-style: italic;
}
InlineTags, InlineTags:focus {
margin: 0 2 1 2;
}
}
"""
BINDINGS = [
Binding("enter", "visit_bookmark", "Visit"),
Binding("c", "copy", "Copy to Clipboard"),
Binding("e", "edit", "Edit"),
Binding("ctrl+r", "read"),
Binding("ctrl+v", "public"),
]
CONTEXT_HELP = """
## Bookmark details keys
The following keys are available in the bookmark details:
| Key | Description |
| - | - |
| <kbd>Enter</kbd> | Visit the current bookmark. |
| <kbd>c</kbd> | Copy the URL of the bookmark to the clipboard. |
| <kbd>e</kbd> | Edit the details of the bookmark. |
| <kbd>Ctrl</kbd>+<kbd>r</kbd> | Toggle the read/unread status of the bookmark. |
| <kbd>Ctrl</kbd>+<kbd>v</kbd> | Toggle the visibility of the bookmark. |
"""
| """The details display widget."""
##############################################################################
# Python imports.
##############################################################################
# Humanize imports.
##############################################################################
# Textual imports.
##############################################################################
# Local imports.
##############################################################################
class Link(Label):
"""Widget for showing the link.
This is here mostly to work around the fact that a click action doesn't
propagate in the way you'd expect.
https://github.com/Textualize/textual/issues/3690
"""
class Visit(Message):
"""Message to indicate that the link should be visited."""
def action_visit(self) -> None:
"""Handle a UI request to visit the link."""
self.post_message(self.Visit())
##############################################################################
class Details(VerticalScroll):
"""A widget for displaying details of a bookmark."""
DEFAULT_CSS = """
Details {
scrollbar-gutter: stable;
.hidden {
visibility: hidden;
}
.empty {
display: none;
}
Label {
margin: 0 2 1 2;
width: 1fr;
color: $text;
}
#title {
background: $primary;
padding: 1 2 1 2;
text-align: center;
}
.detail {
background: $boost;
padding: 1 2 1 2;
}
#added-ish {
margin: 0 2 0 2;
padding: 1 2 0 2;
}
#added-exact {
margin: 0 2 1 2;
padding: 0 2 1 2;
text-align: right;
color: $text-muted;
text-style: italic;
}
InlineTags, InlineTags:focus {
margin: 0 2 1 2;
}
}
"""
BINDINGS = [
Binding("enter", "visit_bookmark", "Visit"),
Binding("c", "copy", "Copy to Clipboard"),
Binding("e", "edit", "Edit"),
Binding("ctrl+r", "read"),
Binding("ctrl+v", "public"),
]
CONTEXT_HELP = """
## Bookmark details keys
The following keys are available in the bookmark details:
| Key | Description |
| - | - |
| <kbd>Enter</kbd> | Visit the current bookmark. |
| <kbd>c</kbd> | Copy the URL of the bookmark to the clipboard. |
| <kbd>e</kbd> | Edit the details of the bookmark. |
| <kbd>Ctrl</kbd>+<kbd>r</kbd> | Toggle the read/unread status of the bookmark. |
| <kbd>Ctrl</kbd>+<kbd>v</kbd> | Toggle the visibility of the bookmark. |
"""
| bookmark: var[Bookmark | None] = var(None, always_update=True) | 4 | 2023-11-13 08:19:41+00:00 | 4k |
wurenkai/MHA-UNet | engine.py | [
{
"identifier": "save_imgs",
"path": "utils.py",
"snippet": "def save_imgs(img, msk, msk_pred, i, save_path, datasets, threshold=0.5, test_data_name=None):\r\n img = img.squeeze(0).permute(1,2,0).detach().cpu().numpy()\r\n img = img / 255. if img.max() > 1.1 else img\r\n if datasets == 'retinal... | import numpy as np
import torch
import torchvision.transforms as transforms
import torch.nn.functional as F
from tqdm import tqdm
from torch.cuda.amp import autocast as autocast
from sklearn.metrics import confusion_matrix
from utils import save_imgs,save_imgs_explainable
from PIL import Image
| 2,981 | optimizer,
scheduler,
epoch,
logger,
config,
scaler=None):
'''
train model for one epoch
'''
# switch to train mode
model.train()
loss_list = []
for iter, data in enumerate(train_loader):
optimizer.zero_grad()
images, targets = data
images, targets = images.cuda(non_blocking=True).float(), targets.cuda(non_blocking=True).float()
if config.amp:
with autocast():
out, x0, x1, x2, x3, x4 = model(images)
loss = criterion(out, targets)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
else:
out,x0,x1,x2,x3,x4 = model(images)
loss = criterion(out, targets)
loss.backward()
optimizer.step()
loss_list.append(loss.item())
now_lr = optimizer.state_dict()['param_groups'][0]['lr']
if iter % config.print_interval == 0:
log_info = f'train: epoch {epoch}, iter:{iter}, loss: {np.mean(loss_list):.4f}, lr: {now_lr}'
print(log_info)
logger.info(log_info)
scheduler.step()
def val_one_epoch(test_loader,
model,
criterion,
epoch,
logger,
config):
# switch to evaluate mode
model.eval()
preds = []
gts = []
loss_list = []
with torch.no_grad():
for data in tqdm(test_loader):
img, msk = data
img, msk = img.cuda(non_blocking=True).float(), msk.cuda(non_blocking=True).float()
out,x0,x1,x2,x3,x4 = model(img)
loss = criterion(out, msk)
loss_list.append(loss.item())
gts.append(msk.squeeze(1).cpu().detach().numpy())
if type(out) is tuple:
out = out[0]
out = out.squeeze(1).cpu().detach().numpy()
preds.append(out)
if epoch % config.val_interval == 0:
preds = np.array(preds).reshape(-1)
gts = np.array(gts).reshape(-1)
y_pre = np.where(preds>=config.threshold, 1, 0)
y_true = np.where(gts>=0.5, 1, 0)
confusion = confusion_matrix(y_true, y_pre)
TN, FP, FN, TP = confusion[0,0], confusion[0,1], confusion[1,0], confusion[1,1]
accuracy = float(TN + TP) / float(np.sum(confusion)) if float(np.sum(confusion)) != 0 else 0
sensitivity = float(TP) / float(TP + FN) if float(TP + FN) != 0 else 0
specificity = float(TN) / float(TN + FP) if float(TN + FP) != 0 else 0
f1_or_dsc = float(2 * TP) / float(2 * TP + FP + FN) if float(2 * TP + FP + FN) != 0 else 0
miou = float(TP) / float(TP + FP + FN) if float(TP + FP + FN) != 0 else 0
log_info = f'val epoch: {epoch}, loss: {np.mean(loss_list):.4f}, miou: {miou}, f1_or_dsc: {f1_or_dsc}, accuracy: {accuracy}, \
specificity: {specificity}, sensitivity: {sensitivity}, confusion_matrix: {confusion}'
print(log_info)
logger.info(log_info)
else:
log_info = f'val epoch: {epoch}, loss: {np.mean(loss_list):.4f}'
print(log_info)
logger.info(log_info)
return np.mean(loss_list)
def test_one_epoch_explainable(test_loader,
model,
criterion,
logger,
config,
test_data_name=None):
# switch to evaluate mode
model.eval()
preds = []
gts = []
a=0
loss_list = []
with torch.no_grad():
for i, data in enumerate(tqdm(test_loader)):
img, msk = data
img, msk = img.cuda(non_blocking=True).float(), msk.cuda(non_blocking=True).float()
out,x0,x1,x2,x3,x4 = model(img)
loss = criterion(out, msk)
loss_list.append(loss.item())
msk = msk.squeeze(1).cpu().detach().numpy()
gts.append(msk)
if type(out) is tuple:
out = out[0]
out = out.squeeze(1).cpu().detach().numpy()
preds.append(out)
|
def train_one_epoch(train_loader,
model,
criterion,
optimizer,
scheduler,
epoch,
logger,
config,
scaler=None):
'''
train model for one epoch
'''
# switch to train mode
model.train()
loss_list = []
for iter, data in enumerate(train_loader):
optimizer.zero_grad()
images, targets = data
images, targets = images.cuda(non_blocking=True).float(), targets.cuda(non_blocking=True).float()
if config.amp:
with autocast():
out, x0, x1, x2, x3, x4 = model(images)
loss = criterion(out, targets)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
else:
out,x0,x1,x2,x3,x4 = model(images)
loss = criterion(out, targets)
loss.backward()
optimizer.step()
loss_list.append(loss.item())
now_lr = optimizer.state_dict()['param_groups'][0]['lr']
if iter % config.print_interval == 0:
log_info = f'train: epoch {epoch}, iter:{iter}, loss: {np.mean(loss_list):.4f}, lr: {now_lr}'
print(log_info)
logger.info(log_info)
scheduler.step()
def val_one_epoch(test_loader,
model,
criterion,
epoch,
logger,
config):
# switch to evaluate mode
model.eval()
preds = []
gts = []
loss_list = []
with torch.no_grad():
for data in tqdm(test_loader):
img, msk = data
img, msk = img.cuda(non_blocking=True).float(), msk.cuda(non_blocking=True).float()
out,x0,x1,x2,x3,x4 = model(img)
loss = criterion(out, msk)
loss_list.append(loss.item())
gts.append(msk.squeeze(1).cpu().detach().numpy())
if type(out) is tuple:
out = out[0]
out = out.squeeze(1).cpu().detach().numpy()
preds.append(out)
if epoch % config.val_interval == 0:
preds = np.array(preds).reshape(-1)
gts = np.array(gts).reshape(-1)
y_pre = np.where(preds>=config.threshold, 1, 0)
y_true = np.where(gts>=0.5, 1, 0)
confusion = confusion_matrix(y_true, y_pre)
TN, FP, FN, TP = confusion[0,0], confusion[0,1], confusion[1,0], confusion[1,1]
accuracy = float(TN + TP) / float(np.sum(confusion)) if float(np.sum(confusion)) != 0 else 0
sensitivity = float(TP) / float(TP + FN) if float(TP + FN) != 0 else 0
specificity = float(TN) / float(TN + FP) if float(TN + FP) != 0 else 0
f1_or_dsc = float(2 * TP) / float(2 * TP + FP + FN) if float(2 * TP + FP + FN) != 0 else 0
miou = float(TP) / float(TP + FP + FN) if float(TP + FP + FN) != 0 else 0
log_info = f'val epoch: {epoch}, loss: {np.mean(loss_list):.4f}, miou: {miou}, f1_or_dsc: {f1_or_dsc}, accuracy: {accuracy}, \
specificity: {specificity}, sensitivity: {sensitivity}, confusion_matrix: {confusion}'
print(log_info)
logger.info(log_info)
else:
log_info = f'val epoch: {epoch}, loss: {np.mean(loss_list):.4f}'
print(log_info)
logger.info(log_info)
return np.mean(loss_list)
def test_one_epoch_explainable(test_loader,
model,
criterion,
logger,
config,
test_data_name=None):
# switch to evaluate mode
model.eval()
preds = []
gts = []
a=0
loss_list = []
with torch.no_grad():
for i, data in enumerate(tqdm(test_loader)):
img, msk = data
img, msk = img.cuda(non_blocking=True).float(), msk.cuda(non_blocking=True).float()
out,x0,x1,x2,x3,x4 = model(img)
loss = criterion(out, msk)
loss_list.append(loss.item())
msk = msk.squeeze(1).cpu().detach().numpy()
gts.append(msk)
if type(out) is tuple:
out = out[0]
out = out.squeeze(1).cpu().detach().numpy()
preds.append(out)
| a = save_imgs_explainable(img,x0,x1,x2,x3,x4,i,a, config.work_dir + 'outputs/', config.datasets, config.threshold,
| 1 | 2023-11-13 06:59:52+00:00 | 4k |
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,765 |
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
conv = build_conversation()
conv.append_message(conv.roles[0], qs)
conv.append_message(conv.roles[1], None)
prompt = conv.get_prompt()
image = Image.open(os.path.join(self.image_folder,
image_file)).convert('RGB')
image_tensor = process_images([image], self.image_processor,
self.model_config)[0]
input_ids = tokenizer_image_token(prompt,
self.tokenizer,
IMAGE_TOKEN_INDEX,
return_tensors='pt')
return input_ids, image_tensor
def __len__(self):
return len(self.questions)
# DataLoader
def create_data_loader(questions,
image_folder,
tokenizer,
image_processor,
model_config,
batch_size=1,
num_workers=4):
assert batch_size == 1, "batch_size must be 1"
dataset = CustomDataset(questions, image_folder, tokenizer,
image_processor, model_config)
data_loader = DataLoader(dataset,
batch_size=batch_size,
num_workers=num_workers,
shuffle=False)
return data_loader
def eval_model(args):
# Model
disable_torch_init()
model_path = os.path.expanduser(args.model_path)
model_name = get_model_name_from_path(model_path)
|
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
conv = build_conversation()
conv.append_message(conv.roles[0], qs)
conv.append_message(conv.roles[1], None)
prompt = conv.get_prompt()
image = Image.open(os.path.join(self.image_folder,
image_file)).convert('RGB')
image_tensor = process_images([image], self.image_processor,
self.model_config)[0]
input_ids = tokenizer_image_token(prompt,
self.tokenizer,
IMAGE_TOKEN_INDEX,
return_tensors='pt')
return input_ids, image_tensor
def __len__(self):
return len(self.questions)
# DataLoader
def create_data_loader(questions,
image_folder,
tokenizer,
image_processor,
model_config,
batch_size=1,
num_workers=4):
assert batch_size == 1, "batch_size must be 1"
dataset = CustomDataset(questions, image_folder, tokenizer,
image_processor, model_config)
data_loader = DataLoader(dataset,
batch_size=batch_size,
num_workers=num_workers,
shuffle=False)
return data_loader
def eval_model(args):
# Model
disable_torch_init()
model_path = os.path.expanduser(args.model_path)
model_name = get_model_name_from_path(model_path) | tokenizer, model, image_processor, context_len = load_pretrained_model( | 5 | 2023-11-10 03:52:46+00:00 | 4k |
vvvm23/TchAIkovsky | train.py | [
{
"identifier": "generate_splits",
"path": "data/dataset.py",
"snippet": "def generate_splits(dataset, splits: Tuple[float, float]):\n length = len(dataset)\n split_size = int(splits[0] * length)\n\n return torch.utils.data.Subset(dataset, range(split_size)), torch.utils.data.Subset(\n d... | import json
import equinox as eqx
import jax
import jax.numpy as jnp
import optax
import orbax.checkpoint as ocp
import tqdm
import wandb
from argparse import ArgumentParser
from datetime import datetime
from pathlib import Path
from jax.experimental import mesh_utils
from jax.sharding import PositionalSharding
from loguru import logger
from data import generate_splits, get_dataloader, get_dataset
from model import TchAIkovskyModel
from utils import seed_others | 1,972 |
def prepare_batch(batch, key=None):
input_ids = jnp.copy(batch["input_ids"][:, :-1])
labels = jnp.copy(batch["input_ids"][:, 1:])
labels = jnp.where(labels == 0, -100, labels)
position_ids = jnp.expand_dims(jnp.arange(labels.shape[-1]), 0).repeat(labels.shape[0], 0)
mask = jnp.asarray(batch["attention_mask"][:, :-1], dtype=bool)
keys = jax.random.split(key, input_ids.shape[0]) if key is not None else None
return dict(input_ids=input_ids, position_ids=position_ids, mask=mask), labels, keys
def loss_fn(model, batch, labels, keys=None):
if keys is None:
logits = jax.vmap(model[0])(**batch)
else:
logits = jax.vmap(model[0])(**batch, key=keys)
num_tokens = (labels != -100).sum()
accuracy = jnp.argmax(logits, axis=-1) == labels
loss = optax.softmax_cross_entropy_with_integer_labels(logits, labels)
accuracy = jnp.where(labels == -100, 0, accuracy).sum() / num_tokens
loss = jnp.where(labels == -100, 0, loss).sum() / num_tokens
return loss, accuracy
def create_train_step(model, optimiser):
opt_state = optimiser.init(eqx.filter(model, eqx.is_inexact_array))
# @eqx.debug.assert_max_traces(max_traces=1)
@eqx.filter_jit
def train_step(model, opt_state, batch, key):
# TODO: some of these arguments are different between first and second step
# need to investigate to avoid a double compile.
batch, labels, keys = prepare_batch(batch, key)
(loss, _), grads = eqx.filter_value_and_grad(loss_fn, has_aux=True)(model, batch, labels, keys)
updates, opt_state = optimiser.update(grads, opt_state, eqx.filter(model, eqx.is_inexact_array))
model = eqx.apply_updates(model, updates)
return model, opt_state, loss
# @eqx.debug.assert_max_traces(max_traces=1)
@eqx.filter_jit
def eval_step(model, batch):
batch, labels, _ = prepare_batch(batch)
loss, accuracy = loss_fn(model, batch, labels)
return loss, accuracy
return train_step, eval_step, opt_state
def wandb_init(args):
return wandb.init(
project="tchaikovsky",
config=vars(args),
mode=None if args.wandb else "disabled",
)
def setup_sharding(args):
devices = mesh_utils.create_device_mesh((len(jax.devices()),))
logger.info(devices)
sharding = PositionalSharding(devices)
return sharding, len(devices)
PRINT_INTERVAL = 4
def main(args):
logger.info("Beginning training script.")
key = jax.random.PRNGKey(args.seed)
seed_others(args.seed)
logger.info(f"Using PRNG key {args.seed}")
sharding, num_devices = setup_sharding(args)
if args.micro_batch_size is None:
args.micro_batch_size = args.batch_size
assert args.batch_size % args.micro_batch_size == 0
model_key, key = jax.random.split(key)
logger.info("Initialising model.")
model = TchAIkovskyModel(
dim=args.dim,
num_heads=args.heads,
num_layers=args.num_layers,
vocab_size=args.vocab_size,
max_positions=args.max_sequence_length,
head_dim=args.head_dim,
dropout=args.dropout,
key=model_key,
dtype=jnp.bfloat16 if args.use_bf16 else jnp.float32,
)
num_parameters = jax.tree_util.tree_reduce(lambda s, p: s + (p.size if eqx.is_inexact_array(p) else 0), model, 0)
logger.info(f"Model has {num_parameters:,} parameters.")
if args.use_bf16:
# map all params to bf16
logger.info("Training with bfloat16.")
model = jax.tree_util.tree_map(lambda p: p.astype(jnp.bfloat16) if eqx.is_inexact_array(p) else p, model)
logger.info("Initialising dataset.")
dataset = get_dataset(
dataset_root=args.dataset,
min_sequence_length=args.min_sequence_length,
max_sequence_length=args.max_sequence_length,
subset=args.subset_proportion,
)
val_dataset, train_dataset = generate_splits(dataset, (args.val_proportion, 1.0 - args.val_proportion))
logger.info(f"Training set size: {len(train_dataset):,} Validation set size: {len(val_dataset):,}")
|
def prepare_batch(batch, key=None):
input_ids = jnp.copy(batch["input_ids"][:, :-1])
labels = jnp.copy(batch["input_ids"][:, 1:])
labels = jnp.where(labels == 0, -100, labels)
position_ids = jnp.expand_dims(jnp.arange(labels.shape[-1]), 0).repeat(labels.shape[0], 0)
mask = jnp.asarray(batch["attention_mask"][:, :-1], dtype=bool)
keys = jax.random.split(key, input_ids.shape[0]) if key is not None else None
return dict(input_ids=input_ids, position_ids=position_ids, mask=mask), labels, keys
def loss_fn(model, batch, labels, keys=None):
if keys is None:
logits = jax.vmap(model[0])(**batch)
else:
logits = jax.vmap(model[0])(**batch, key=keys)
num_tokens = (labels != -100).sum()
accuracy = jnp.argmax(logits, axis=-1) == labels
loss = optax.softmax_cross_entropy_with_integer_labels(logits, labels)
accuracy = jnp.where(labels == -100, 0, accuracy).sum() / num_tokens
loss = jnp.where(labels == -100, 0, loss).sum() / num_tokens
return loss, accuracy
def create_train_step(model, optimiser):
opt_state = optimiser.init(eqx.filter(model, eqx.is_inexact_array))
# @eqx.debug.assert_max_traces(max_traces=1)
@eqx.filter_jit
def train_step(model, opt_state, batch, key):
# TODO: some of these arguments are different between first and second step
# need to investigate to avoid a double compile.
batch, labels, keys = prepare_batch(batch, key)
(loss, _), grads = eqx.filter_value_and_grad(loss_fn, has_aux=True)(model, batch, labels, keys)
updates, opt_state = optimiser.update(grads, opt_state, eqx.filter(model, eqx.is_inexact_array))
model = eqx.apply_updates(model, updates)
return model, opt_state, loss
# @eqx.debug.assert_max_traces(max_traces=1)
@eqx.filter_jit
def eval_step(model, batch):
batch, labels, _ = prepare_batch(batch)
loss, accuracy = loss_fn(model, batch, labels)
return loss, accuracy
return train_step, eval_step, opt_state
def wandb_init(args):
return wandb.init(
project="tchaikovsky",
config=vars(args),
mode=None if args.wandb else "disabled",
)
def setup_sharding(args):
devices = mesh_utils.create_device_mesh((len(jax.devices()),))
logger.info(devices)
sharding = PositionalSharding(devices)
return sharding, len(devices)
PRINT_INTERVAL = 4
def main(args):
logger.info("Beginning training script.")
key = jax.random.PRNGKey(args.seed)
seed_others(args.seed)
logger.info(f"Using PRNG key {args.seed}")
sharding, num_devices = setup_sharding(args)
if args.micro_batch_size is None:
args.micro_batch_size = args.batch_size
assert args.batch_size % args.micro_batch_size == 0
model_key, key = jax.random.split(key)
logger.info("Initialising model.")
model = TchAIkovskyModel(
dim=args.dim,
num_heads=args.heads,
num_layers=args.num_layers,
vocab_size=args.vocab_size,
max_positions=args.max_sequence_length,
head_dim=args.head_dim,
dropout=args.dropout,
key=model_key,
dtype=jnp.bfloat16 if args.use_bf16 else jnp.float32,
)
num_parameters = jax.tree_util.tree_reduce(lambda s, p: s + (p.size if eqx.is_inexact_array(p) else 0), model, 0)
logger.info(f"Model has {num_parameters:,} parameters.")
if args.use_bf16:
# map all params to bf16
logger.info("Training with bfloat16.")
model = jax.tree_util.tree_map(lambda p: p.astype(jnp.bfloat16) if eqx.is_inexact_array(p) else p, model)
logger.info("Initialising dataset.")
dataset = get_dataset(
dataset_root=args.dataset,
min_sequence_length=args.min_sequence_length,
max_sequence_length=args.max_sequence_length,
subset=args.subset_proportion,
)
val_dataset, train_dataset = generate_splits(dataset, (args.val_proportion, 1.0 - args.val_proportion))
logger.info(f"Training set size: {len(train_dataset):,} Validation set size: {len(val_dataset):,}")
| train_loader = get_dataloader( | 1 | 2023-11-13 07:31:30+00:00 | 4k |
LiquidFun/aoc_tiles | aoc_tiles/drawer.py | [
{
"identifier": "color_similarity",
"path": "aoc_tiles/colors.py",
"snippet": "def color_similarity(color_a, color_b, threshold):\n return abs(luminance(color_a) - luminance(color_b)) < threshold"
},
{
"identifier": "darker_color",
"path": "aoc_tiles/colors.py",
"snippet": "def darker... | import math
from functools import partial
from pathlib import Path
from typing import List, Tuple, Union, Dict
from PIL import ImageColor, Image
from PIL.ImageDraw import ImageDraw
from aoc_tiles.colors import color_similarity, darker_color, extension_to_colors
from aoc_tiles.config import Config
from aoc_tiles.fonts import main_font, secondary_font
from aoc_tiles.leaderboard import DayScores | 2,929 |
def format_time(time: str) -> str:
"""Formats time as mm:ss if the time is below 1 hour, otherwise it returns >1h to a max of >24h
>>> format_time("00:58:32")
'58:32'
>>> format_time(">1h")
' >1h'
"""
time = time.replace(">", ">")
if ">" in time:
formatted = time
else:
h, m, s = time.split(":")
formatted = f">{h}h" if int(h) >= 1 else f"{m:02}:{s:02}"
return f"{formatted:>5}"
class TileDrawer:
def __init__(self, config: Config):
self.config = config
def draw_tile(
self, day: str, languages: List[str], day_scores: Union[DayScores, None], path: Path, stars: int
):
"""Saves a graphic for a given day and year. Returns the path to it."""
image = self.get_alternating_background(languages, stars == 2)
drawer = ImageDraw(image)
text_kwargs = {"fill": self.config.text_color}
# Get all colors of the day, check if any one is similar to TEXT_COLOR
# If yes, add outline
for language in languages:
color = ImageColor.getrgb(extension_to_colors()[language])
|
def format_time(time: str) -> str:
"""Formats time as mm:ss if the time is below 1 hour, otherwise it returns >1h to a max of >24h
>>> format_time("00:58:32")
'58:32'
>>> format_time(">1h")
' >1h'
"""
time = time.replace(">", ">")
if ">" in time:
formatted = time
else:
h, m, s = time.split(":")
formatted = f">{h}h" if int(h) >= 1 else f"{m:02}:{s:02}"
return f"{formatted:>5}"
class TileDrawer:
def __init__(self, config: Config):
self.config = config
def draw_tile(
self, day: str, languages: List[str], day_scores: Union[DayScores, None], path: Path, stars: int
):
"""Saves a graphic for a given day and year. Returns the path to it."""
image = self.get_alternating_background(languages, stars == 2)
drawer = ImageDraw(image)
text_kwargs = {"fill": self.config.text_color}
# Get all colors of the day, check if any one is similar to TEXT_COLOR
# If yes, add outline
for language in languages:
color = ImageColor.getrgb(extension_to_colors()[language]) | if color_similarity(color, self.config.text_color, self.config.contrast_improvement_threshold): | 0 | 2023-11-14 21:41:12+00:00 | 4k |
etri-crossmodal/gbswt5 | gbswt5/modeling_gbst5.py | [
{
"identifier": "GBSWT5Config",
"path": "gbswt5/configuration_gbst5.py",
"snippet": "class GBSWT5Config(PretrainedConfig):\n \"\"\" Based on models.t5. configuration_t5. T5Config in hf Transformers. \"\"\"\n model_type = \"gbswt5\"\n keys_to_ignore_at_inference = [\"past_key_values\"]\n attr... | import copy
import torch
from typing import Optional, Union, Tuple
from torch import nn
from transformers import add_start_docstrings
from transformers.utils import logging
from transformers.modeling_outputs import (
BaseModelOutput,
BaseModelOutputWithPastAndCrossAttentions,
Seq2SeqLMOutput,
Seq2SeqModelOutput,
)
from transformers.models.t5.modeling_t5 import (
T5LayerNorm, T5Block, T5Stack,
T5Model, T5PreTrainedModel, T5ForConditionalGeneration, T5EncoderModel,
T5DenseActDense, T5DenseGatedActDense, T5Attention,
T5_START_DOCSTRING
)
from .configuration_gbst5 import GBSWT5Config
from .gbst import GBSWT | 3,357 | """
hf transformers-compatible GBST + T5 Model implementation.
several methods are copying from huggingface/transformers/models/t5/modeling_t5.py
as Implementation Standards for compatibility. (version 4.28.1)
hf transformers' modeling_t5.py file is distributed under Apache 2.0 License.
Copyright (C) 2023, ETRI LIRS, Jong-hun Shin.
"""
logger = logging.get_logger(__name__)
class GBSWT5PreTrainedModel(T5PreTrainedModel):
| """
hf transformers-compatible GBST + T5 Model implementation.
several methods are copying from huggingface/transformers/models/t5/modeling_t5.py
as Implementation Standards for compatibility. (version 4.28.1)
hf transformers' modeling_t5.py file is distributed under Apache 2.0 License.
Copyright (C) 2023, ETRI LIRS, Jong-hun Shin.
"""
logger = logging.get_logger(__name__)
class GBSWT5PreTrainedModel(T5PreTrainedModel): | config_class = GBSWT5Config | 0 | 2023-11-17 02:04:46+00:00 | 4k |
GOAT-AI-lab/GOAT-Storytelling-Agent | goat_storytelling_agent/storytelling_agent.py | [
{
"identifier": "utils",
"path": "goat_storytelling_agent/utils.py",
"snippet": "def split_into_words_w_newline(text):\ndef remove_last_n_words(text, n):\ndef keep_last_n_words(text, n):"
},
{
"identifier": "Plan",
"path": "goat_storytelling_agent/plan.py",
"snippet": "class Plan:\n @... | import sys
import time
import re
import json
import requests
import traceback
from goat_storytelling_agent import utils
from goat_storytelling_agent.plan import Plan
from transformers import LlamaTokenizerFast
from goat_storytelling_agent import prompts | 3,172 | act = self.query_chat(messages)
if act:
act_dict = Plan.parse_act(act)
while len(act_dict['chapters']) < 2:
act = self.query_chat(messages)
act_dict = Plan.parse_act(act)
else:
plan[act_num] = act_dict
text_plan = Plan.plan_2_str(plan)
all_messages.append(messages)
return all_messages, plan
def split_chapters_into_scenes(self, plan):
"""Creates a by-scene breakdown of all chapters
Parameters
----------
plan : Dict
Dict with book plan
Returns
-------
List[Dict]
Used messages for logging
dict
Dict with updated book plan
"""
all_messages = []
act_chapters = {}
for i, act in enumerate(plan, start=1):
text_act, chs = Plan.act_2_str(plan, i)
act_chapters[i] = chs
messages = self.prompt_engine.split_chapters_into_scenes_messages(
i, text_act, self.form)
act_scenes = self.query_chat(messages)
act['act_scenes'] = act_scenes
all_messages.append(messages)
for i, act in enumerate(plan, start=1):
act_scenes = act['act_scenes']
act_scenes = re.split(r'Chapter (\d+)', act_scenes.strip())
act['chapter_scenes'] = {}
chapters = [text.strip() for text in act_scenes[:]
if (text and text.strip())]
current_ch = None
merged_chapters = {}
for snippet in chapters:
if snippet.isnumeric():
ch_num = int(snippet)
if ch_num != current_ch:
current_ch = snippet
merged_chapters[ch_num] = ''
continue
if merged_chapters:
merged_chapters[ch_num] += snippet
ch_nums = list(merged_chapters.keys()) if len(
merged_chapters) <= len(act_chapters[i]) else act_chapters[i]
merged_chapters = {ch_num: merged_chapters[ch_num]
for ch_num in ch_nums}
for ch_num, chapter in merged_chapters.items():
scenes = re.split(r'Scene \d+.{0,10}?:', chapter)
scenes = [text.strip() for text in scenes[1:]
if (text and (len(text.split()) > 3))]
if not scenes:
continue
act['chapter_scenes'][ch_num] = scenes
return all_messages, plan
@staticmethod
def prepare_scene_text(text):
lines = text.split('\n')
ch_ids = [i for i in range(5)
if 'Chapter ' in lines[i]]
if ch_ids:
lines = lines[ch_ids[-1]+1:]
sc_ids = [i for i in range(5)
if 'Scene ' in lines[i]]
if sc_ids:
lines = lines[sc_ids[-1]+1:]
placeholder_i = None
for i in range(len(lines)):
if lines[i].startswith('Chapter ') or lines[i].startswith('Scene '):
placeholder_i = i
break
if placeholder_i is not None:
lines = lines[:i]
text = '\n'.join(lines)
return text
def write_a_scene(
self, scene, sc_num, ch_num, plan, previous_scene=None):
"""Generates a scene text for a form
Parameters
----------
scene : str
Scene description
sc_num : int
Scene number
ch_num : int
Chapter number
plan : Dict
Dict with book plan
previous_scene : str, optional
Previous scene text, by default None
Returns
-------
List[Dict]
Used messages for logging
str
Generated scene text
"""
text_plan = Plan.plan_2_str(plan)
messages = self.prompt_engine.scene_messages(
scene, sc_num, ch_num, text_plan, self.form)
if previous_scene:
|
SUPPORTED_BACKENDS = ["hf", "llama.cpp"]
def generate_prompt_parts(
messages, include_roles=set(('user', 'assistant', 'system'))):
last_role = None
messages = [m for m in messages if m['role'] in include_roles]
for idx, message in enumerate(messages):
nl = "\n" if idx > 0 else ""
if message['role'] == 'system':
if idx > 0 and last_role not in (None, "system"):
raise ValueError("system message not at start")
yield f"{message['content']}"
elif message['role'] == 'user':
yield f"{nl}### USER: {message['content']}"
elif message['role'] == 'assistant':
yield f"{nl}### ASSISTANT: {message['content']}"
last_role = message['role']
if last_role != 'assistant':
yield '\n### ASSISTANT:'
def _query_chat_hf(endpoint, messages, tokenizer, retries=3,
request_timeout=120, max_tokens=4096,
extra_options={'do_sample': True}):
endpoint = endpoint.rstrip('/')
prompt = ''.join(generate_prompt_parts(messages))
tokens = tokenizer(prompt, add_special_tokens=True,
truncation=False)['input_ids']
data = {
"inputs": prompt,
"parameters": {
'max_new_tokens': max_tokens - len(tokens),
**extra_options
}
}
headers = {'Content-Type': 'application/json'}
while retries > 0:
try:
response = requests.post(
f"{endpoint}/generate", headers=headers, data=json.dumps(data),
timeout=request_timeout)
if messages and messages[-1]["role"] == "assistant":
result_prefix = messages[-1]["content"]
else:
result_prefix = ''
generated_text = result_prefix + json.loads(
response.text)['generated_text']
return generated_text
except Exception:
traceback.print_exc()
print('Timeout error, retrying...')
retries -= 1
time.sleep(5)
else:
return ''
def _query_chat_llamacpp(endpoint, messages, retries=3, request_timeout=120,
max_tokens=4096, extra_options={}):
endpoint = endpoint.rstrip('/')
headers = {'Content-Type': 'application/json'}
prompt = ''.join(generate_prompt_parts(messages))
print(f"\n\n========== Submitting prompt: >>\n{prompt}", end="")
sys.stdout.flush()
response = requests.post(
f"{endpoint}/tokenize", headers=headers,
data=json.dumps({"content": prompt}),
timeout=request_timeout, stream=False)
tokens = [1, *response.json()["tokens"]]
data = {
"prompt": tokens,
"stream": True,
"n_predict": max_tokens - len(tokens),
**extra_options,
}
jdata = json.dumps(data)
request_kwargs = dict(headers=headers, data=jdata,
timeout=request_timeout, stream=True)
response = requests.post(f"{endpoint}/completion", **request_kwargs)
result = bytearray()
if messages and messages[-1]["role"] == "assistant":
result += messages[-1]["content"].encode("utf-8")
is_first = True
for line in response.iter_lines():
line = line.strip()
if not line:
continue
if line.startswith(b"error:"):
retries -= 1
print(f"\nError(retry={retries}): {line!r}")
if retries < 0:
break
del response
time.sleep(5)
response = requests.post(f"{endpoint}/completion", **request_kwargs)
is_first = True
result.clear()
continue
if not line.startswith(b"data: "):
raise ValueError(f"Got unexpected response: {line!r}")
parsed = json.loads(line[6:])
content = parsed.get("content", b"")
result += bytes(content, encoding="utf-8")
if is_first:
is_first = False
print("<<|", end="")
sys.stdout.flush()
print(content, end="")
sys.stdout.flush()
if parsed.get("stop") is True:
break
print("\nDone reading response.")
return str(result, encoding="utf-8").strip()
class StoryAgent:
def __init__(self, backend_uri, backend="hf", request_timeout=120,
max_tokens=4096, n_crop_previous=400,
prompt_engine=None, form='novel',
extra_options={}, scene_extra_options={}):
self.backend = backend.lower()
if self.backend not in SUPPORTED_BACKENDS:
raise ValueError("Unknown backend")
if self.backend == "hf":
self.tokenizer = LlamaTokenizerFast.from_pretrained(
"GOAT-AI/GOAT-70B-Storytelling")
if prompt_engine is None:
self.prompt_engine = prompts
else:
self.prompt_engine = prompt_engine
self.form = form
self.max_tokens = max_tokens
self.extra_options = extra_options
self.scene_extra_options = extra_options.copy()
self.scene_extra_options.update(scene_extra_options)
self.backend_uri = backend_uri
self.n_crop_previous = n_crop_previous
self.request_timeout = request_timeout
def query_chat(self, messages, retries=3):
if self.backend == "hf":
result = _query_chat_hf(
self.backend_uri, messages, self.tokenizer, retries=retries,
request_timeout=self.request_timeout,
max_tokens=self.max_tokens, extra_options=self.extra_options)
elif self.backend == "llama.cpp":
result = _query_chat_llamacpp(
self.backend_uri, messages, retries=retries,
request_timeout=self.request_timeout,
max_tokens=self.max_tokens, extra_options=self.extra_options)
return result
def parse_book_spec(self, text_spec):
# Initialize book spec dict with empty fields
fields = self.prompt_engine.book_spec_fields
spec_dict = {field: '' for field in fields}
last_field = None
if "\"\"\"" in text_spec[:int(len(text_spec)/2)]:
header, sep, text_spec = text_spec.partition("\"\"\"")
text_spec = text_spec.strip()
# Process raw spec into dict
for line in text_spec.split('\n'):
pseudokey, sep, value = line.partition(':')
pseudokey = pseudokey.lower().strip()
matched_key = [key for key in fields
if (key.lower().strip() in pseudokey)
and (len(pseudokey) < (2 * len(key.strip())))]
if (':' in line) and (len(matched_key) == 1):
last_field = matched_key[0]
if last_field in spec_dict:
spec_dict[last_field] += value.strip()
elif ':' in line:
last_field = 'other'
spec_dict[last_field] = ''
else:
if last_field:
# If line does not contain ':' it should be
# the continuation of the last field's value
spec_dict[last_field] += ' ' + line.strip()
spec_dict.pop('other', None)
return spec_dict
def init_book_spec(self, topic):
"""Creates initial book specification
Parameters
----------
topic : str
Short initial topic
Returns
-------
List[Dict]
Used messages for logging
str
Book specification text
"""
messages = self.prompt_engine.init_book_spec_messages(topic, self.form)
text_spec = self.query_chat(messages)
spec_dict = self.parse_book_spec(text_spec)
text_spec = "\n".join(f"{key}: {value}"
for key, value in spec_dict.items())
# Check and fill in missing fields
for field in self.prompt_engine.book_spec_fields:
while not spec_dict[field]:
messages = self.prompt_engine.missing_book_spec_messages(
field, text_spec)
missing_part = self.query_chat(messages)
key, sep, value = missing_part.partition(':')
if key.lower().strip() == field.lower().strip():
spec_dict[field] = value.strip()
text_spec = "\n".join(f"{key}: {value}"
for key, value in spec_dict.items())
return messages, text_spec
def enhance_book_spec(self, book_spec):
"""Make book specification more detailed
Parameters
----------
book_spec : str
Book specification
Returns
-------
List[Dict]
Used messages for logging
str
Book specification text
"""
messages = self.prompt_engine.enhance_book_spec_messages(
book_spec, self.form)
text_spec = self.query_chat(messages)
spec_dict_old = self.parse_book_spec(book_spec)
spec_dict_new = self.parse_book_spec(text_spec)
# Check and fill in missing fields
for field in self.prompt_engine.book_spec_fields:
if not spec_dict_new[field]:
spec_dict_new[field] = spec_dict_old[field]
text_spec = "\n".join(f"{key}: {value}"
for key, value in spec_dict_new.items())
return messages, text_spec
def create_plot_chapters(self, book_spec):
"""Create initial by-plot outline of form
Parameters
----------
book_spec : str
Book specification
Returns
-------
List[Dict]
Used messages for logging
dict
Dict with book plan
"""
messages = self.prompt_engine.create_plot_chapters_messages(book_spec, self.form)
plan = []
while not plan:
text_plan = self.query_chat(messages)
if text_plan:
plan = Plan.parse_text_plan(text_plan)
return messages, plan
def enhance_plot_chapters(self, book_spec, plan):
"""Enhances the outline to make the flow more engaging
Parameters
----------
book_spec : str
Book specification
plan : Dict
Dict with book plan
Returns
-------
List[Dict]
Used messages for logging
dict
Dict with updated book plan
"""
text_plan = Plan.plan_2_str(plan)
all_messages = []
for act_num in range(3):
messages = self.prompt_engine.enhance_plot_chapters_messages(
act_num, text_plan, book_spec, self.form)
act = self.query_chat(messages)
if act:
act_dict = Plan.parse_act(act)
while len(act_dict['chapters']) < 2:
act = self.query_chat(messages)
act_dict = Plan.parse_act(act)
else:
plan[act_num] = act_dict
text_plan = Plan.plan_2_str(plan)
all_messages.append(messages)
return all_messages, plan
def split_chapters_into_scenes(self, plan):
"""Creates a by-scene breakdown of all chapters
Parameters
----------
plan : Dict
Dict with book plan
Returns
-------
List[Dict]
Used messages for logging
dict
Dict with updated book plan
"""
all_messages = []
act_chapters = {}
for i, act in enumerate(plan, start=1):
text_act, chs = Plan.act_2_str(plan, i)
act_chapters[i] = chs
messages = self.prompt_engine.split_chapters_into_scenes_messages(
i, text_act, self.form)
act_scenes = self.query_chat(messages)
act['act_scenes'] = act_scenes
all_messages.append(messages)
for i, act in enumerate(plan, start=1):
act_scenes = act['act_scenes']
act_scenes = re.split(r'Chapter (\d+)', act_scenes.strip())
act['chapter_scenes'] = {}
chapters = [text.strip() for text in act_scenes[:]
if (text and text.strip())]
current_ch = None
merged_chapters = {}
for snippet in chapters:
if snippet.isnumeric():
ch_num = int(snippet)
if ch_num != current_ch:
current_ch = snippet
merged_chapters[ch_num] = ''
continue
if merged_chapters:
merged_chapters[ch_num] += snippet
ch_nums = list(merged_chapters.keys()) if len(
merged_chapters) <= len(act_chapters[i]) else act_chapters[i]
merged_chapters = {ch_num: merged_chapters[ch_num]
for ch_num in ch_nums}
for ch_num, chapter in merged_chapters.items():
scenes = re.split(r'Scene \d+.{0,10}?:', chapter)
scenes = [text.strip() for text in scenes[1:]
if (text and (len(text.split()) > 3))]
if not scenes:
continue
act['chapter_scenes'][ch_num] = scenes
return all_messages, plan
@staticmethod
def prepare_scene_text(text):
lines = text.split('\n')
ch_ids = [i for i in range(5)
if 'Chapter ' in lines[i]]
if ch_ids:
lines = lines[ch_ids[-1]+1:]
sc_ids = [i for i in range(5)
if 'Scene ' in lines[i]]
if sc_ids:
lines = lines[sc_ids[-1]+1:]
placeholder_i = None
for i in range(len(lines)):
if lines[i].startswith('Chapter ') or lines[i].startswith('Scene '):
placeholder_i = i
break
if placeholder_i is not None:
lines = lines[:i]
text = '\n'.join(lines)
return text
def write_a_scene(
self, scene, sc_num, ch_num, plan, previous_scene=None):
"""Generates a scene text for a form
Parameters
----------
scene : str
Scene description
sc_num : int
Scene number
ch_num : int
Chapter number
plan : Dict
Dict with book plan
previous_scene : str, optional
Previous scene text, by default None
Returns
-------
List[Dict]
Used messages for logging
str
Generated scene text
"""
text_plan = Plan.plan_2_str(plan)
messages = self.prompt_engine.scene_messages(
scene, sc_num, ch_num, text_plan, self.form)
if previous_scene: | previous_scene = utils.keep_last_n_words(previous_scene, | 0 | 2023-11-17 11:53:00+00:00 | 4k |
dazhangyu123/ACMIL | modules/topk/polynomial/sp.py | [
{
"identifier": "divide_and_conquer",
"path": "modules/topk/polynomial/divide_conquer.py",
"snippet": "def divide_and_conquer(x, k, mul):\n \"\"\"\n Divide and conquer method for polynomial expansion\n x is a 2d tensor of size (n_classes, n_roots)\n The objective is to obtain the k first coe... | import torch
import torch.nn as nn
import torch.autograd as ag
from .divide_conquer import divide_and_conquer
from .multiplication import Multiplication
from .grad import d_logS_d_expX | 1,761 |
class LogSumExp(nn.Module):
def __init__(self, k, p=None, thresh=1e-5):
super(LogSumExp, self).__init__()
self.k = k
self.p = int(1 + 0.2 * k) if p is None else p
self.mul = Multiplication(self.k + self.p - 1)
self.thresh = thresh
self.register_buffer('grad_k', torch.Tensor(0))
self.register_buffer('grad_km1', torch.Tensor(0))
self.buffers = (self.grad_km1, self.grad_k)
def forward(self, x):
f = LogSumExp_F()
return f.apply(x, self.k, self.p, self.thresh, self.mul, self.buffers)
class LogSumExp_F(ag.Function):
@staticmethod
def forward(self, x, k, p, thresh, mul, buffers):
"""
Returns a matrix of size (2, n_samples) with sigma_{k-1} and sigma_{k}
for each sample of the mini-batch.
"""
self.save_for_backward(x)
self.k, self.p, self.thresh = k, p, thresh
# unpack buffers
self.grad_km1, self.grad_k = buffers
# number of samples and number of coefficients to compute
n_s = x.size(0)
kp = self.k + self.p - 1
assert kp <= x.size(1)
# clone to allow in-place operations
x = x.clone()
# pre-compute normalization
x_summed = x.sum(1)
# invert in log-space
x.t_().mul_(-1)
# initialize polynomials (in log-space)
x = [x, x.clone().fill_(0)]
# polynomial multiplications
|
class LogSumExp(nn.Module):
def __init__(self, k, p=None, thresh=1e-5):
super(LogSumExp, self).__init__()
self.k = k
self.p = int(1 + 0.2 * k) if p is None else p
self.mul = Multiplication(self.k + self.p - 1)
self.thresh = thresh
self.register_buffer('grad_k', torch.Tensor(0))
self.register_buffer('grad_km1', torch.Tensor(0))
self.buffers = (self.grad_km1, self.grad_k)
def forward(self, x):
f = LogSumExp_F()
return f.apply(x, self.k, self.p, self.thresh, self.mul, self.buffers)
class LogSumExp_F(ag.Function):
@staticmethod
def forward(self, x, k, p, thresh, mul, buffers):
"""
Returns a matrix of size (2, n_samples) with sigma_{k-1} and sigma_{k}
for each sample of the mini-batch.
"""
self.save_for_backward(x)
self.k, self.p, self.thresh = k, p, thresh
# unpack buffers
self.grad_km1, self.grad_k = buffers
# number of samples and number of coefficients to compute
n_s = x.size(0)
kp = self.k + self.p - 1
assert kp <= x.size(1)
# clone to allow in-place operations
x = x.clone()
# pre-compute normalization
x_summed = x.sum(1)
# invert in log-space
x.t_().mul_(-1)
# initialize polynomials (in log-space)
x = [x, x.clone().fill_(0)]
# polynomial multiplications | log_res = divide_and_conquer(x, kp, mul=mul) | 0 | 2023-11-12 14:07:34+00:00 | 4k |
Kav-K/Described | discord_service/cogs/image_service_cog.py | [
{
"identifier": "EmbedStatics",
"path": "discord_service/embeds/embed_helper.py",
"snippet": "class EmbedStatics:\n def __init__(self):\n pass\n\n def status_to_string(status):\n if status:\n return \"enabled\"\n else:\n return \"disabled\"\n\n @static... | import pickle
import re
import traceback
import aiofiles
import discord
from collections import defaultdict
from pathlib import Path
from discord_service.embeds.embed_helper import EmbedStatics
from services.check_service import Check
from services.environment_service import EnvService
from services.openai_service import OpenAIExecutor | 2,708 |
class ServerInformation:
def __init__(self, status: bool = False):
self.status = status
class ImageService(discord.Cog, name="ImageService"):
"""cog containing the optimizer command"""
async def change_guild_status(self, guild_id, status: bool):
self.server_information[guild_id].status = status
try:
directory_path = Path(EnvService.save_path()) / "pickles"
directory_path.mkdir(parents=True, exist_ok=True)
async with aiofiles.open(
EnvService.save_path() / "pickles" / "server_information.pickle",
"wb",
) as f:
await f.write(pickle.dumps(self.server_information))
return True
except:
traceback.print_exc()
print("Could not save server information to disk after update.")
return False
def __init__(
self,
bot,
):
super().__init__()
self.bot = bot
self.openai_service = OpenAIExecutor()
self.allowed_channels = EnvService.get_described_channels()
try:
with open(
EnvService.save_path() / "pickles" / "server_information.pickle",
"rb",
) as f:
self.server_information = pickle.load(f)
print("Loaded server information pickle.")
except:
self.server_information = defaultdict(ServerInformation)
for guild in self.bot.guilds:
self.server_information[guild.id] = ServerInformation(False)
@discord.slash_command(
name="describe",
description="Turn image descriptions on or off for the server.",
guild_ids=EnvService.get_allowed_guilds(),
|
class ServerInformation:
def __init__(self, status: bool = False):
self.status = status
class ImageService(discord.Cog, name="ImageService"):
"""cog containing the optimizer command"""
async def change_guild_status(self, guild_id, status: bool):
self.server_information[guild_id].status = status
try:
directory_path = Path(EnvService.save_path()) / "pickles"
directory_path.mkdir(parents=True, exist_ok=True)
async with aiofiles.open(
EnvService.save_path() / "pickles" / "server_information.pickle",
"wb",
) as f:
await f.write(pickle.dumps(self.server_information))
return True
except:
traceback.print_exc()
print("Could not save server information to disk after update.")
return False
def __init__(
self,
bot,
):
super().__init__()
self.bot = bot
self.openai_service = OpenAIExecutor()
self.allowed_channels = EnvService.get_described_channels()
try:
with open(
EnvService.save_path() / "pickles" / "server_information.pickle",
"rb",
) as f:
self.server_information = pickle.load(f)
print("Loaded server information pickle.")
except:
self.server_information = defaultdict(ServerInformation)
for guild in self.bot.guilds:
self.server_information[guild.id] = ServerInformation(False)
@discord.slash_command(
name="describe",
description="Turn image descriptions on or off for the server.",
guild_ids=EnvService.get_allowed_guilds(), | checks=[Check.check_admin_roles()], | 1 | 2023-11-14 02:22:13+00:00 | 4k |
juftin/hatch-pip-compile | hatch_pip_compile/plugin.py | [
{
"identifier": "HatchPipCompileError",
"path": "hatch_pip_compile/exceptions.py",
"snippet": "class HatchPipCompileError(Exception):\n \"\"\"\n Base exception for hatch-pip-compile\n \"\"\""
},
{
"identifier": "PipInstaller",
"path": "hatch_pip_compile/installer.py",
"snippet":... | import functools
import hashlib
import logging
import os
import pathlib
import shutil
import tempfile
from subprocess import CompletedProcess
from typing import Any, Dict, List, Optional, Union
from hatch.env.virtual import VirtualEnvironment
from hatch.utils.platform import Platform
from hatchling.dep.core import dependencies_in_sync
from packaging.requirements import Requirement
from hatch_pip_compile.exceptions import HatchPipCompileError
from hatch_pip_compile.installer import PipInstaller, PipSyncInstaller, PluginInstaller
from hatch_pip_compile.lock import PipCompileLock | 2,800 | """
hatch-pip-compile plugin
"""
logger = logging.getLogger(__name__)
class PipCompileEnvironment(VirtualEnvironment):
"""
Virtual Environment supported by pip-compile
"""
PLUGIN_NAME = "pip-compile"
default_env_name = "default"
def __repr__(self):
"""
Get representation of PipCompileEnvironment
"""
return f"<{self.__class__.__name__} - {self.name}>"
def __init__(self, *args, **kwargs) -> None:
"""
Initialize PipCompileEnvironment with extra attributes
"""
super().__init__(*args, **kwargs)
lock_filename_config = self.config.get("lock-filename")
if lock_filename_config is None:
if self.name == self.default_env_name:
lock_filename = "requirements.txt"
else:
lock_filename = f"requirements/requirements-{self.name}.txt"
else:
with self.metadata.context.apply_context(self.context):
lock_filename = self.metadata.context.format(lock_filename_config)
self.piptools_lock_file = self.root / lock_filename
self.piptools_lock = PipCompileLock(
lock_file=self.piptools_lock_file,
dependencies=self.dependencies,
virtualenv=self.virtual_env,
constraints_file=self.piptools_constraints_file,
project_root=self.root,
env_name=self.name,
project_name=self.metadata.name,
)
install_method = self.config.get("pip-compile-installer", "pip")
self.installer: PluginInstaller
if install_method == "pip":
self.installer = PipInstaller(environment=self)
elif install_method == "pip-sync":
self.installer = PipSyncInstaller(environment=self)
else:
msg = (
f"Invalid pip-tools install method: {install_method} - "
"must be 'pip' or 'pip-sync'"
)
| """
hatch-pip-compile plugin
"""
logger = logging.getLogger(__name__)
class PipCompileEnvironment(VirtualEnvironment):
"""
Virtual Environment supported by pip-compile
"""
PLUGIN_NAME = "pip-compile"
default_env_name = "default"
def __repr__(self):
"""
Get representation of PipCompileEnvironment
"""
return f"<{self.__class__.__name__} - {self.name}>"
def __init__(self, *args, **kwargs) -> None:
"""
Initialize PipCompileEnvironment with extra attributes
"""
super().__init__(*args, **kwargs)
lock_filename_config = self.config.get("lock-filename")
if lock_filename_config is None:
if self.name == self.default_env_name:
lock_filename = "requirements.txt"
else:
lock_filename = f"requirements/requirements-{self.name}.txt"
else:
with self.metadata.context.apply_context(self.context):
lock_filename = self.metadata.context.format(lock_filename_config)
self.piptools_lock_file = self.root / lock_filename
self.piptools_lock = PipCompileLock(
lock_file=self.piptools_lock_file,
dependencies=self.dependencies,
virtualenv=self.virtual_env,
constraints_file=self.piptools_constraints_file,
project_root=self.root,
env_name=self.name,
project_name=self.metadata.name,
)
install_method = self.config.get("pip-compile-installer", "pip")
self.installer: PluginInstaller
if install_method == "pip":
self.installer = PipInstaller(environment=self)
elif install_method == "pip-sync":
self.installer = PipSyncInstaller(environment=self)
else:
msg = (
f"Invalid pip-tools install method: {install_method} - "
"must be 'pip' or 'pip-sync'"
) | raise HatchPipCompileError(msg) | 0 | 2023-11-10 00:34:00+00:00 | 4k |
google-deepmind/pix2act | pix2act/tasks/webshop/write_tf_examples.py | [
{
"identifier": "env_utils",
"path": "pix2act/common/env_utils.py",
"snippet": "class EnvConfig:\nclass CursorState:\ndef rel_x_y_to_x_y(env_config, x_rel, y_rel):\ndef is_float(element: str) -> bool:\ndef is_valid_coordinate(env_config: EnvConfig, x_str: str, y_str: str) -> bool:\ndef is_valid(env_conf... | import json
import os
import typing
import tensorflow as tf
from typing import Any, Dict, List
from absl import app
from absl import flags
from pix2act.common import env_utils
from pix2act.common import render_utils
from pix2act.common import tf_utils
from pix2act.tasks.webshop import demo_utils
from pix2act.tasks.webshop import webshop_env
from selenium import webdriver
from selenium.common import exceptions | 2,092 |
r"""Converts demonstrations to tf examples for training, validation, and test.
# pylint:disable=long-too-long
This requires that the Webshop server is running locally. See the official repo
for setup instructions: https://github.com/princeton-nlp/WebShop
Follows split and preprocessing here from the get_data method here:
https://github.com/princeton-nlp/WebShop/blob/master/baseline_models/train_choice_il.py
# pylint:enable=long-too-long
"""
FLAGS = flags.FLAGS
flags.DEFINE_string(
"webshop_url",
"http://localhost:3000/",
"Webshop server URL.",
)
flags.DEFINE_string(
"demo_file",
"",
"File containing high-level demonstrations.",
)
flags.DEFINE_string(
"human_goals_file",
"",
"Human goals file which dictates train/dev/test split.",
)
flags.DEFINE_string(
"processed_dir",
"",
"Processed dir name.",
)
flags.DEFINE_float(
"reward_threshold",
0.1,
"Demonstrations below this threshold will be discarded.",
)
flags.DEFINE_bool(
"do_word_input_search",
True,
"Use word level input for search.",
)
flags.DEFINE_bool(
"skip_test",
True,
"Skips test split if true.",
)
flags.DEFINE_string(
"cursor_dir",
"gs://pix2act-data/cursors/",
"Directory with cursor files.",
)
flags.DEFINE_bool(
"render_action_history",
False,
"Renders action history on the screenshot if true.",
)
flags.DEFINE_integer(
"num_prepend_actions",
5,
"Prepends these many previous actions to parse before current actions.",
)
flags.DEFINE_integer(
"max_action_chars",
200,
(
"Max num of chars which can be rendered on the action section of the"
" input."
),
)
def process_data(driver):
"""Process and split data according to the official WebShop repo."""
env_config = webshop_env.get_env_config(FLAGS.cursor_dir)
demos = demo_utils.read_demos_file(FLAGS.demo_file)
human_goals = demo_utils.read_goals_file(FLAGS.human_goals_file)
split_info = {}
for split in demo_utils.SPLITS.keys():
split_info[split] = {"num_processed": 0, "rewards": {}}
for demo_idx, demo in enumerate(demos):
demo_examples = []
_, goal_idx = demo_utils.process_goal(demo["states"][0], human_goals)
split = demo_utils.get_split(goal_idx)
if FLAGS.skip_test and split == "test":
continue
print("Processing %d out of %d" % (demo_idx, len(demos)))
driver.get(FLAGS.webshop_url + "fixed_%d" % goal_idx)
instruction_text = demo_utils.get_instruction_text(driver)
cursor_state = env_utils.CursorState()
for i, (demo_action, demo_action_translate) in enumerate(
zip(demo["actions"], demo["actions_translate"])
):
for low_level_action, _ in demo_utils.convert_action(
driver, demo_action, demo_action_translate, FLAGS.do_word_input_search
):
parse = low_level_action
history = demo_utils.get_action_history(
demo_examples,
FLAGS.num_prepend_actions,
)
current_frame = env_utils.get_screenshot(
driver, env_config, cursor_state
)
| # 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 demonstrations to tf examples for training, validation, and test.
# pylint:disable=long-too-long
This requires that the Webshop server is running locally. See the official repo
for setup instructions: https://github.com/princeton-nlp/WebShop
Follows split and preprocessing here from the get_data method here:
https://github.com/princeton-nlp/WebShop/blob/master/baseline_models/train_choice_il.py
# pylint:enable=long-too-long
"""
FLAGS = flags.FLAGS
flags.DEFINE_string(
"webshop_url",
"http://localhost:3000/",
"Webshop server URL.",
)
flags.DEFINE_string(
"demo_file",
"",
"File containing high-level demonstrations.",
)
flags.DEFINE_string(
"human_goals_file",
"",
"Human goals file which dictates train/dev/test split.",
)
flags.DEFINE_string(
"processed_dir",
"",
"Processed dir name.",
)
flags.DEFINE_float(
"reward_threshold",
0.1,
"Demonstrations below this threshold will be discarded.",
)
flags.DEFINE_bool(
"do_word_input_search",
True,
"Use word level input for search.",
)
flags.DEFINE_bool(
"skip_test",
True,
"Skips test split if true.",
)
flags.DEFINE_string(
"cursor_dir",
"gs://pix2act-data/cursors/",
"Directory with cursor files.",
)
flags.DEFINE_bool(
"render_action_history",
False,
"Renders action history on the screenshot if true.",
)
flags.DEFINE_integer(
"num_prepend_actions",
5,
"Prepends these many previous actions to parse before current actions.",
)
flags.DEFINE_integer(
"max_action_chars",
200,
(
"Max num of chars which can be rendered on the action section of the"
" input."
),
)
def process_data(driver):
"""Process and split data according to the official WebShop repo."""
env_config = webshop_env.get_env_config(FLAGS.cursor_dir)
demos = demo_utils.read_demos_file(FLAGS.demo_file)
human_goals = demo_utils.read_goals_file(FLAGS.human_goals_file)
split_info = {}
for split in demo_utils.SPLITS.keys():
split_info[split] = {"num_processed": 0, "rewards": {}}
for demo_idx, demo in enumerate(demos):
demo_examples = []
_, goal_idx = demo_utils.process_goal(demo["states"][0], human_goals)
split = demo_utils.get_split(goal_idx)
if FLAGS.skip_test and split == "test":
continue
print("Processing %d out of %d" % (demo_idx, len(demos)))
driver.get(FLAGS.webshop_url + "fixed_%d" % goal_idx)
instruction_text = demo_utils.get_instruction_text(driver)
cursor_state = env_utils.CursorState()
for i, (demo_action, demo_action_translate) in enumerate(
zip(demo["actions"], demo["actions_translate"])
):
for low_level_action, _ in demo_utils.convert_action(
driver, demo_action, demo_action_translate, FLAGS.do_word_input_search
):
parse = low_level_action
history = demo_utils.get_action_history(
demo_examples,
FLAGS.num_prepend_actions,
)
current_frame = env_utils.get_screenshot(
driver, env_config, cursor_state
) | current_frame = render_utils.render_header( | 1 | 2023-11-13 22:50:55+00:00 | 4k |
zhang-tao-whu/DVIS_Plus | mask2former_video/modeling/transformer_decoder/video_mask2former_transformer_decoder.py | [
{
"identifier": "TRANSFORMER_DECODER_REGISTRY",
"path": "mask2former/modeling/transformer_decoder/maskformer_transformer_decoder.py",
"snippet": "TRANSFORMER_DECODER_REGISTRY = Registry(\"TRANSFORMER_MODULE\")"
},
{
"identifier": "PositionEmbeddingSine3D",
"path": "mask2former_video/modeling... | import logging
import fvcore.nn.weight_init as weight_init
import torch
from typing import Optional
from torch import nn, Tensor
from torch.nn import functional as F
from detectron2.config import configurable
from detectron2.layers import Conv2d
from mask2former.modeling.transformer_decoder.maskformer_transformer_decoder import TRANSFORMER_DECODER_REGISTRY
from .position_encoding import PositionEmbeddingSine3D | 2,505 |
self._reset_parameters()
def _reset_parameters(self):
for p in self.parameters():
if p.dim() > 1:
nn.init.xavier_uniform_(p)
def with_pos_embed(self, tensor, pos: Optional[Tensor]):
return tensor if pos is None else tensor + pos
def forward_post(self, tgt, memory,
memory_mask: Optional[Tensor] = None,
memory_key_padding_mask: Optional[Tensor] = None,
pos: Optional[Tensor] = None,
query_pos: Optional[Tensor] = None):
tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt, query_pos),
key=self.with_pos_embed(memory, pos),
value=memory, attn_mask=memory_mask,
key_padding_mask=memory_key_padding_mask)[0]
tgt = tgt + self.dropout(tgt2)
tgt = self.norm(tgt)
return tgt
def forward_pre(self, tgt, memory,
memory_mask: Optional[Tensor] = None,
memory_key_padding_mask: Optional[Tensor] = None,
pos: Optional[Tensor] = None,
query_pos: Optional[Tensor] = None):
tgt2 = self.norm(tgt)
tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt2, query_pos),
key=self.with_pos_embed(memory, pos),
value=memory, attn_mask=memory_mask,
key_padding_mask=memory_key_padding_mask)[0]
tgt = tgt + self.dropout(tgt2)
return tgt
def forward(self, tgt, memory,
memory_mask: Optional[Tensor] = None,
memory_key_padding_mask: Optional[Tensor] = None,
pos: Optional[Tensor] = None,
query_pos: Optional[Tensor] = None):
if self.normalize_before:
return self.forward_pre(tgt, memory, memory_mask,
memory_key_padding_mask, pos, query_pos)
return self.forward_post(tgt, memory, memory_mask,
memory_key_padding_mask, pos, query_pos)
class FFNLayer(nn.Module):
def __init__(self, d_model, dim_feedforward=2048, dropout=0.0,
activation="relu", normalize_before=False):
super().__init__()
# Implementation of Feedforward model
self.linear1 = nn.Linear(d_model, dim_feedforward)
self.dropout = nn.Dropout(dropout)
self.linear2 = nn.Linear(dim_feedforward, d_model)
self.norm = nn.LayerNorm(d_model)
self.activation = _get_activation_fn(activation)
self.normalize_before = normalize_before
self._reset_parameters()
def _reset_parameters(self):
for p in self.parameters():
if p.dim() > 1:
nn.init.xavier_uniform_(p)
def with_pos_embed(self, tensor, pos: Optional[Tensor]):
return tensor if pos is None else tensor + pos
def forward_post(self, tgt):
tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt))))
tgt = tgt + self.dropout(tgt2)
tgt = self.norm(tgt)
return tgt
def forward_pre(self, tgt):
tgt2 = self.norm(tgt)
tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2))))
tgt = tgt + self.dropout(tgt2)
return tgt
def forward(self, tgt):
if self.normalize_before:
return self.forward_pre(tgt)
return self.forward_post(tgt)
def _get_activation_fn(activation):
"""Return an activation function given a string"""
if activation == "relu":
return F.relu
if activation == "gelu":
return F.gelu
if activation == "glu":
return F.glu
raise RuntimeError(F"activation should be relu/gelu, not {activation}.")
class MLP(nn.Module):
""" Very simple multi-layer perceptron (also called FFN)"""
def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
super().__init__()
self.num_layers = num_layers
h = [hidden_dim] * (num_layers - 1)
self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
def forward(self, x):
for i, layer in enumerate(self.layers):
x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
return x
| # Copyright (c) Facebook, Inc. and its affiliates.
# Modified by Bowen Cheng from: https://github.com/facebookresearch/detr/blob/master/models/detr.py
class SelfAttentionLayer(nn.Module):
def __init__(self, d_model, nhead, dropout=0.0,
activation="relu", normalize_before=False):
super().__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
self.norm = nn.LayerNorm(d_model)
self.dropout = nn.Dropout(dropout)
self.activation = _get_activation_fn(activation)
self.normalize_before = normalize_before
self._reset_parameters()
def _reset_parameters(self):
for p in self.parameters():
if p.dim() > 1:
nn.init.xavier_uniform_(p)
def with_pos_embed(self, tensor, pos: Optional[Tensor]):
return tensor if pos is None else tensor + pos
def forward_post(self, tgt,
tgt_mask: Optional[Tensor] = None,
tgt_key_padding_mask: Optional[Tensor] = None,
query_pos: Optional[Tensor] = None):
q = k = self.with_pos_embed(tgt, query_pos)
tgt2 = self.self_attn(q, k, value=tgt, attn_mask=tgt_mask,
key_padding_mask=tgt_key_padding_mask)[0]
tgt = tgt + self.dropout(tgt2)
tgt = self.norm(tgt)
return tgt
def forward_pre(self, tgt,
tgt_mask: Optional[Tensor] = None,
tgt_key_padding_mask: Optional[Tensor] = None,
query_pos: Optional[Tensor] = None):
tgt2 = self.norm(tgt)
q = k = self.with_pos_embed(tgt2, query_pos)
tgt2 = self.self_attn(q, k, value=tgt2, attn_mask=tgt_mask,
key_padding_mask=tgt_key_padding_mask)[0]
tgt = tgt + self.dropout(tgt2)
return tgt
def forward(self, tgt,
tgt_mask: Optional[Tensor] = None,
tgt_key_padding_mask: Optional[Tensor] = None,
query_pos: Optional[Tensor] = None):
if self.normalize_before:
return self.forward_pre(tgt, tgt_mask,
tgt_key_padding_mask, query_pos)
return self.forward_post(tgt, tgt_mask,
tgt_key_padding_mask, query_pos)
class CrossAttentionLayer(nn.Module):
def __init__(self, d_model, nhead, dropout=0.0,
activation="relu", normalize_before=False):
super().__init__()
self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
self.norm = nn.LayerNorm(d_model)
self.dropout = nn.Dropout(dropout)
self.activation = _get_activation_fn(activation)
self.normalize_before = normalize_before
self._reset_parameters()
def _reset_parameters(self):
for p in self.parameters():
if p.dim() > 1:
nn.init.xavier_uniform_(p)
def with_pos_embed(self, tensor, pos: Optional[Tensor]):
return tensor if pos is None else tensor + pos
def forward_post(self, tgt, memory,
memory_mask: Optional[Tensor] = None,
memory_key_padding_mask: Optional[Tensor] = None,
pos: Optional[Tensor] = None,
query_pos: Optional[Tensor] = None):
tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt, query_pos),
key=self.with_pos_embed(memory, pos),
value=memory, attn_mask=memory_mask,
key_padding_mask=memory_key_padding_mask)[0]
tgt = tgt + self.dropout(tgt2)
tgt = self.norm(tgt)
return tgt
def forward_pre(self, tgt, memory,
memory_mask: Optional[Tensor] = None,
memory_key_padding_mask: Optional[Tensor] = None,
pos: Optional[Tensor] = None,
query_pos: Optional[Tensor] = None):
tgt2 = self.norm(tgt)
tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt2, query_pos),
key=self.with_pos_embed(memory, pos),
value=memory, attn_mask=memory_mask,
key_padding_mask=memory_key_padding_mask)[0]
tgt = tgt + self.dropout(tgt2)
return tgt
def forward(self, tgt, memory,
memory_mask: Optional[Tensor] = None,
memory_key_padding_mask: Optional[Tensor] = None,
pos: Optional[Tensor] = None,
query_pos: Optional[Tensor] = None):
if self.normalize_before:
return self.forward_pre(tgt, memory, memory_mask,
memory_key_padding_mask, pos, query_pos)
return self.forward_post(tgt, memory, memory_mask,
memory_key_padding_mask, pos, query_pos)
class FFNLayer(nn.Module):
def __init__(self, d_model, dim_feedforward=2048, dropout=0.0,
activation="relu", normalize_before=False):
super().__init__()
# Implementation of Feedforward model
self.linear1 = nn.Linear(d_model, dim_feedforward)
self.dropout = nn.Dropout(dropout)
self.linear2 = nn.Linear(dim_feedforward, d_model)
self.norm = nn.LayerNorm(d_model)
self.activation = _get_activation_fn(activation)
self.normalize_before = normalize_before
self._reset_parameters()
def _reset_parameters(self):
for p in self.parameters():
if p.dim() > 1:
nn.init.xavier_uniform_(p)
def with_pos_embed(self, tensor, pos: Optional[Tensor]):
return tensor if pos is None else tensor + pos
def forward_post(self, tgt):
tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt))))
tgt = tgt + self.dropout(tgt2)
tgt = self.norm(tgt)
return tgt
def forward_pre(self, tgt):
tgt2 = self.norm(tgt)
tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2))))
tgt = tgt + self.dropout(tgt2)
return tgt
def forward(self, tgt):
if self.normalize_before:
return self.forward_pre(tgt)
return self.forward_post(tgt)
def _get_activation_fn(activation):
"""Return an activation function given a string"""
if activation == "relu":
return F.relu
if activation == "gelu":
return F.gelu
if activation == "glu":
return F.glu
raise RuntimeError(F"activation should be relu/gelu, not {activation}.")
class MLP(nn.Module):
""" Very simple multi-layer perceptron (also called FFN)"""
def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
super().__init__()
self.num_layers = num_layers
h = [hidden_dim] * (num_layers - 1)
self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
def forward(self, x):
for i, layer in enumerate(self.layers):
x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
return x
| @TRANSFORMER_DECODER_REGISTRY.register() | 0 | 2023-11-14 10:55:11+00:00 | 4k |
teamreboott/data-modori | data_modori/config/config.py | [
{
"identifier": "OPERATORS",
"path": "data_modori/ops/base_op.py",
"snippet": "OPERATORS = Registry('Operators')"
},
{
"identifier": "setup_logger",
"path": "data_modori/utils/logger_utils.py",
"snippet": "def setup_logger(save_dir, distributed_rank=0, filename='log.txt', mode='o', redir... | import os
import shutil
import time
import tempfile
import pprint
from argparse import ArgumentError
from typing import Dict, List, Tuple, Union
from jsonargparse import (ActionConfigFile, ArgumentParser, dict_to_namespace,
namespace_to_dict)
from jsonargparse.typing import NonNegativeInt, PositiveInt
from loguru import logger
from data_modori.ops.base_op import OPERATORS
from data_modori.utils.logger_utils import setup_logger
from datasets import disable_caching
from datasets import config
from tabulate import tabulate | 2,843 | help='Number of samples extracted by tracer to show the dataset '
'difference before and after a op. Only available when '
'open_tracer is true.')
parser.add_argument(
'--op_fusion',
type=bool,
default=False,
help='Whether to fuse operators that share the same intermediate '
'variables automatically. Op fusion might reduce the memory '
'requirements slightly but speed up the whole process.')
parser.add_argument(
'--process',
type=List[Dict],
help='List of several operators with their arguments, these ops will '
'be applied to dataset in order')
parser.add_argument(
'--save_stats_in_one_file',
type=bool,
default=False,
help='Whether to save all stats to only one file. Only used in '
'Analysis.')
parser.add_argument(
'--ray_address',
type=str,
default='auto',
help='The address of the Ray cluster.'
)
# add all parameters of the registered ops class to the parser,
# and these op parameters can be modified through the command line,
ops_sorted_by_types = sort_op_by_types_and_names(OPERATORS.modules.items())
_collect_config_info_from_class_docs(ops_sorted_by_types, parser)
try:
cfg = parser.parse_args(args=args)
option_in_commands = [
''.join(arg.split('--')[1].split('.')[0]) for arg in parser.args
if '--' in arg and 'config' not in arg
]
full_option_in_commands = list(
set([
''.join(arg.split('--')[1].split('=')[0])
for arg in parser.args if '--' in arg and 'config' not in arg
]))
if cfg.process is None:
cfg.process = []
# check and update every op params in `cfg.process`
# e.g.
# `python demo.py --config demo.yaml
# --language_id_score_filter.lang en`
for i, op_in_process in enumerate(cfg.process):
op_in_process_name = list(op_in_process.keys())[0]
temp_cfg = cfg
if op_in_process_name not in option_in_commands:
# update op params to temp cfg if set
if op_in_process[op_in_process_name]:
temp_cfg = parser.merge_config(
dict_to_namespace(op_in_process), cfg)
else:
# args in the command line override the ones in `cfg.process`
for full_option_in_command in full_option_in_commands:
key = full_option_in_command.split('.')[1]
if op_in_process[
op_in_process_name] and key in op_in_process[
op_in_process_name].keys():
op_in_process[op_in_process_name].pop(key)
if op_in_process[op_in_process_name]:
temp_cfg = parser.merge_config(
dict_to_namespace(op_in_process), temp_cfg)
# update op params of cfg.process
internal_op_para = temp_cfg.get(op_in_process_name)
cfg.process[i] = {
op_in_process_name:
None if internal_op_para is None else
namespace_to_dict(internal_op_para)
}
cfg = init_setup_from_cfg(cfg)
# copy the config file into the work directory
config_backup(cfg)
# show the final config tables before the process started
display_config(cfg)
return cfg
except ArgumentError:
logger.error('Config initialization failed')
def init_setup_from_cfg(cfg):
"""
Do some extra setup tasks after parsing config file or command line.
1. create working directory and a log directory
2. update cache directory
3. update checkpoint and `temp_dir` of tempfile
:param cfg: a original cfg
:param cfg: a updated cfg
"""
export_path = cfg.export_path
cfg.work_dir = os.path.dirname(export_path)
log_dir = os.path.join(cfg.work_dir, 'log')
if not os.path.exists(log_dir):
os.makedirs(log_dir, exist_ok=True)
timestamp = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
cfg.timestamp = timestamp
logfile_name = timestamp + '.txt'
|
def init_configs(args=None):
"""
initialize the jsonargparse parser and parse configs from one of:
1. POSIX-style commands line args;
2. config files in yaml (json and jsonnet supersets);
3. environment variables
4. hard-coded defaults
:param args: list of params, e.g., ['--conifg', 'cfg.yaml'], defaut None.
:return: a global cfg object used by the Executor or Analyser
"""
parser = ArgumentParser(default_env=True, default_config_files=None)
parser.add_argument(
'--config',
action=ActionConfigFile,
help='Path to a configuration file.',
required=True)
# basic global paras with extended type hints
# e.g., files can be mode include flags
# "fr": "path to a file that exists and is readable")
# "fc": "path to a file that can be created if it does not exist")
# "dw": "path to a directory that exists and is writeable")
# "dc": "path to a directory that can be created if it does not exist")
# "drw": "path to a directory that exists and is readable and writeable")
parser.add_argument(
'--project_name',
type=str,
default='hello_world',
help='Name of your data process project.')
parser.add_argument(
'--executor_type',
type=str,
default='default',
choices=['default', 'ray'],
help='Type of executor, support "default" or "ray" for now.'
)
parser.add_argument(
'--dataset_path',
type=str,
help='Path to datasets with optional weights(0.0-1.0), 1.0 as '
'default. Accepted format:<w1> dataset1-path <w2> dataset2-path '
'<w3> dataset3-path ...')
parser.add_argument(
'--export_path',
type=str,
default='./outputs/hello_world.jsonl',
help='Path to export and save the output processed dataset. The '
'directory to store the processed dataset will be the work '
'directory of this process.')
parser.add_argument(
'--export_shard_size',
type=NonNegativeInt,
default=0,
help='Shard size of exported dataset in Byte. In default, it\'s 0, '
'which means export the whole dataset into only one file. If '
'it\'s set a positive number, the exported dataset will be split '
'into several sub-dataset shards, and the max size of each shard '
'won\'t larger than the export_shard_size')
parser.add_argument(
'--export_in_parallel',
type=bool,
default=False,
help='Whether to export the result dataset in parallel to a single '
'file, which usually takes less time. It only works when '
'export_shard_size is 0, and its default number of processes is '
'the same as the argument np. **Notice**: If it\'s True, '
'sometimes exporting in parallel might require much more time '
'due to the IO blocking, especially for very large datasets. '
'When this happens, False is a better choice, although it takes '
'more time.')
parser.add_argument(
'--np',
type=PositiveInt,
default=4,
help='Number of processes to process dataset.')
parser.add_argument(
'--text_keys',
type=Union[str, List[str]],
default='text',
help='Key name of field where the sample texts to be processed, e.g., '
'`text`, `text.instruction`, `text.output`, ... Note: currently, '
'we support specify only ONE key for each op, for cases '
'requiring multiple keys, users can specify the op multiple '
'times. We will only use the first key of `text_keys` when you '
'set multiple keys.')
parser.add_argument(
'--suffixes',
type=Union[str, List[str], Tuple[str]],
default=[],
help='Suffixes of files that will be find and loaded. If not set, we '
'will find all suffix files, and select a suitable formatter '
'with the most files as default.')
parser.add_argument(
'--use_cache',
type=bool,
default=True,
help='Whether to use the cache management of huggingface datasets. It '
'might take up lots of disk space when using cache')
parser.add_argument(
'--ds_cache_dir',
type=str,
default=None,
help='Cache dir for HuggingFace datasets. In default it\'s the same '
'as the environment variable `HF_DATASETS_CACHE`, whose default '
'value is usually "~/.cache/huggingface/datasets". If this '
'argument is set to a valid path by users, it will override the '
'default cache dir.')
parser.add_argument(
'--cache_compress',
type=str,
default=None,
help='The compression method of the cache file, which can be'
'specified in ["gzip", "zstd", "lz4"]. If this parameter is'
'None, the cache file will not be compressed.')
parser.add_argument(
'--use_checkpoint',
type=bool,
default=False,
help='Whether to use the checkpoint management to save the latest '
'version of dataset to work dir when processing. Rerun the same '
'config will reload the checkpoint and skip ops before it. Cache '
'will be disabled when it is true . If args of ops before the '
'checkpoint are changed, all ops will be rerun from the '
'beginning.')
parser.add_argument(
'--temp_dir',
type=str,
default=None,
help='Path to the temp directory to store intermediate caches when '
'cache is disabled. In default it\'s None, so the temp dir will '
'be specified by system. NOTICE: you should be caution when '
'setting this argument because it might cause unexpected program '
'behaviors when this path is set to an unsafe directory.')
parser.add_argument(
'--open_tracer',
type=bool,
default=False,
help='Whether to open the tracer to trace samples changed during '
'process. It might take more time when opening tracer.')
parser.add_argument(
'--op_list_to_trace',
type=List[str],
default=[],
help='Which ops will be traced by tracer. If it\'s empty, all ops in '
'cfg.process will be traced. Only available when open_tracer is '
'true.')
parser.add_argument(
'--trace_num',
type=int,
default=10,
help='Number of samples extracted by tracer to show the dataset '
'difference before and after a op. Only available when '
'open_tracer is true.')
parser.add_argument(
'--op_fusion',
type=bool,
default=False,
help='Whether to fuse operators that share the same intermediate '
'variables automatically. Op fusion might reduce the memory '
'requirements slightly but speed up the whole process.')
parser.add_argument(
'--process',
type=List[Dict],
help='List of several operators with their arguments, these ops will '
'be applied to dataset in order')
parser.add_argument(
'--save_stats_in_one_file',
type=bool,
default=False,
help='Whether to save all stats to only one file. Only used in '
'Analysis.')
parser.add_argument(
'--ray_address',
type=str,
default='auto',
help='The address of the Ray cluster.'
)
# add all parameters of the registered ops class to the parser,
# and these op parameters can be modified through the command line,
ops_sorted_by_types = sort_op_by_types_and_names(OPERATORS.modules.items())
_collect_config_info_from_class_docs(ops_sorted_by_types, parser)
try:
cfg = parser.parse_args(args=args)
option_in_commands = [
''.join(arg.split('--')[1].split('.')[0]) for arg in parser.args
if '--' in arg and 'config' not in arg
]
full_option_in_commands = list(
set([
''.join(arg.split('--')[1].split('=')[0])
for arg in parser.args if '--' in arg and 'config' not in arg
]))
if cfg.process is None:
cfg.process = []
# check and update every op params in `cfg.process`
# e.g.
# `python demo.py --config demo.yaml
# --language_id_score_filter.lang en`
for i, op_in_process in enumerate(cfg.process):
op_in_process_name = list(op_in_process.keys())[0]
temp_cfg = cfg
if op_in_process_name not in option_in_commands:
# update op params to temp cfg if set
if op_in_process[op_in_process_name]:
temp_cfg = parser.merge_config(
dict_to_namespace(op_in_process), cfg)
else:
# args in the command line override the ones in `cfg.process`
for full_option_in_command in full_option_in_commands:
key = full_option_in_command.split('.')[1]
if op_in_process[
op_in_process_name] and key in op_in_process[
op_in_process_name].keys():
op_in_process[op_in_process_name].pop(key)
if op_in_process[op_in_process_name]:
temp_cfg = parser.merge_config(
dict_to_namespace(op_in_process), temp_cfg)
# update op params of cfg.process
internal_op_para = temp_cfg.get(op_in_process_name)
cfg.process[i] = {
op_in_process_name:
None if internal_op_para is None else
namespace_to_dict(internal_op_para)
}
cfg = init_setup_from_cfg(cfg)
# copy the config file into the work directory
config_backup(cfg)
# show the final config tables before the process started
display_config(cfg)
return cfg
except ArgumentError:
logger.error('Config initialization failed')
def init_setup_from_cfg(cfg):
"""
Do some extra setup tasks after parsing config file or command line.
1. create working directory and a log directory
2. update cache directory
3. update checkpoint and `temp_dir` of tempfile
:param cfg: a original cfg
:param cfg: a updated cfg
"""
export_path = cfg.export_path
cfg.work_dir = os.path.dirname(export_path)
log_dir = os.path.join(cfg.work_dir, 'log')
if not os.path.exists(log_dir):
os.makedirs(log_dir, exist_ok=True)
timestamp = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
cfg.timestamp = timestamp
logfile_name = timestamp + '.txt' | setup_logger(save_dir=log_dir, filename=logfile_name, redirect=cfg.executor_type=='default') | 1 | 2023-11-13 04:52:55+00:00 | 4k |
52phm/pylmkit | pylmkit/core/base.py | [
{
"identifier": "read_yaml",
"path": "pylmkit/utils/data_utils.py",
"snippet": "def read_yaml(filepath):\n try:\n with open(filepath, encoding=\"utf-8\") as fp:\n result = yaml.load(fp, Loader=SafeLoader)\n except Exception as e:\n raise Exception(e)\n return result"
... | from abc import ABC
from pathlib import Path
from tqdm import tqdm
from pydantic import Field, BaseModel
from pylmkit.utils.data_utils import read_yaml, read_json, write_yaml, write_json
from pylmkit.utils.data_utils import message_as_string, document_as_dict, dict_as_document
from typing import Any, List, Optional, Type, Union, Sequence, Literal
from pylmkit.perception.directory import BaseLoader
from pylmkit.utils.data_utils import text_as_document
from pylmkit.perception.directory import RecursiveCharacterTextSplitter
from functools import partial
from pylmkit.core.html import init_css, init_footer, init_logo
from pylmkit.core.html import _zh, _en
import time
import pandas as pd
import streamlit as st | 2,276 |
class BaseMemory(object):
human_prefix: str = "Human"
ai_prefix: str = "AI"
system_prefix: str = "System"
def __init__(self, init_memory=None, streamlit_web=False):
self.memory_messages = []
self.streamlit_web = streamlit_web
if self.streamlit_web: # streamlit rerun page, so need cache
if "memory" not in st.session_state:
st.session_state["memory"] = self.memory_messages
if isinstance(init_memory, list):
self.memory_messages = init_memory
if self.streamlit_web:
st.session_state['memory'] = self.memory_messages
if self.streamlit_web: # streamlit rerun page, so need cache
self.memory_messages = st.session_state['memory']
def add(self, role, content, refer=''):
""" role,human ai system
"""
if role in ['user', 'User', 'USER', 'human', 'Human', 'HUMAN']:
role = self.human_prefix
elif role in ['ai', 'Ai', 'AI', 'assistant']:
role = self.ai_prefix
elif role in ['sys', 'system', 'System', 'SYS', 'SYSTEM']:
role = self.system_prefix
else:
raise Exception(f"The role `{role}` does not exist")
self.memory_messages.append(
{"role": role, "content": content, "refer": refer, "date": time.strftime('%Y-%m-%d %H:%M:%S')})
if self.streamlit_web: # streamlit rerun page, so need cache
st.session_state['memory'] = self.memory_messages
def to_csv(self, filepath, index=False, **kwargs):
data = self.memory_messages
pd.DataFrame(data).to_csv(filepath, index=index, **kwargs)
def clear(self):
self.memory_messages = []
if self.streamlit_web: # streamlit rerun page, so need cache
st.session_state['memory'] = self.memory_messages
def _get(self, mode='message'):
if mode == 'message':
return self.memory_messages
elif mode == 'string':
return message_as_string(self.memory_messages)
else:
raise Exception(f"There is no such `{mode}` mode. Support modes: message, string")
class BaseKnowledgeBase(object):
def __init__(self, init_documents=None):
self.documents = []
self.splitter_documents = []
if isinstance(init_documents, list):
self.documents = init_documents
@classmethod
def load(cls, filepath, is_return=True, return_mode="doc", extend=True):
if filepath.endswith('.json'):
data = read_json(filepath)
elif filepath.endswith('.yaml') or filepath.endswith('yml'):
data = read_yaml(filepath) # data=[{},{}]
else:
raise Exception(f"The file type is not supported")
data_dict_as_document = dict_as_document(data)
result = cls()._base(documents=data_dict_as_document, return_mode=return_mode, is_return=is_return,
extend=extend)
if is_return:
return result
@classmethod
def add(cls, texts, metadatas=None, is_return=True, return_mode="doc", extend=True, types="Document"):
data_dict_as_document = text_as_document(texts=texts, metadatas=metadatas, types=types)
result = cls()._base(documents=data_dict_as_document, return_mode=return_mode, is_return=is_return,
extend=extend)
if is_return:
return result
def split(self, splitter=None, chunk_size=500, chunk_overlap=100, return_mode='doc', **kwargs):
if splitter is None:
splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap, **kwargs)
else:
splitter = splitter
self.splitter_documents = splitter.split_documents(self.documents)
if return_mode == 'doc':
return self.splitter_documents
else:
|
class BaseMemory(object):
human_prefix: str = "Human"
ai_prefix: str = "AI"
system_prefix: str = "System"
def __init__(self, init_memory=None, streamlit_web=False):
self.memory_messages = []
self.streamlit_web = streamlit_web
if self.streamlit_web: # streamlit rerun page, so need cache
if "memory" not in st.session_state:
st.session_state["memory"] = self.memory_messages
if isinstance(init_memory, list):
self.memory_messages = init_memory
if self.streamlit_web:
st.session_state['memory'] = self.memory_messages
if self.streamlit_web: # streamlit rerun page, so need cache
self.memory_messages = st.session_state['memory']
def add(self, role, content, refer=''):
""" role,human ai system
"""
if role in ['user', 'User', 'USER', 'human', 'Human', 'HUMAN']:
role = self.human_prefix
elif role in ['ai', 'Ai', 'AI', 'assistant']:
role = self.ai_prefix
elif role in ['sys', 'system', 'System', 'SYS', 'SYSTEM']:
role = self.system_prefix
else:
raise Exception(f"The role `{role}` does not exist")
self.memory_messages.append(
{"role": role, "content": content, "refer": refer, "date": time.strftime('%Y-%m-%d %H:%M:%S')})
if self.streamlit_web: # streamlit rerun page, so need cache
st.session_state['memory'] = self.memory_messages
def to_csv(self, filepath, index=False, **kwargs):
data = self.memory_messages
pd.DataFrame(data).to_csv(filepath, index=index, **kwargs)
def clear(self):
self.memory_messages = []
if self.streamlit_web: # streamlit rerun page, so need cache
st.session_state['memory'] = self.memory_messages
def _get(self, mode='message'):
if mode == 'message':
return self.memory_messages
elif mode == 'string':
return message_as_string(self.memory_messages)
else:
raise Exception(f"There is no such `{mode}` mode. Support modes: message, string")
class BaseKnowledgeBase(object):
def __init__(self, init_documents=None):
self.documents = []
self.splitter_documents = []
if isinstance(init_documents, list):
self.documents = init_documents
@classmethod
def load(cls, filepath, is_return=True, return_mode="doc", extend=True):
if filepath.endswith('.json'):
data = read_json(filepath)
elif filepath.endswith('.yaml') or filepath.endswith('yml'):
data = read_yaml(filepath) # data=[{},{}]
else:
raise Exception(f"The file type is not supported")
data_dict_as_document = dict_as_document(data)
result = cls()._base(documents=data_dict_as_document, return_mode=return_mode, is_return=is_return,
extend=extend)
if is_return:
return result
@classmethod
def add(cls, texts, metadatas=None, is_return=True, return_mode="doc", extend=True, types="Document"):
data_dict_as_document = text_as_document(texts=texts, metadatas=metadatas, types=types)
result = cls()._base(documents=data_dict_as_document, return_mode=return_mode, is_return=is_return,
extend=extend)
if is_return:
return result
def split(self, splitter=None, chunk_size=500, chunk_overlap=100, return_mode='doc', **kwargs):
if splitter is None:
splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap, **kwargs)
else:
splitter = splitter
self.splitter_documents = splitter.split_documents(self.documents)
if return_mode == 'doc':
return self.splitter_documents
else: | return document_as_dict(self.splitter_documents) | 5 | 2023-11-18 10:31:58+00:00 | 4k |
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,604 |
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):
print(f"{idx}: {action}")
# Create a mapping from WindowEvent to action index
window_event_to_action = {
'PRESS_ARROW_DOWN': 0,
'PRESS_ARROW_LEFT': 1,
'PRESS_ARROW_RIGHT': 2,
'PRESS_ARROW_UP': 3,
'PRESS_BUTTON_A': 4,
'PRESS_BUTTON_B': 5,
'PRESS_BUTTON_START': 6,
'PRESS_BUTTON_SELECT': 7,
# Add more mappings if necessary
}
while True:
# Get input from pyboy's get_input method
input_events = env.game.get_input()
env.game.tick()
env.render()
if len(input_events) == 0:
continue
for event in input_events:
event_str = str(event)
if event_str in window_event_to_action:
action_index = window_event_to_action[event_str]
observation, reward, done, _, info = env.step(
action_index, fast_video=False)
# Check for game over
if done:
print(f"{done}")
break
# Additional game logic or information display can go here
print(f"new Reward: {reward}\n")
class Base:
def __init__(self, rom_path='pokemon_red.gb',
state_path=None, headless=True, quiet=False, **kwargs):
'''Creates a PokemonRed environment'''
if state_path is None:
state_path = __file__.rstrip('environment.py') + 'has_pokedex_nballs.state'
|
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):
print(f"{idx}: {action}")
# Create a mapping from WindowEvent to action index
window_event_to_action = {
'PRESS_ARROW_DOWN': 0,
'PRESS_ARROW_LEFT': 1,
'PRESS_ARROW_RIGHT': 2,
'PRESS_ARROW_UP': 3,
'PRESS_BUTTON_A': 4,
'PRESS_BUTTON_B': 5,
'PRESS_BUTTON_START': 6,
'PRESS_BUTTON_SELECT': 7,
# Add more mappings if necessary
}
while True:
# Get input from pyboy's get_input method
input_events = env.game.get_input()
env.game.tick()
env.render()
if len(input_events) == 0:
continue
for event in input_events:
event_str = str(event)
if event_str in window_event_to_action:
action_index = window_event_to_action[event_str]
observation, reward, done, _, info = env.step(
action_index, fast_video=False)
# Check for game over
if done:
print(f"{done}")
break
# Additional game logic or information display can go here
print(f"new Reward: {reward}\n")
class Base:
def __init__(self, rom_path='pokemon_red.gb',
state_path=None, headless=True, quiet=False, **kwargs):
'''Creates a PokemonRed environment'''
if state_path is None:
state_path = __file__.rstrip('environment.py') + 'has_pokedex_nballs.state'
| self.game, self.screen = make_env( | 1 | 2023-11-16 18:34:28+00:00 | 4k |
AlexandrErohin/home-assistant-flightradar24 | custom_components/flightradar24/sensor.py | [
{
"identifier": "DOMAIN",
"path": "custom_components/flightradar24/const.py",
"snippet": "DOMAIN = \"flightradar24\""
},
{
"identifier": "FlightRadar24Coordinator",
"path": "custom_components/flightradar24/coordinator.py",
"snippet": "class FlightRadar24Coordinator(DataUpdateCoordinator[... | from dataclasses import dataclass
from collections.abc import Callable
from typing import Any
from homeassistant.components.sensor import (
SensorStateClass,
SensorEntity,
SensorEntityDescription,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.device_registry import DeviceInfo
from .const import DOMAIN
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .coordinator import FlightRadar24Coordinator | 2,721 |
@dataclass
class FlightRadar24SensorRequiredKeysMixin:
value: Callable[[FlightRadar24Coordinator], Any]
attributes: Callable[[FlightRadar24Coordinator], Any]
@dataclass
class TFlightRadar24SensorEntityDescription(SensorEntityDescription, FlightRadar24SensorRequiredKeysMixin):
"""A class that describes sensor entities."""
SENSOR_TYPES: tuple[TFlightRadar24SensorEntityDescription, ...] = (
TFlightRadar24SensorEntityDescription(
key="in_area",
name="Current in area",
icon="mdi:airplane",
state_class=SensorStateClass.TOTAL,
value=lambda coord: len(coord.tracked) if coord.tracked is not None else 0,
attributes=lambda coord: {'flights': [coord.tracked[x] for x in coord.tracked]},
),
TFlightRadar24SensorEntityDescription(
key="entered",
name="Entered area",
icon="mdi:airplane",
state_class=SensorStateClass.TOTAL,
value=lambda coord: len(coord.entered),
attributes=lambda coord: {'flights': coord.entered},
),
TFlightRadar24SensorEntityDescription(
key="exited",
name="Exited area",
icon="mdi:airplane",
state_class=SensorStateClass.TOTAL,
value=lambda coord: len(coord.exited),
attributes=lambda coord: {'flights': coord.exited},
),
)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
|
@dataclass
class FlightRadar24SensorRequiredKeysMixin:
value: Callable[[FlightRadar24Coordinator], Any]
attributes: Callable[[FlightRadar24Coordinator], Any]
@dataclass
class TFlightRadar24SensorEntityDescription(SensorEntityDescription, FlightRadar24SensorRequiredKeysMixin):
"""A class that describes sensor entities."""
SENSOR_TYPES: tuple[TFlightRadar24SensorEntityDescription, ...] = (
TFlightRadar24SensorEntityDescription(
key="in_area",
name="Current in area",
icon="mdi:airplane",
state_class=SensorStateClass.TOTAL,
value=lambda coord: len(coord.tracked) if coord.tracked is not None else 0,
attributes=lambda coord: {'flights': [coord.tracked[x] for x in coord.tracked]},
),
TFlightRadar24SensorEntityDescription(
key="entered",
name="Entered area",
icon="mdi:airplane",
state_class=SensorStateClass.TOTAL,
value=lambda coord: len(coord.entered),
attributes=lambda coord: {'flights': coord.entered},
),
TFlightRadar24SensorEntityDescription(
key="exited",
name="Exited area",
icon="mdi:airplane",
state_class=SensorStateClass.TOTAL,
value=lambda coord: len(coord.exited),
attributes=lambda coord: {'flights': coord.exited},
),
)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None: | coordinator = hass.data[DOMAIN][entry.entry_id] | 0 | 2023-11-16 10:51:24+00:00 | 4k |
ej0cl6/TextEE | TextEE/models/EEQA/EDtrainer.py | [
{
"identifier": "BasicTrainer",
"path": "TextEE/models/trainer.py",
"snippet": "class BasicTrainer(object):\n def __init__(self, config, type_set=None):\n self.config = config\n self.type_set = type_set\n \n @classmethod\n def add_extra_info_fn(cls, instances, raw_data, con... | import os, sys, logging, tqdm, pprint
import torch
import numpy as np
import ipdb
from collections import namedtuple
from transformers import RobertaTokenizer, AutoTokenizer, get_linear_schedule_with_warmup
from torch.utils.data import DataLoader
from torch.optim import AdamW
from ..trainer import BasicTrainer
from .EDmodel import EEQAEDModel
from scorer import compute_ED_scores, print_scores | 3,002 |
logger = logging.getLogger(__name__)
EDBatch_fields = ['batch_doc_id', 'batch_wnd_id', 'batch_tokens', 'batch_pieces', 'batch_token_lens', 'batch_token_num', 'batch_text', 'batch_triggers']
EDBatch = namedtuple('EDBatch', field_names=EDBatch_fields, defaults=[None] * len(EDBatch_fields))
def ED_collate_fn(batch):
return EDBatch(
batch_doc_id=[instance["doc_id"] for instance in batch],
batch_wnd_id=[instance["wnd_id"] for instance in batch],
batch_tokens=[instance["tokens"] for instance in batch],
batch_pieces=[instance["pieces"] for instance in batch],
batch_token_lens=[instance["token_lens"] for instance in batch],
batch_token_num=[instance["token_num"] for instance in batch],
batch_text=[instance["text"] for instance in batch],
batch_triggers=[instance["triggers"] for instance in batch],
)
|
logger = logging.getLogger(__name__)
EDBatch_fields = ['batch_doc_id', 'batch_wnd_id', 'batch_tokens', 'batch_pieces', 'batch_token_lens', 'batch_token_num', 'batch_text', 'batch_triggers']
EDBatch = namedtuple('EDBatch', field_names=EDBatch_fields, defaults=[None] * len(EDBatch_fields))
def ED_collate_fn(batch):
return EDBatch(
batch_doc_id=[instance["doc_id"] for instance in batch],
batch_wnd_id=[instance["wnd_id"] for instance in batch],
batch_tokens=[instance["tokens"] for instance in batch],
batch_pieces=[instance["pieces"] for instance in batch],
batch_token_lens=[instance["token_lens"] for instance in batch],
batch_token_num=[instance["token_num"] for instance in batch],
batch_text=[instance["text"] for instance in batch],
batch_triggers=[instance["triggers"] for instance in batch],
)
| class EEQAEDTrainer(BasicTrainer): | 0 | 2023-11-15 21:32:56+00:00 | 4k |
isce-framework/snaphu-py | src/snaphu/_unwrap.py | [
{
"identifier": "run_snaphu",
"path": "src/snaphu/_snaphu.py",
"snippet": "def run_snaphu(config_file: str | os.PathLike[str]) -> None:\n \"\"\"\n Run SNAPHU with the specified config file.\n\n Parameters\n ----------\n config_file : path-like\n The file path of a text file storing... | import io
import os
import textwrap
import numpy as np
from dataclasses import dataclass
from pathlib import Path
from tempfile import mkstemp
from typing import cast, overload
from ._snaphu import run_snaphu
from ._util import BlockIterator, scratch_directory
from .io import InputDataset, OutputDataset | 3,261 | class SnaphuConfig:
"""
SNAPHU configuration parameters.
Parameters
----------
infile : path-like
The input interferogram file path.
corrfile : path-like
The input coherence file path.
outfile : path-like
The output unwrapped phase file path.
conncompfile : path-like
The output connected component labels file path.
linelength : int
The line length, in samples, of the input interferogram data array.
ncorrlooks : float
The equivalent number of independent looks used to form the coherence data.
statcostmode : str
The statistical cost mode.
initmethod : str
The algorithm used for initializing the network solver routine.
bytemaskfile : path-like or None, optional
An optional file path of a byte mask file. If None, no mask is applied. Defaults
to None.
tiling_params : TilingParams or None, optional
Optional additional configuration parameters affecting scene tiling and parallel
processing. Defaults to None.
"""
infile: str | os.PathLike[str]
corrfile: str | os.PathLike[str]
outfile: str | os.PathLike[str]
conncompfile: str | os.PathLike[str]
linelength: int
ncorrlooks: float
statcostmode: str
initmethod: str
bytemaskfile: str | os.PathLike[str] | None = None
tiling_params: TilingParams | None = None
def to_string(self) -> str:
"""
Write SNAPHU configuration parameters to a string.
Creates a multi-line string in SNAPHU configuration file format.
Returns
-------
str
The output string.
"""
config = textwrap.dedent(f"""\
INFILE {os.fspath(self.infile)}
INFILEFORMAT COMPLEX_DATA
CORRFILE {os.fspath(self.corrfile)}
CORRFILEFORMAT FLOAT_DATA
OUTFILE {os.fspath(self.outfile)}
OUTFILEFORMAT FLOAT_DATA
CONNCOMPFILE {os.fspath(self.conncompfile)}
CONNCOMPOUTTYPE UINT
LINELENGTH {self.linelength}
NCORRLOOKS {self.ncorrlooks}
STATCOSTMODE {self.statcostmode.upper()}
INITMETHOD {self.initmethod.upper()}
""")
if self.bytemaskfile is not None:
config += f"BYTEMASKFILE {os.fspath(self.bytemaskfile)}\n"
if self.tiling_params is not None:
config += self.tiling_params.to_string()
return config
def _to_file_textio(self, file_: io.TextIOBase, /) -> None:
# Write config params to file.
s = self.to_string()
count = file_.write(s)
# Check that the full text was successfully written to the file.
if count != len(s):
errmsg = "failed to write config params to file"
raise RuntimeError(errmsg)
def _to_file_pathlike(self, file_: str | os.PathLike[str], /) -> None:
# Create the file's parent directory(ies) if they didn't already exist.
p = Path(file_)
p.parent.mkdir(parents=True, exist_ok=True)
# Write config params to file.
s = self.to_string()
p.write_text(s)
def to_file(self, file_: str | os.PathLike[str] | io.TextIOBase, /) -> None:
"""
Write SNAPHU configuration parameters to a file.
The resulting file is suitable for passing to the SNAPHU executable as a
configuration file.
Parameters
----------
file_ : path-like or file-like
The output file. May be an open text file or a file path. If the file
and any of its parent directories do not exist, they will be created. If the
path to an existing file is specified, the file will be overwritten.
"""
if isinstance(file_, io.TextIOBase):
self._to_file_textio(file_)
elif isinstance(file_, (str, os.PathLike)):
self._to_file_pathlike(file_)
else:
errmsg = (
"to_file argument must be a path-like or file-like object, instead got"
f" type={type(file_)}"
)
raise TypeError(errmsg)
def check_shapes(
| from __future__ import annotations
__all__ = [
"unwrap",
]
@dataclass(frozen=True)
class TilingParams:
"""
SNAPHU configuration parameters affecting scene tiling and parallel processing.
Parameters
----------
ntilerow, ntilecol : int, optional
Number of tiles along the row/column directions. If `ntilerow` and `ntilecol`
are both 1 (the default), the interferogram will be unwrapped as a single tile.
rowovrlp, colovrlp : int, optional
Overlap, in number of rows/columns, between neighboring tiles. Defaults to 0.
nproc : int, optional
Maximum number of child processes to spawn for parallel tile unwrapping.
Defaults to 1.
"""
ntilerow: int = 1
ntilecol: int = 1
rowovrlp: int = 0
colovrlp: int = 0
nproc: int = 1
def to_string(self) -> str:
"""
Write SNAPHU tiling parameters to a string.
Creates a multi-line string in SNAPHU configuration file format.
Returns
-------
str
The output string.
"""
return textwrap.dedent(f"""\
NTILEROW {self.ntilerow}
NTILECOL {self.ntilecol}
ROWOVRLP {self.rowovrlp}
COLOVRLP {self.colovrlp}
NPROC {self.nproc}
""")
@dataclass(frozen=True)
class SnaphuConfig:
"""
SNAPHU configuration parameters.
Parameters
----------
infile : path-like
The input interferogram file path.
corrfile : path-like
The input coherence file path.
outfile : path-like
The output unwrapped phase file path.
conncompfile : path-like
The output connected component labels file path.
linelength : int
The line length, in samples, of the input interferogram data array.
ncorrlooks : float
The equivalent number of independent looks used to form the coherence data.
statcostmode : str
The statistical cost mode.
initmethod : str
The algorithm used for initializing the network solver routine.
bytemaskfile : path-like or None, optional
An optional file path of a byte mask file. If None, no mask is applied. Defaults
to None.
tiling_params : TilingParams or None, optional
Optional additional configuration parameters affecting scene tiling and parallel
processing. Defaults to None.
"""
infile: str | os.PathLike[str]
corrfile: str | os.PathLike[str]
outfile: str | os.PathLike[str]
conncompfile: str | os.PathLike[str]
linelength: int
ncorrlooks: float
statcostmode: str
initmethod: str
bytemaskfile: str | os.PathLike[str] | None = None
tiling_params: TilingParams | None = None
def to_string(self) -> str:
"""
Write SNAPHU configuration parameters to a string.
Creates a multi-line string in SNAPHU configuration file format.
Returns
-------
str
The output string.
"""
config = textwrap.dedent(f"""\
INFILE {os.fspath(self.infile)}
INFILEFORMAT COMPLEX_DATA
CORRFILE {os.fspath(self.corrfile)}
CORRFILEFORMAT FLOAT_DATA
OUTFILE {os.fspath(self.outfile)}
OUTFILEFORMAT FLOAT_DATA
CONNCOMPFILE {os.fspath(self.conncompfile)}
CONNCOMPOUTTYPE UINT
LINELENGTH {self.linelength}
NCORRLOOKS {self.ncorrlooks}
STATCOSTMODE {self.statcostmode.upper()}
INITMETHOD {self.initmethod.upper()}
""")
if self.bytemaskfile is not None:
config += f"BYTEMASKFILE {os.fspath(self.bytemaskfile)}\n"
if self.tiling_params is not None:
config += self.tiling_params.to_string()
return config
def _to_file_textio(self, file_: io.TextIOBase, /) -> None:
# Write config params to file.
s = self.to_string()
count = file_.write(s)
# Check that the full text was successfully written to the file.
if count != len(s):
errmsg = "failed to write config params to file"
raise RuntimeError(errmsg)
def _to_file_pathlike(self, file_: str | os.PathLike[str], /) -> None:
# Create the file's parent directory(ies) if they didn't already exist.
p = Path(file_)
p.parent.mkdir(parents=True, exist_ok=True)
# Write config params to file.
s = self.to_string()
p.write_text(s)
def to_file(self, file_: str | os.PathLike[str] | io.TextIOBase, /) -> None:
"""
Write SNAPHU configuration parameters to a file.
The resulting file is suitable for passing to the SNAPHU executable as a
configuration file.
Parameters
----------
file_ : path-like or file-like
The output file. May be an open text file or a file path. If the file
and any of its parent directories do not exist, they will be created. If the
path to an existing file is specified, the file will be overwritten.
"""
if isinstance(file_, io.TextIOBase):
self._to_file_textio(file_)
elif isinstance(file_, (str, os.PathLike)):
self._to_file_pathlike(file_)
else:
errmsg = (
"to_file argument must be a path-like or file-like object, instead got"
f" type={type(file_)}"
)
raise TypeError(errmsg)
def check_shapes( | igram: InputDataset, | 3 | 2023-11-16 21:48:58+00:00 | 4k |
fofr/cog-sdxl-multi-controlnet-lora | predict.py | [
{
"identifier": "WeightsDownloader",
"path": "weights_downloader.py",
"snippet": "class WeightsDownloader:\n @staticmethod\n def download_if_not_exists(url, dest):\n if not os.path.exists(dest):\n WeightsDownloader.download(url, dest)\n\n @staticmethod\n def download(url, d... | import os
import time
import numpy as np
import torch
from typing import List, Optional
from cog import BasePredictor, Input, Path
from diffusers import (
DDIMScheduler,
DiffusionPipeline,
DPMSolverMultistepScheduler,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler,
HeunDiscreteScheduler,
PNDMScheduler,
StableDiffusionXLImg2ImgPipeline,
StableDiffusionXLInpaintPipeline,
StableDiffusionXLControlNetPipeline,
StableDiffusionXLControlNetInpaintPipeline,
StableDiffusionXLControlNetImg2ImgPipeline,
)
from diffusers.pipelines.stable_diffusion.safety_checker import (
StableDiffusionSafetyChecker,
)
from transformers import CLIPImageProcessor
from weights_downloader import WeightsDownloader
from weights_manager import WeightsManager
from controlnet import ControlNet
from sizing_strategy import SizingStrategy | 3,039 |
SDXL_MODEL_CACHE = "./sdxl-cache"
REFINER_MODEL_CACHE = "./refiner-cache"
SAFETY_CACHE = "./safety-cache"
FEATURE_EXTRACTOR = "./feature-extractor"
SDXL_URL = "https://weights.replicate.delivery/default/sdxl/sdxl-vae-upcast-fix.tar"
REFINER_URL = (
"https://weights.replicate.delivery/default/sdxl/refiner-no-vae-no-encoder-1.0.tar"
)
SAFETY_URL = "https://weights.replicate.delivery/default/sdxl/safety-1.0.tar"
class KarrasDPM:
def from_config(config):
return DPMSolverMultistepScheduler.from_config(config, use_karras_sigmas=True)
SCHEDULERS = {
"DDIM": DDIMScheduler,
"DPMSolverMultistep": DPMSolverMultistepScheduler,
"HeunDiscrete": HeunDiscreteScheduler,
"KarrasDPM": KarrasDPM,
"K_EULER_ANCESTRAL": EulerAncestralDiscreteScheduler,
"K_EULER": EulerDiscreteScheduler,
"PNDM": PNDMScheduler,
}
class Predictor(BasePredictor):
def load_trained_weights(self, weights, pipe):
self.weights_manager.load_trained_weights(weights, pipe)
def build_controlnet_pipeline(self, pipeline_class, controlnet_models):
pipe = pipeline_class.from_pretrained(
SDXL_MODEL_CACHE,
torch_dtype=torch.float16,
use_safetensors=True,
variant="fp16",
vae=self.txt2img_pipe.vae,
text_encoder=self.txt2img_pipe.text_encoder,
text_encoder_2=self.txt2img_pipe.text_encoder_2,
tokenizer=self.txt2img_pipe.tokenizer,
tokenizer_2=self.txt2img_pipe.tokenizer_2,
unet=self.txt2img_pipe.unet,
scheduler=self.txt2img_pipe.scheduler,
controlnet=self.controlnet.get_models(controlnet_models),
)
pipe.to("cuda")
return pipe
def setup(self, weights: Optional[Path] = None):
"""Load the model into memory to make running multiple predictions efficient"""
start = time.time()
|
SDXL_MODEL_CACHE = "./sdxl-cache"
REFINER_MODEL_CACHE = "./refiner-cache"
SAFETY_CACHE = "./safety-cache"
FEATURE_EXTRACTOR = "./feature-extractor"
SDXL_URL = "https://weights.replicate.delivery/default/sdxl/sdxl-vae-upcast-fix.tar"
REFINER_URL = (
"https://weights.replicate.delivery/default/sdxl/refiner-no-vae-no-encoder-1.0.tar"
)
SAFETY_URL = "https://weights.replicate.delivery/default/sdxl/safety-1.0.tar"
class KarrasDPM:
def from_config(config):
return DPMSolverMultistepScheduler.from_config(config, use_karras_sigmas=True)
SCHEDULERS = {
"DDIM": DDIMScheduler,
"DPMSolverMultistep": DPMSolverMultistepScheduler,
"HeunDiscrete": HeunDiscreteScheduler,
"KarrasDPM": KarrasDPM,
"K_EULER_ANCESTRAL": EulerAncestralDiscreteScheduler,
"K_EULER": EulerDiscreteScheduler,
"PNDM": PNDMScheduler,
}
class Predictor(BasePredictor):
def load_trained_weights(self, weights, pipe):
self.weights_manager.load_trained_weights(weights, pipe)
def build_controlnet_pipeline(self, pipeline_class, controlnet_models):
pipe = pipeline_class.from_pretrained(
SDXL_MODEL_CACHE,
torch_dtype=torch.float16,
use_safetensors=True,
variant="fp16",
vae=self.txt2img_pipe.vae,
text_encoder=self.txt2img_pipe.text_encoder,
text_encoder_2=self.txt2img_pipe.text_encoder_2,
tokenizer=self.txt2img_pipe.tokenizer,
tokenizer_2=self.txt2img_pipe.tokenizer_2,
unet=self.txt2img_pipe.unet,
scheduler=self.txt2img_pipe.scheduler,
controlnet=self.controlnet.get_models(controlnet_models),
)
pipe.to("cuda")
return pipe
def setup(self, weights: Optional[Path] = None):
"""Load the model into memory to make running multiple predictions efficient"""
start = time.time() | self.sizing_strategy = SizingStrategy() | 3 | 2023-11-13 13:04:41+00:00 | 4k |
ahayler/s4c | datasets/kitti_raw/kitti_raw_dataset.py | [
{
"identifier": "apply_crop",
"path": "utils/array_operations.py",
"snippet": "def apply_crop(array, crop):\n return array[crop[0]:crop[0] + crop[2], crop[1]:crop[1] + crop[3]]"
},
{
"identifier": "get_color_aug_fn",
"path": "utils/augmentation.py",
"snippet": "def get_color_aug_fn(pa... | import os
import time
import cv2
import numpy as np
import torch
from collections import Counter
from pathlib import Path
from torch.utils.data import Dataset
from torchvision.transforms import ColorJitter
from utils.array_operations import apply_crop
from utils.augmentation import get_color_aug_fn | 2,545 |
R_rect = np.eye(4, dtype=np.float32)
R_rect[:3, :3] = cam_calib_file_data['R_rect_00'].reshape(3, 3)
T_v2c = np.hstack((velo_calib_file_data['R'].reshape(3, 3), velo_calib_file_data['T'][..., np.newaxis]))
T_v2c = np.vstack((T_v2c, np.array([0, 0, 0, 1.0], dtype=np.float32)))
P_v2cl = P_rect_l @ R_rect @ T_v2c
P_v2cr = P_rect_r @ R_rect @ T_v2c
# Compute the rectified extrinsics from cam0 to camN
T_l = np.eye(4, dtype=np.float32)
T_l[0, 3] = P_rect_l[0, 3] / P_rect_l[0, 0]
T_r = np.eye(4, dtype=np.float32)
T_r[0, 3] = P_rect_r[0, 3] / P_rect_r[0, 0]
K = P_rect_l[:3, :3]
if keep_aspect_ratio:
r_orig = im_size[0] / im_size[1]
r_target = target_image_size[0] / target_image_size[1]
if r_orig >= r_target:
new_height = r_target * im_size[1]
crop_height = im_size[0] - ((im_size[0] - new_height) // 2) * 2
box = ((im_size[0] - new_height) // 2, 0, crop_height, int(im_size[1]))
c_x = K[0, 2] / im_size[1]
c_y = (K[1, 2] - (im_size[0] - new_height) / 2) / new_height
rescale = im_size[1] / target_image_size[1]
else:
new_width = im_size[0] / r_target
crop_width = im_size[1] - ((im_size[1] - new_width) // 2) * 2
box = (0, (im_size[1] - new_width) // 2, im_size[0], crop_width)
c_x = (K[0, 2] - (im_size[1] - new_width) / 2) / new_width
c_y = K[1, 2] / im_size[0]
rescale = im_size[0] / target_image_size[0]
f_x = (K[0, 0] / target_image_size[1]) / rescale
f_y = (K[1, 1] / target_image_size[0]) / rescale
box = tuple([int(x) for x in box])
else:
f_x = K[0, 0] / im_size[1]
f_y = K[1, 1] / im_size[0]
c_x = K[0, 2] / im_size[1]
c_y = K[1, 2] / im_size[0]
box = None
# Replace old K with new K
K[0, 0] = f_x * 2.
K[1, 1] = f_y * 2.
K[0, 2] = c_x * 2 - 1
K[1, 2] = c_y * 2 - 1
# Invert to get camera to center transformation, not center to camera
T_r = np.linalg.inv(T_r)
T_l = np.linalg.inv(T_l)
calibs[day] = {
"K": K,
"T_l": T_l,
"T_r": T_r,
"P_v2cl": P_v2cl,
"P_v2cr": P_v2cr,
"crop": box
}
return calibs
@staticmethod
def _load_poses(pose_path, sequences):
poses = {}
for day, seq, _ in sequences:
pose_file = Path(pose_path) / day / f"{seq}.txt"
poses_seq = []
try:
with open(pose_file, 'r') as f:
lines = f.readlines()
for line in lines:
T_w_cam0 = np.fromstring(line, dtype=float, sep=' ')
T_w_cam0 = T_w_cam0.reshape(3, 4)
T_w_cam0 = np.vstack((T_w_cam0, [0, 0, 0, 1]))
poses_seq.append(T_w_cam0)
except FileNotFoundError:
print(f'Ground truth poses are not avaialble for sequence {seq}.')
poses_seq = np.array(poses_seq, dtype=np.float32)
poses[(day, seq)] = poses_seq
return poses
def load_images(self, day, seq, ids, load_left, load_right):
imgs_left = []
imgs_right = []
for id in ids:
if load_left:
img = cv2.cvtColor(cv2.imread(os.path.join(self.data_path, day, seq, "image_02", "data", f"{id:010d}.jpg")), cv2.COLOR_BGR2RGB).astype(np.float32) / 255
imgs_left += [img]
if load_right:
img = cv2.cvtColor(cv2.imread(os.path.join(self.data_path, day, seq, "image_03", "data", f"{id:010d}.jpg")), cv2.COLOR_BGR2RGB).astype(np.float32) / 255
imgs_right += [img]
return imgs_left, imgs_right
def process_img(self, img: np.array, crop_box=None, color_aug_fn=None):
if crop_box:
|
# This could also be retrieved from
BASE_SIZES = {
"2011_09_26": (375, 1242),
"2011_09_28": (370, 1224),
"2011_09_29": (374, 1238),
"2011_09_30": (370, 1226),
"2011_10_03": (376, 1241),
}
class KittiRawDataset(Dataset):
def __init__(self,
data_path: str,
pose_path: str,
split_path: str,
target_image_size=(192, 640),
return_stereo=False,
return_depth=False,
frame_count=2,
keyframe_offset=0,
dilation=1,
keep_aspect_ratio=False,
eigen_depth=True,
color_aug=False
):
self.data_path = data_path
self.pose_path = pose_path
self.split_path = split_path
self.target_image_size = target_image_size
self.return_stereo = return_stereo
self.return_depth = return_depth
self.frame_count = frame_count
self.dilation = dilation
self.keyframe_offset = keyframe_offset
self.keep_aspect_ratio = keep_aspect_ratio
self.eigen_depth = eigen_depth
self.color_aug = color_aug
self._sequences = self._get_sequences(self.data_path)
self._seq_lengths = {(day, seq): length for day, seq, length in self._sequences}
self._calibs = self._load_calibs(self.data_path, self.target_image_size, keep_aspect_ratio)
self._poses = self._load_poses(self.pose_path, self._sequences)
self._datapoints = self._load_split(self.split_path)
self._left_offset = ((self.frame_count - 1) // 2 + self.keyframe_offset) * self.dilation
self._skip = 0
self.length = len(self._datapoints)
@staticmethod
def _get_sequences(data_path):
all_sequences = []
data_path = Path(data_path)
for day in data_path.iterdir():
if not day.is_dir():
continue
day_sequences = [seq for seq in day.iterdir() if seq.is_dir()]
lengths = [len(list((seq / "image_02" / "data").iterdir())) for seq in day_sequences]
day_sequences = [(day.name, seq.name, length) for seq, length in zip(day_sequences, lengths)]
all_sequences.extend(day_sequences)
return all_sequences
@staticmethod
def _load_split(split_path):
with open(split_path, "r") as f:
lines = f.readlines()
def split_line(l):
segments = l.split(" ")
day, sequence = segments[0].split("/")
# (day, sequence, id, is_right)
return day, sequence, int(segments[1]), segments[2] == "r"
return list(map(split_line, lines))
@staticmethod
def _load_calibs(data_path, target_image_size, keep_aspect_ratio):
calibs = {}
for day in BASE_SIZES.keys():
day_folder = Path(data_path) / day
cam_calib_file = day_folder / "calib_cam_to_cam.txt"
velo_calib_file = day_folder / "calib_velo_to_cam.txt"
cam_calib_file_data = {}
with open(cam_calib_file, 'r') as f:
for line in f.readlines():
key, value = line.split(':', 1)
try:
cam_calib_file_data[key] = np.array([float(x) for x in value.split()], dtype=np.float32)
except ValueError:
pass
velo_calib_file_data = {}
with open(velo_calib_file, 'r') as f:
for line in f.readlines():
key, value = line.split(':', 1)
try:
velo_calib_file_data[key] = np.array([float(x) for x in value.split()], dtype=np.float32)
except ValueError:
pass
im_size = BASE_SIZES[day]
# Create 3x4 projection matrices
P_rect_l = np.reshape(cam_calib_file_data['P_rect_02'], (3, 4))
P_rect_r = np.reshape(cam_calib_file_data['P_rect_03'], (3, 4))
R_rect = np.eye(4, dtype=np.float32)
R_rect[:3, :3] = cam_calib_file_data['R_rect_00'].reshape(3, 3)
T_v2c = np.hstack((velo_calib_file_data['R'].reshape(3, 3), velo_calib_file_data['T'][..., np.newaxis]))
T_v2c = np.vstack((T_v2c, np.array([0, 0, 0, 1.0], dtype=np.float32)))
P_v2cl = P_rect_l @ R_rect @ T_v2c
P_v2cr = P_rect_r @ R_rect @ T_v2c
# Compute the rectified extrinsics from cam0 to camN
T_l = np.eye(4, dtype=np.float32)
T_l[0, 3] = P_rect_l[0, 3] / P_rect_l[0, 0]
T_r = np.eye(4, dtype=np.float32)
T_r[0, 3] = P_rect_r[0, 3] / P_rect_r[0, 0]
K = P_rect_l[:3, :3]
if keep_aspect_ratio:
r_orig = im_size[0] / im_size[1]
r_target = target_image_size[0] / target_image_size[1]
if r_orig >= r_target:
new_height = r_target * im_size[1]
crop_height = im_size[0] - ((im_size[0] - new_height) // 2) * 2
box = ((im_size[0] - new_height) // 2, 0, crop_height, int(im_size[1]))
c_x = K[0, 2] / im_size[1]
c_y = (K[1, 2] - (im_size[0] - new_height) / 2) / new_height
rescale = im_size[1] / target_image_size[1]
else:
new_width = im_size[0] / r_target
crop_width = im_size[1] - ((im_size[1] - new_width) // 2) * 2
box = (0, (im_size[1] - new_width) // 2, im_size[0], crop_width)
c_x = (K[0, 2] - (im_size[1] - new_width) / 2) / new_width
c_y = K[1, 2] / im_size[0]
rescale = im_size[0] / target_image_size[0]
f_x = (K[0, 0] / target_image_size[1]) / rescale
f_y = (K[1, 1] / target_image_size[0]) / rescale
box = tuple([int(x) for x in box])
else:
f_x = K[0, 0] / im_size[1]
f_y = K[1, 1] / im_size[0]
c_x = K[0, 2] / im_size[1]
c_y = K[1, 2] / im_size[0]
box = None
# Replace old K with new K
K[0, 0] = f_x * 2.
K[1, 1] = f_y * 2.
K[0, 2] = c_x * 2 - 1
K[1, 2] = c_y * 2 - 1
# Invert to get camera to center transformation, not center to camera
T_r = np.linalg.inv(T_r)
T_l = np.linalg.inv(T_l)
calibs[day] = {
"K": K,
"T_l": T_l,
"T_r": T_r,
"P_v2cl": P_v2cl,
"P_v2cr": P_v2cr,
"crop": box
}
return calibs
@staticmethod
def _load_poses(pose_path, sequences):
poses = {}
for day, seq, _ in sequences:
pose_file = Path(pose_path) / day / f"{seq}.txt"
poses_seq = []
try:
with open(pose_file, 'r') as f:
lines = f.readlines()
for line in lines:
T_w_cam0 = np.fromstring(line, dtype=float, sep=' ')
T_w_cam0 = T_w_cam0.reshape(3, 4)
T_w_cam0 = np.vstack((T_w_cam0, [0, 0, 0, 1]))
poses_seq.append(T_w_cam0)
except FileNotFoundError:
print(f'Ground truth poses are not avaialble for sequence {seq}.')
poses_seq = np.array(poses_seq, dtype=np.float32)
poses[(day, seq)] = poses_seq
return poses
def load_images(self, day, seq, ids, load_left, load_right):
imgs_left = []
imgs_right = []
for id in ids:
if load_left:
img = cv2.cvtColor(cv2.imread(os.path.join(self.data_path, day, seq, "image_02", "data", f"{id:010d}.jpg")), cv2.COLOR_BGR2RGB).astype(np.float32) / 255
imgs_left += [img]
if load_right:
img = cv2.cvtColor(cv2.imread(os.path.join(self.data_path, day, seq, "image_03", "data", f"{id:010d}.jpg")), cv2.COLOR_BGR2RGB).astype(np.float32) / 255
imgs_right += [img]
return imgs_left, imgs_right
def process_img(self, img: np.array, crop_box=None, color_aug_fn=None):
if crop_box: | img = apply_crop(img, crop_box) | 0 | 2023-11-12 21:53:27+00:00 | 4k |
TimbreWatermarking/TimbreWatermarking | watermarking_model/model/modules.py | [
{
"identifier": "FCBlock",
"path": "watermarking_model/model/blocks.py",
"snippet": "class FCBlock(nn.Module):\n \"\"\" Fully Connected Block \"\"\"\n\n def __init__(self, in_features, out_features, activation=None, bias=False, dropout=None, spectral_norm=False):\n super(FCBlock, self).__in... | from base64 import encode
from torch.nn import LeakyReLU
from .blocks import FCBlock, PositionalEncoding, Mish, Conv1DBlock
import torch
import torch.nn as nn | 1,743 |
class Encoder(nn.Module):
def __init__(self, model_config, msg_length, win_dim, embedding_dim, nlayers_encoder=6, transformer_drop=0.1, attention_heads=8):
super(Encoder, self).__init__()
self.encoder_layer = nn.TransformerEncoderLayer(d_model=embedding_dim, nhead=attention_heads, dropout=transformer_drop)
self.dec_encoder_layer = nn.TransformerDecoderLayer(d_model=embedding_dim, nhead=attention_heads, dropout=transformer_drop)
self.encoder = nn.TransformerEncoder(self.encoder_layer, nlayers_encoder)
self.decoder = nn.TransformerDecoder(self.dec_encoder_layer, nlayers_encoder)
#MLP for the input audio waveform
self.wav_linear_in = FCBlock(win_dim, embedding_dim, activation=LeakyReLU(inplace=True))
self.wav_linear_out = FCBlock(embedding_dim, win_dim)
#MLP for the input wm
self.msg_linear_in = FCBlock(msg_length, embedding_dim, activation=LeakyReLU(inplace=True))
#position encoding
self.pos_encoder = PositionalEncoding(d_model=embedding_dim, dropout=transformer_drop)
def forward_encode_msg(self, x, w):
x_embedding = self.wav_linear_in(x)
p_x = self.pos_encoder(x_embedding)
encoder_out = self.encoder(p_x.transpose(0,1)).transpose(0,1) # tgt_len, bsz, embed_dim = query.size()
# Temporal Average Pooling
wav_feature = torch.mean(encoder_out, dim=1, keepdim=True) # [B, 1, H]
msg_feature = self.msg_linear_in(w)
encoded_msg = wav_feature.add(msg_feature)
return encoded_msg, encoder_out, p_x
def forward_decode_wav(self, encoded_msg, encoder_out, p_x):
# B, _, D = encoded_msg.shape
encode_msg_repeat = encoded_msg.repeat(1, p_x.size(1), 1)
embeded = self.decoder((encode_msg_repeat + p_x).transpose(0,1), memory=encoder_out.transpose(0,1)).transpose(0,1)
wav_out = self.wav_linear_out(embeded)
return wav_out
def forward(self, x, w):
encoded_msg, encoder_out, p_x = self.forward_encode_msg(x, w)
wav_out = self.forward_decode_wav(encoded_msg, encoder_out, p_x)
return wav_out
class Decoder(nn.Module):
def __init__(self, model_config, msg_length, win_dim, embedding_dim, nlayers_decoder=6, transformer_drop=0.1, attention_heads=8):
super(Decoder, self).__init__()
self.msg_decoder_layer = nn.TransformerEncoderLayer(d_model=embedding_dim, nhead=attention_heads, dropout=transformer_drop)
self.msg_decoder = nn.TransformerEncoder(self.msg_decoder_layer, nlayers_decoder)
self.msg_linear_out = FCBlock(embedding_dim, msg_length)
#MLP for the input audio waveform
self.wav_linear_in = FCBlock(win_dim, embedding_dim, activation=LeakyReLU(inplace=True))
#position encoding
self.pos_encoder = PositionalEncoding(d_model=embedding_dim, dropout=transformer_drop)
def forward(self, x):
x_embedding = self.wav_linear_in(x)
p_x = self.pos_encoder(x_embedding)
encoder_out = self.msg_decoder(p_x.transpose(0,1)).transpose(0,1)
# Temporal Average Pooling
wav_feature = torch.mean(encoder_out, dim=1, keepdim=True) # [B, 1, H]
out_msg = self.msg_linear_out(wav_feature)
return out_msg
class Discriminator(nn.Module):
def __init__(self, msg_length, win_dim, embedding_dim, nlayers_decoder=6, transformer_drop=0.1, attention_heads=8):
super(Decoder, self).__init__()
self.msg_decoder_layer = nn.TransformerEncoderLayer(d_model=embedding_dim, nhead=attention_heads, dropout=transformer_drop)
self.msg_decoder = nn.TransformerEncoder(self.msg_decoder_layer, nlayers_decoder)
self.msg_linear_out = FCBlock(embedding_dim, msg_length)
#MLP for the input audio waveform
|
class Encoder(nn.Module):
def __init__(self, model_config, msg_length, win_dim, embedding_dim, nlayers_encoder=6, transformer_drop=0.1, attention_heads=8):
super(Encoder, self).__init__()
self.encoder_layer = nn.TransformerEncoderLayer(d_model=embedding_dim, nhead=attention_heads, dropout=transformer_drop)
self.dec_encoder_layer = nn.TransformerDecoderLayer(d_model=embedding_dim, nhead=attention_heads, dropout=transformer_drop)
self.encoder = nn.TransformerEncoder(self.encoder_layer, nlayers_encoder)
self.decoder = nn.TransformerDecoder(self.dec_encoder_layer, nlayers_encoder)
#MLP for the input audio waveform
self.wav_linear_in = FCBlock(win_dim, embedding_dim, activation=LeakyReLU(inplace=True))
self.wav_linear_out = FCBlock(embedding_dim, win_dim)
#MLP for the input wm
self.msg_linear_in = FCBlock(msg_length, embedding_dim, activation=LeakyReLU(inplace=True))
#position encoding
self.pos_encoder = PositionalEncoding(d_model=embedding_dim, dropout=transformer_drop)
def forward_encode_msg(self, x, w):
x_embedding = self.wav_linear_in(x)
p_x = self.pos_encoder(x_embedding)
encoder_out = self.encoder(p_x.transpose(0,1)).transpose(0,1) # tgt_len, bsz, embed_dim = query.size()
# Temporal Average Pooling
wav_feature = torch.mean(encoder_out, dim=1, keepdim=True) # [B, 1, H]
msg_feature = self.msg_linear_in(w)
encoded_msg = wav_feature.add(msg_feature)
return encoded_msg, encoder_out, p_x
def forward_decode_wav(self, encoded_msg, encoder_out, p_x):
# B, _, D = encoded_msg.shape
encode_msg_repeat = encoded_msg.repeat(1, p_x.size(1), 1)
embeded = self.decoder((encode_msg_repeat + p_x).transpose(0,1), memory=encoder_out.transpose(0,1)).transpose(0,1)
wav_out = self.wav_linear_out(embeded)
return wav_out
def forward(self, x, w):
encoded_msg, encoder_out, p_x = self.forward_encode_msg(x, w)
wav_out = self.forward_decode_wav(encoded_msg, encoder_out, p_x)
return wav_out
class Decoder(nn.Module):
def __init__(self, model_config, msg_length, win_dim, embedding_dim, nlayers_decoder=6, transformer_drop=0.1, attention_heads=8):
super(Decoder, self).__init__()
self.msg_decoder_layer = nn.TransformerEncoderLayer(d_model=embedding_dim, nhead=attention_heads, dropout=transformer_drop)
self.msg_decoder = nn.TransformerEncoder(self.msg_decoder_layer, nlayers_decoder)
self.msg_linear_out = FCBlock(embedding_dim, msg_length)
#MLP for the input audio waveform
self.wav_linear_in = FCBlock(win_dim, embedding_dim, activation=LeakyReLU(inplace=True))
#position encoding
self.pos_encoder = PositionalEncoding(d_model=embedding_dim, dropout=transformer_drop)
def forward(self, x):
x_embedding = self.wav_linear_in(x)
p_x = self.pos_encoder(x_embedding)
encoder_out = self.msg_decoder(p_x.transpose(0,1)).transpose(0,1)
# Temporal Average Pooling
wav_feature = torch.mean(encoder_out, dim=1, keepdim=True) # [B, 1, H]
out_msg = self.msg_linear_out(wav_feature)
return out_msg
class Discriminator(nn.Module):
def __init__(self, msg_length, win_dim, embedding_dim, nlayers_decoder=6, transformer_drop=0.1, attention_heads=8):
super(Decoder, self).__init__()
self.msg_decoder_layer = nn.TransformerEncoderLayer(d_model=embedding_dim, nhead=attention_heads, dropout=transformer_drop)
self.msg_decoder = nn.TransformerEncoder(self.msg_decoder_layer, nlayers_decoder)
self.msg_linear_out = FCBlock(embedding_dim, msg_length)
#MLP for the input audio waveform | self.wav_linear_in = FCBlock(win_dim, embedding_dim, activation=Mish()) | 2 | 2023-11-13 01:40:03+00:00 | 4k |
joseph-crowley/tool-creator | tool_user.py | [
{
"identifier": "AssistantConfig",
"path": "user_config.py",
"snippet": "class AssistantConfig:\n def __init__(self, tools_to_use=None):\n self.tools_to_use = tools_to_use or []\n self.instructions_for_assistant = 'Use the tools to accomplish the task'\n self.files_for_assistant ... | import os
import json
from user_config import AssistantConfig as UserConfig
from utils import chat as chat_loop
from openai import OpenAI | 2,411 | """
Create an assistant using the tools from tool_creator using the assistant creation API
"""
client = OpenAI() # be sure to set your OPENAI_API_KEY environment variable
def create_tool_user(assistant_details):
# create the assistant
tool_user = client.beta.assistants.create(**assistant_details["build_params"])
print(f"Created assistant {tool_user.id} to use tools\n\n" + 90*"-" + "\n\n", flush=True)
# save the assistant info to a json file
info_to_export = {
"assistant_id": tool_user.id,
"assistant_details": assistant_details,
}
os.makedirs('assistants', exist_ok=True)
with open('assistants/tool_user.json', 'w') as f:
json.dump(info_to_export, f, indent=4)
return tool_user
def talk_to_tool_user(assistant_details):
"""
talk to the assistant to use the tools
"""
# check if json file exists
try:
os.makedirs('assistants', exist_ok=True)
with open('assistants/tool_user.json') as f:
create_new = input(f'Assistant details found in tool_user.json. Create a new assistant? [y/N]')
if create_new == 'y':
raise Exception("User wants a new assistant")
assistant_from_json = json.load(f)
tool_user = client.beta.assistants.retrieve(assistant_from_json['assistant_id'])
print(f"Loaded assistant details from tool_user.json\n\n" + 90*"-" + "\n\n", flush=True)
print(f'Assistant {tool_user.id}:\n')
assistant_details = assistant_from_json["assistant_details"]
except:
# create the assistant first
tool_user = create_tool_user(assistant_details)
# gather the dependencies
dependencies = assistant_details["dependencies"]
if dependencies:
print(f"Installing dependencies...", flush=True)
for d in dependencies:
os.system(f"pip install {d}")
print(f"Installed dependencies\n\n" + 90*"-" + "\n\n", flush=True)
# exec the functions from the py files
os.makedirs('tools', exist_ok=True)
functions = assistant_details["functions"]
for func in functions:
print(f"Loading function {func} into execution environment", flush=True)
try:
with open('tools/' + func + '.py') as f:
exec(f.read(), globals())
functions.update({func: eval(func)})
except Exception as e:
print(f"Exception loading function {func}: {e}", flush=True)
print(f"Continuing without {func}...", flush=True)
print(f"Loaded functions\n\n" + 90*"-" + "\n\n", flush=True)
# Create thread
thread = client.beta.threads.create()
# chat with the assistant
| """
Create an assistant using the tools from tool_creator using the assistant creation API
"""
client = OpenAI() # be sure to set your OPENAI_API_KEY environment variable
def create_tool_user(assistant_details):
# create the assistant
tool_user = client.beta.assistants.create(**assistant_details["build_params"])
print(f"Created assistant {tool_user.id} to use tools\n\n" + 90*"-" + "\n\n", flush=True)
# save the assistant info to a json file
info_to_export = {
"assistant_id": tool_user.id,
"assistant_details": assistant_details,
}
os.makedirs('assistants', exist_ok=True)
with open('assistants/tool_user.json', 'w') as f:
json.dump(info_to_export, f, indent=4)
return tool_user
def talk_to_tool_user(assistant_details):
"""
talk to the assistant to use the tools
"""
# check if json file exists
try:
os.makedirs('assistants', exist_ok=True)
with open('assistants/tool_user.json') as f:
create_new = input(f'Assistant details found in tool_user.json. Create a new assistant? [y/N]')
if create_new == 'y':
raise Exception("User wants a new assistant")
assistant_from_json = json.load(f)
tool_user = client.beta.assistants.retrieve(assistant_from_json['assistant_id'])
print(f"Loaded assistant details from tool_user.json\n\n" + 90*"-" + "\n\n", flush=True)
print(f'Assistant {tool_user.id}:\n')
assistant_details = assistant_from_json["assistant_details"]
except:
# create the assistant first
tool_user = create_tool_user(assistant_details)
# gather the dependencies
dependencies = assistant_details["dependencies"]
if dependencies:
print(f"Installing dependencies...", flush=True)
for d in dependencies:
os.system(f"pip install {d}")
print(f"Installed dependencies\n\n" + 90*"-" + "\n\n", flush=True)
# exec the functions from the py files
os.makedirs('tools', exist_ok=True)
functions = assistant_details["functions"]
for func in functions:
print(f"Loading function {func} into execution environment", flush=True)
try:
with open('tools/' + func + '.py') as f:
exec(f.read(), globals())
functions.update({func: eval(func)})
except Exception as e:
print(f"Exception loading function {func}: {e}", flush=True)
print(f"Continuing without {func}...", flush=True)
print(f"Loaded functions\n\n" + 90*"-" + "\n\n", flush=True)
# Create thread
thread = client.beta.threads.create()
# chat with the assistant | chat_loop(client, thread, tool_user, functions) | 0 | 2023-11-10 03:02:32+00:00 | 4k |
nillion-oss/tinysig | src/tinysig/tecdsa.py | [
{
"identifier": "add",
"path": "src/tinysig/utils.py",
"snippet": "def add(values: list[int], size: int) -> int:\ndef add_ec(points: list[EccPoint]) -> int:\ndef generate_additive_shares(secret: int, n: int, size: int) -> list[int]:\ndef multiply(values: list[int], size: int) -> int:\ndef egcd(a: int, p... | from Crypto.Hash import SHA256
from phe import paillier
from typing import List
from .utils import add, add_ec, multiply, rand, egcd, verify_dsa_signature, verify_ecdsa_signature
from .setup import DSASetup, ECDSASetup
from .network import Network, Client | 3,566 | raise TypeError("Invalid type provided. "
"Please use either 'DSASetup' or 'ECDSASetup' types."
)
# Generate public and private keys for the paillier homomorphic encryption scheme
for i in range(C):
pub_key, priv_key = paillier.generate_paillier_keypair()
self.clients[i].he_private_key = priv_key
for node in self.nodes:
node.he_public_keys[i] = pub_key
for client in self.clients:
client.he_public_keys[i] = pub_key
def get_lambda(self, labels: list[str]) -> None:
"""
Emulates the generation of LAMBDA pairs :math:`([h^{\gamma}], [\gamma])` between all nodes.
Parameters:
labels (list[str]): A list of labels for which lambda values will be generated
and stored.
Returns:
None
"""
n = len(labels)
h = self.h
q = self.q
q_minus_one = q - 1
for l in range(n):
# Locally generate lambda
alpha = rand(q_minus_one)
h_alpha = pow(h, alpha, q)
self.share(alpha, q_minus_one, labels[l]+"_lambda_sh_exp")
self.share(h_alpha, q, labels[l]+"_lambda_sh_base")
def rss_protocol(self, size: int, label: str) -> None:
"""
Random Secret Sharing (RSS) Protocol.
This function implements a one-round RSS protocol. The goal is to share a random
secret value among a group of nodes using a specific label for the shares.
Parameters:
size (int): The maximum size of the random secret to be generated and shared.
label (str): A label to identify the shared secrets and their associated operations.
Returns:
None
"""
# Round 1
for node in self.nodes:
# Step 1: locally generate random secret
random_element = rand(size)
# Step 2: share random secret with all nodes
self.share(random_element, size, label+"sh_node_"+str(node.id))
# All local
for node in self.nodes:
# DB management
list_of_shares = [
node.get_share(label + "sh_node_" + str(other_node.id))
for other_node in self.nodes
]
# Step 3: add locally all shares
random_sum = add(list_of_shares, size)
# DB management
sh_label = label+"_sh_exp"
node.set_share(random_sum, sh_label)
if not self.debug:
[node.delete_share(label + "sh_node_" + str(other_node.id))
for other_node in self.nodes]
def pow_share_protocol(self, base_type: str, get_label: str, save_label: str) -> None:
"""
Compute a power-sharing protocol among a group of nodes.
This function implements a one-round protocol to securely compute :math:`b^{s}` where
the exponent is a secret shared element between the nodes.
Parameters:
base_type (str): The type of base used: 'exp', when base to be used is self.h;
'base', when the base to be used is self.dsa.g. Note: 'base'
option can only be use for the DSA setup.
get_label (str): The label to retrieve shares of 's' from nodes.
save_label (str): The label to save the final result to.
Returns:
None
"""
if base_type not in ["exp", "base"]:
raise ValueError("{} is not one of the specified base types.\
Please choose one of the following:\n \
['exp', 'base']".format(base_type))
prime = self.q if base_type == "exp" else self.dsa.p
# Round 1
for node in self.nodes:
# DB management
exponent = node.get_share(get_label+"_sh_"+base_type)
# Step 1: compute base^share
if base_type == "exp":
h_exp = pow(self.h, exponent, prime)
else:
h_exp = pow(self.dsa.g, exponent, prime)
# Step 2: Broadcast base^share to nodes
self.broadcast(h_exp, "pow_share_node_"+str(node.id))
# All local
for node in self.nodes:
# DB management
base_exps = [
node.get_open("pow_share_node_"+str(other_node.id))
for other_node in self.nodes
]
# Step 3: multiply locally all powers of shares
|
class ThresholdSignature(Network):
clients: List[Client]
def __init__(self, N, C, setup=None, debug=False):
self.debug = debug
if setup is None:
self.dsa = DSASetup.generate_dsa_setup()
self.setup = DSASetup
super().__init__(N, self.dsa.q, self.dsa.h)
elif type(setup) == DSASetup:
self.dsa = setup
self.setup = DSASetup
super().__init__(N, self.dsa.q, self.dsa.h)
elif type(setup) == ECDSASetup:
self.ecdsa = setup.generate_ecdsa_setup()
self.setup = ECDSASetup
super().__init__(N, self.ecdsa.q, self.ecdsa.h)
else:
raise TypeError("Invalid type provided. "
"Please use either 'DSASetup' or 'ECDSASetup' types."
)
# Generate public and private keys for the paillier homomorphic encryption scheme
for i in range(C):
pub_key, priv_key = paillier.generate_paillier_keypair()
self.clients[i].he_private_key = priv_key
for node in self.nodes:
node.he_public_keys[i] = pub_key
for client in self.clients:
client.he_public_keys[i] = pub_key
def get_lambda(self, labels: list[str]) -> None:
"""
Emulates the generation of LAMBDA pairs :math:`([h^{\gamma}], [\gamma])` between all nodes.
Parameters:
labels (list[str]): A list of labels for which lambda values will be generated
and stored.
Returns:
None
"""
n = len(labels)
h = self.h
q = self.q
q_minus_one = q - 1
for l in range(n):
# Locally generate lambda
alpha = rand(q_minus_one)
h_alpha = pow(h, alpha, q)
self.share(alpha, q_minus_one, labels[l]+"_lambda_sh_exp")
self.share(h_alpha, q, labels[l]+"_lambda_sh_base")
def rss_protocol(self, size: int, label: str) -> None:
"""
Random Secret Sharing (RSS) Protocol.
This function implements a one-round RSS protocol. The goal is to share a random
secret value among a group of nodes using a specific label for the shares.
Parameters:
size (int): The maximum size of the random secret to be generated and shared.
label (str): A label to identify the shared secrets and their associated operations.
Returns:
None
"""
# Round 1
for node in self.nodes:
# Step 1: locally generate random secret
random_element = rand(size)
# Step 2: share random secret with all nodes
self.share(random_element, size, label+"sh_node_"+str(node.id))
# All local
for node in self.nodes:
# DB management
list_of_shares = [
node.get_share(label + "sh_node_" + str(other_node.id))
for other_node in self.nodes
]
# Step 3: add locally all shares
random_sum = add(list_of_shares, size)
# DB management
sh_label = label+"_sh_exp"
node.set_share(random_sum, sh_label)
if not self.debug:
[node.delete_share(label + "sh_node_" + str(other_node.id))
for other_node in self.nodes]
def pow_share_protocol(self, base_type: str, get_label: str, save_label: str) -> None:
"""
Compute a power-sharing protocol among a group of nodes.
This function implements a one-round protocol to securely compute :math:`b^{s}` where
the exponent is a secret shared element between the nodes.
Parameters:
base_type (str): The type of base used: 'exp', when base to be used is self.h;
'base', when the base to be used is self.dsa.g. Note: 'base'
option can only be use for the DSA setup.
get_label (str): The label to retrieve shares of 's' from nodes.
save_label (str): The label to save the final result to.
Returns:
None
"""
if base_type not in ["exp", "base"]:
raise ValueError("{} is not one of the specified base types.\
Please choose one of the following:\n \
['exp', 'base']".format(base_type))
prime = self.q if base_type == "exp" else self.dsa.p
# Round 1
for node in self.nodes:
# DB management
exponent = node.get_share(get_label+"_sh_"+base_type)
# Step 1: compute base^share
if base_type == "exp":
h_exp = pow(self.h, exponent, prime)
else:
h_exp = pow(self.dsa.g, exponent, prime)
# Step 2: Broadcast base^share to nodes
self.broadcast(h_exp, "pow_share_node_"+str(node.id))
# All local
for node in self.nodes:
# DB management
base_exps = [
node.get_open("pow_share_node_"+str(other_node.id))
for other_node in self.nodes
]
# Step 3: multiply locally all powers of shares | val = multiply(base_exps, prime) | 0 | 2023-11-14 13:55:41+00:00 | 4k |
Exscientia/physicsml | src/physicsml/models/mace/modules/blocks.py | [
{
"identifier": "Activation",
"path": "src/physicsml/models/mace/modules/_activation.py",
"snippet": "class Activation(torch.nn.Module):\n r\"\"\"Scalar activation function.\n\n Odd scalar inputs require activation functions with a defined parity (odd or even).\n\n Parameters\n ----------\n ... | from typing import Optional
from e3nn import nn, o3
from torch_geometric.utils.scatter import scatter
from ._activation import Activation
from .irreps_tools import reshape_irreps, tp_out_irreps_with_instructions
from .radial import BesselBasis, PolynomialCutoff
from .symmetric_contraction import SymmetricContraction
import torch | 3,534 |
class NonLinearReadoutBlock(torch.nn.Module):
def __init__(
self,
irreps_in: o3.Irreps,
MLP_irreps: o3.Irreps,
irreps_out: o3.Irreps,
) -> None:
super().__init__()
self.linear_1 = o3.Linear(irreps_in=irreps_in, irreps_out=MLP_irreps)
self.non_linearity = Activation(irreps_in=MLP_irreps, acts=[torch.nn.SiLU()])
self.linear_2 = o3.Linear(irreps_in=MLP_irreps, irreps_out=irreps_out)
def forward(self, x: torch.Tensor) -> torch.Tensor: # [n_nodes, irreps] # [..., ]
x = self.linear_1(x)
x = self.non_linearity(x)
x = self.linear_2(x)
return x
class RadialEmbeddingBlock(torch.nn.Module):
def __init__(
self,
r_max: float,
num_bessel: int,
num_polynomial_cutoff: int,
) -> None:
super().__init__()
self.bessel_fn = BesselBasis(r_max=r_max, num_basis=num_bessel)
self.cutoff_fn = PolynomialCutoff(r_max=r_max, p=num_polynomial_cutoff)
self.out_dim = num_bessel
def forward(
self,
edge_lengths: torch.Tensor, # [n_edges, 1]
) -> torch.Tensor:
bessel = self.bessel_fn(edge_lengths) # [n_edges, n_basis]
cutoff = self.cutoff_fn(edge_lengths) # [n_edges, 1]
output: torch.Tensor = bessel * cutoff # [n_edges, n_basis]
return output
class NodeUpdateBlock(torch.nn.Module):
def __init__(
self,
node_attrs_irreps: o3.Irreps,
node_feats_irreps: o3.Irreps,
hidden_irreps: o3.Irreps,
residual_connection: bool,
) -> None:
super().__init__()
# net to compute W m_i
self.linear = o3.Linear(
hidden_irreps,
hidden_irreps,
internal_weights=True,
shared_weights=True,
)
if residual_connection:
# residual connection from original node attrs and node features
self.residual_connection_layer = o3.FullyConnectedTensorProduct(
node_feats_irreps,
node_attrs_irreps,
hidden_irreps,
)
else:
self.residual_connection_layer = None
def forward(
self,
m_i: torch.Tensor,
node_feats: torch.Tensor,
node_attrs: torch.Tensor,
) -> torch.Tensor:
if self.residual_connection_layer is not None:
node_feats = self.linear(m_i) + self.residual_connection_layer(
node_feats,
node_attrs,
)
else:
node_feats = self.linear(m_i)
return node_feats
class MessageBlock(torch.nn.Module):
def __init__(
self,
interaction_irreps: o3.Irreps,
node_attrs_irreps: o3.Irreps,
hidden_irreps: o3.Irreps,
correlation: int,
) -> None:
super().__init__()
# symmetric contraction to make A_i into messages m_i = W B_i
|
class NonLinearReadoutBlock(torch.nn.Module):
def __init__(
self,
irreps_in: o3.Irreps,
MLP_irreps: o3.Irreps,
irreps_out: o3.Irreps,
) -> None:
super().__init__()
self.linear_1 = o3.Linear(irreps_in=irreps_in, irreps_out=MLP_irreps)
self.non_linearity = Activation(irreps_in=MLP_irreps, acts=[torch.nn.SiLU()])
self.linear_2 = o3.Linear(irreps_in=MLP_irreps, irreps_out=irreps_out)
def forward(self, x: torch.Tensor) -> torch.Tensor: # [n_nodes, irreps] # [..., ]
x = self.linear_1(x)
x = self.non_linearity(x)
x = self.linear_2(x)
return x
class RadialEmbeddingBlock(torch.nn.Module):
def __init__(
self,
r_max: float,
num_bessel: int,
num_polynomial_cutoff: int,
) -> None:
super().__init__()
self.bessel_fn = BesselBasis(r_max=r_max, num_basis=num_bessel)
self.cutoff_fn = PolynomialCutoff(r_max=r_max, p=num_polynomial_cutoff)
self.out_dim = num_bessel
def forward(
self,
edge_lengths: torch.Tensor, # [n_edges, 1]
) -> torch.Tensor:
bessel = self.bessel_fn(edge_lengths) # [n_edges, n_basis]
cutoff = self.cutoff_fn(edge_lengths) # [n_edges, 1]
output: torch.Tensor = bessel * cutoff # [n_edges, n_basis]
return output
class NodeUpdateBlock(torch.nn.Module):
def __init__(
self,
node_attrs_irreps: o3.Irreps,
node_feats_irreps: o3.Irreps,
hidden_irreps: o3.Irreps,
residual_connection: bool,
) -> None:
super().__init__()
# net to compute W m_i
self.linear = o3.Linear(
hidden_irreps,
hidden_irreps,
internal_weights=True,
shared_weights=True,
)
if residual_connection:
# residual connection from original node attrs and node features
self.residual_connection_layer = o3.FullyConnectedTensorProduct(
node_feats_irreps,
node_attrs_irreps,
hidden_irreps,
)
else:
self.residual_connection_layer = None
def forward(
self,
m_i: torch.Tensor,
node_feats: torch.Tensor,
node_attrs: torch.Tensor,
) -> torch.Tensor:
if self.residual_connection_layer is not None:
node_feats = self.linear(m_i) + self.residual_connection_layer(
node_feats,
node_attrs,
)
else:
node_feats = self.linear(m_i)
return node_feats
class MessageBlock(torch.nn.Module):
def __init__(
self,
interaction_irreps: o3.Irreps,
node_attrs_irreps: o3.Irreps,
hidden_irreps: o3.Irreps,
correlation: int,
) -> None:
super().__init__()
# symmetric contraction to make A_i into messages m_i = W B_i | self.symmetric_contractions = SymmetricContraction( | 5 | 2023-11-10 13:54:53+00:00 | 4k |
naver-ai/scob | utils/config_manager.py | [
{
"identifier": "misc",
"path": "utils/misc.py",
"snippet": "def get_node_rank():\ndef get_local_rank():\ndef is_rank_zero():\ndef cpu_count():\ndef get_file(dataset_path, prefix, postfix, ext):\ndef is_otor(task_name, or_oracle=False, oracle=False):"
},
{
"identifier": "AVAILABLE_TASKS",
"p... | import enum
import os
import pickle
import time
import torch
import torch.distributed as dist
from datetime import timedelta
from omegaconf import OmegaConf
from omegaconf.dictconfig import DictConfig
from utils import misc
from utils.constants import AVAILABLE_TASKS, DecoderTypes, HeadTypes, Seperators, Tasks
from utils.misc import cpu_count, is_otor
from utils.singleton import Singleton
| 2,971 | "This configuration should be added"
" automatically in runtime."
)
for mode in ["train", "val", "test"]:
num_devices = torch.cuda.device_count() * self.__config.train.num_nodes
if self.__config[mode].batch_size % num_devices != 0:
raise ValueError(
f"{mode} batch-size should be a multiple"
" of the number of gpu devices"
)
# check decoder_names
decoder_name_set_from_dataset_items = set()
for dataset_item in self.__config.dataset_items:
for task in dataset_item.tasks:
decoder_name_set_from_dataset_items.add(task.decoder)
decoder_name_set_from_decoders = set()
for decoder_name, decoder_cfg in self.__config.model.decoders.items():
decoder_name_set_from_decoders.add(decoder_name)
assert decoder_name.startswith(decoder_cfg.type)
if decoder_name_set_from_dataset_items != decoder_name_set_from_decoders:
raise ValueError(
"Please match decoder-names.\n"
f"dec-names from dataset_items: {decoder_name_set_from_dataset_items}\n"
f"dec-names from decoders: {decoder_name_set_from_decoders}"
)
# Check available tasks
for dataset_item in self.__config.dataset_items:
for task in dataset_item.tasks:
decoder_cfg = self.__config.model.decoders[task.decoder]
available_tasks = AVAILABLE_TASKS[decoder_cfg.type]
if task.name not in available_tasks:
raise ValueError(
f"Unavailable task {task.name} for decoder {task.decoder}"
)
if decoder_cfg.type == DecoderTypes.TRANSFORMER:
assert not (
(decoder_cfg.head_type == HeadTypes.TWO_HEAD)
^ task.name.endswith(HeadTypes.TWO_HEAD)
), "Two head model should solve two head task."
# Check image_normalize type in PATCH_CLS with grayscale label
if (
hasattr(decoder_cfg, "task")
and decoder_cfg.task == Tasks.PATCH_CLS
and decoder_cfg.kwargs.classification_type == "grayscale"
):
transforms_dict = task.transforms_dict
if isinstance(transforms_dict, str):
if transforms_dict not in self.__config.custom_transforms_dict:
raise ValueError(
f"{transforms_dict} is not in cfg.custom_transforms_dict"
)
transforms_dict = self.__config.custom_transforms_dict[
transforms_dict
]
assert transforms_dict["image_normalize"] == "imagenet_default"
def __change_config(self):
"""Change config like path"""
cfg = self.__config # get reference of __config
# -------------------------------------------
# for convinience (only used for evaluate.py)
if cfg.eval.dataset_name is not None and cfg.eval.task_name is not None:
cfg.dataset_items = [get_eval_dataset_item(cfg.eval)]
# -------------------------------------------
workspace = cfg.workspace_name
if workspace is None:
workspace = os.getcwd()
cfg.workspace = workspace
self.__change_data_paths()
cfg.model.resume_model_path = self.__change_weight_path(
workspace, cfg.model.resume_model_path
)
self.__change_log_dirs()
num_devices = torch.cuda.device_count() * cfg.train.num_nodes
for mode in ["train", "val", "test"]:
# set per-gpu num_workers
if cfg.debug:
cfg[mode].num_workers = 0
else:
num_workers = cfg[mode].num_workers
if num_workers == -1:
num_workers = cpu_count() * cfg.train.num_nodes
cfg[mode].num_workers = max(num_workers // num_devices, 1)
# set per-gpu batch size
new_batch_size = cfg[mode].batch_size // num_devices
cfg[mode].batch_size = new_batch_size
if mode == "train" and is_otor(cfg.dataset_items[0].tasks[0].name):
if cfg[mode].batch_size % 2 > 0:
assert (
cfg[mode].batch_size % 2 == 0
), "when use otor, batch size should be even number."
cfg[mode].batch_size = cfg[mode].batch_size // 2
if cfg.reproduce.seed == -1:
# To avoid each rank have different random_seed, we use TCPStore.
if misc.is_rank_zero():
random_seed = int(time.time()) % 10000
self.__tcp_store_server.set("random_seed", str(random_seed))
else:
random_seed = int(self.__tcp_store_cli.get("random_seed").decode())
cfg.reproduce.seed = random_seed
# Make DTD (Dataset-name, Task-name, Decoder-name) configs
dtd_dict = {}
for dataset_item in cfg.dataset_items:
dataset_name = dataset_item.name
for task in dataset_item.tasks:
| """
SCOB
Copyright (c) 2023-present NAVER Cloud Corp.
MIT license
config parser with omegaconf
"""
class FileType(enum.Enum): # pylint: disable=missing-class-docstring
YAML = 1
PICKLE = 2
class ConfigManager(metaclass=Singleton):
"""Singleton ConfigManager for project
Notes:
Do not call ConfigManager.get_instance() inside the model class.
When creating a model instance, all necessary arguments must be received as constructor arguments.
SHOULD_NOT_USE_CONFIGS (List[str]): Keys that should not be included in the configuration.
Because the corresponding configurations are applied at runtime,
It should not be given through defualt.yaml, user config, or CLI.
"""
SHOULD_NOT_USE_CONFIGS = [
"workspace",
"save_weight_dir",
"tensorboard_dir",
"dtd_dict",
]
def __init__(
self,
conf_path=None,
default_conf_path="./configs/default.yaml",
conf_type=FileType.YAML,
default_conf_type=FileType.YAML,
use_cli=True,
):
self.__config = None
self.__tcp_store_server = None
self.__tcp_store_cli = None
self.default_conf_path = default_conf_path
self.conf_path = conf_path
self.__load(default_conf_type, conf_type, use_cli)
@property
def cfg(self):
"""Return path config"""
return self.__config
@property
def model_cfg(self):
"""Return model config"""
return self.__config.model
def __load(self, default_conf_type, conf_type, use_cli):
"""load config from file"""
# Load configuration parameters
# Step 1. Default config
self.__config = self.__read_conf(self.default_conf_path, default_conf_type)
# Step 2. Config specified by __init__()
if self.conf_path:
cfg = self.__read_conf(self.conf_path, conf_type)
self.__merge_config(cfg)
if use_cli:
# Step 3. Config specified CLI's --config parameter
cfg_cli = self.__get_config_from_cli()
if "config" in cfg_cli:
cfg = OmegaConf.load(cfg_cli.config)
self.__merge_config(cfg)
# Step 4. Config specified CLI's --XYZ parameters
self.__merge_config(cfg_cli)
self.__init_tcp_store()
# Validate config content and apply a few changes
self.__check_config()
self.__change_config()
# Finalize config
OmegaConf.set_readonly(self.__config, True)
OmegaConf.set_struct(self.__config, True)
if misc.is_rank_zero():
print(OmegaConf.to_yaml(self.__config))
@staticmethod
def __read_conf(path, file_type=FileType.YAML):
if file_type is FileType.PICKLE:
with open(path, "rb") as fp:
cfg = pickle.load(fp)
elif file_type is FileType.YAML:
cfg = OmegaConf.load(path)
else:
raise ValueError("[FileType Enum]: Invalid value!")
return cfg
def save(self, path, file_type):
"""Save config file to path"""
with open(path, "wb") as fp:
if file_type is FileType.PICKLE:
pickle.dump(self.__config, fp)
fp.flush()
elif file_type is FileType.YAML:
OmegaConf.save(config=self.__config, f=fp.name)
else:
raise ValueError("[FileType Enum]: Invalid value!")
def __merge_config(self, cfg_for_overwrite):
"""omegaconf merge_config
Notes:
dataset merge 할 때 dictionary끼리 append 되기 때문에 이를 방지함.
"""
self.__config = OmegaConf.merge(self.__config, cfg_for_overwrite)
if "dataset_items" in cfg_for_overwrite:
self.__config.dataset_items = cfg_for_overwrite.dataset_items
if (
"model" in cfg_for_overwrite
and "decoders" in cfg_for_overwrite.model
and "type" in list(cfg_for_overwrite.model.decoders.values())[0]
and "kwargs" in list(cfg_for_overwrite.model.decoders.values())[0]
and "loss_func" in list(cfg_for_overwrite.model.decoders.values())[0]
):
self.__config.model.decoders = cfg_for_overwrite.model.decoders
@staticmethod
def __get_config_from_cli():
"""Get config from cli.
This function can also cover arguments with '--'
"""
cfg_cli = OmegaConf.from_cli()
cli_keys = list(cfg_cli.keys())
for cli_key in cli_keys:
if "--" in cli_key:
cfg_cli[cli_key.replace("--", "")] = cfg_cli[cli_key]
del cfg_cli[cli_key]
return cfg_cli
def __init_tcp_store(self):
ip = self.__config.tcp_store_ip
port = self.__config.tcp_store_port
time_delta = timedelta(seconds=300)
if misc.is_rank_zero():
self.__tcp_store_server = dist.TCPStore(ip, port, -1, True, time_delta)
else:
self.__tcp_store_cli = dist.TCPStore(ip, port, -1, False, time_delta)
def __check_config(self):
"""Check config"""
for key in self.SHOULD_NOT_USE_CONFIGS:
if key in self.__config.keys():
raise ValueError(
f"Do not use {key} as a configuration. \n"
"This configuration should be added"
" automatically in runtime."
)
for mode in ["train", "val", "test"]:
num_devices = torch.cuda.device_count() * self.__config.train.num_nodes
if self.__config[mode].batch_size % num_devices != 0:
raise ValueError(
f"{mode} batch-size should be a multiple"
" of the number of gpu devices"
)
# check decoder_names
decoder_name_set_from_dataset_items = set()
for dataset_item in self.__config.dataset_items:
for task in dataset_item.tasks:
decoder_name_set_from_dataset_items.add(task.decoder)
decoder_name_set_from_decoders = set()
for decoder_name, decoder_cfg in self.__config.model.decoders.items():
decoder_name_set_from_decoders.add(decoder_name)
assert decoder_name.startswith(decoder_cfg.type)
if decoder_name_set_from_dataset_items != decoder_name_set_from_decoders:
raise ValueError(
"Please match decoder-names.\n"
f"dec-names from dataset_items: {decoder_name_set_from_dataset_items}\n"
f"dec-names from decoders: {decoder_name_set_from_decoders}"
)
# Check available tasks
for dataset_item in self.__config.dataset_items:
for task in dataset_item.tasks:
decoder_cfg = self.__config.model.decoders[task.decoder]
available_tasks = AVAILABLE_TASKS[decoder_cfg.type]
if task.name not in available_tasks:
raise ValueError(
f"Unavailable task {task.name} for decoder {task.decoder}"
)
if decoder_cfg.type == DecoderTypes.TRANSFORMER:
assert not (
(decoder_cfg.head_type == HeadTypes.TWO_HEAD)
^ task.name.endswith(HeadTypes.TWO_HEAD)
), "Two head model should solve two head task."
# Check image_normalize type in PATCH_CLS with grayscale label
if (
hasattr(decoder_cfg, "task")
and decoder_cfg.task == Tasks.PATCH_CLS
and decoder_cfg.kwargs.classification_type == "grayscale"
):
transforms_dict = task.transforms_dict
if isinstance(transforms_dict, str):
if transforms_dict not in self.__config.custom_transforms_dict:
raise ValueError(
f"{transforms_dict} is not in cfg.custom_transforms_dict"
)
transforms_dict = self.__config.custom_transforms_dict[
transforms_dict
]
assert transforms_dict["image_normalize"] == "imagenet_default"
def __change_config(self):
"""Change config like path"""
cfg = self.__config # get reference of __config
# -------------------------------------------
# for convinience (only used for evaluate.py)
if cfg.eval.dataset_name is not None and cfg.eval.task_name is not None:
cfg.dataset_items = [get_eval_dataset_item(cfg.eval)]
# -------------------------------------------
workspace = cfg.workspace_name
if workspace is None:
workspace = os.getcwd()
cfg.workspace = workspace
self.__change_data_paths()
cfg.model.resume_model_path = self.__change_weight_path(
workspace, cfg.model.resume_model_path
)
self.__change_log_dirs()
num_devices = torch.cuda.device_count() * cfg.train.num_nodes
for mode in ["train", "val", "test"]:
# set per-gpu num_workers
if cfg.debug:
cfg[mode].num_workers = 0
else:
num_workers = cfg[mode].num_workers
if num_workers == -1:
num_workers = cpu_count() * cfg.train.num_nodes
cfg[mode].num_workers = max(num_workers // num_devices, 1)
# set per-gpu batch size
new_batch_size = cfg[mode].batch_size // num_devices
cfg[mode].batch_size = new_batch_size
if mode == "train" and is_otor(cfg.dataset_items[0].tasks[0].name):
if cfg[mode].batch_size % 2 > 0:
assert (
cfg[mode].batch_size % 2 == 0
), "when use otor, batch size should be even number."
cfg[mode].batch_size = cfg[mode].batch_size // 2
if cfg.reproduce.seed == -1:
# To avoid each rank have different random_seed, we use TCPStore.
if misc.is_rank_zero():
random_seed = int(time.time()) % 10000
self.__tcp_store_server.set("random_seed", str(random_seed))
else:
random_seed = int(self.__tcp_store_cli.get("random_seed").decode())
cfg.reproduce.seed = random_seed
# Make DTD (Dataset-name, Task-name, Decoder-name) configs
dtd_dict = {}
for dataset_item in cfg.dataset_items:
dataset_name = dataset_item.name
for task in dataset_item.tasks:
| dtd_key_str = Seperators.DTD.join(
| 4 | 2023-11-15 00:40:08+00:00 | 4k |
speckai/speck | src/python/speck/chat/entities.py | [
{
"identifier": "ChatLogger",
"path": "src/python/speck/chat/logger.py",
"snippet": "class ChatLogger:\n @staticmethod\n def log(log_config: \"LogConfig\", prompt: Any, model: str, response: Any, **kwargs):\n if kwargs.get(\"config\", {}).get(\"_log\", True):\n universal_format_l... | from abc import ABC, abstractmethod
from typing import Any, Callable, Iterator, Literal, Optional, Tuple, Union
from openai._types import NotGiven
from pydantic import BaseModel, Extra
from ..chat.logger import ChatLogger
from ..debug._debug_socket import run_debug_websocket | 2,229 | "stream": self.stream,
"_log": self._log,
"temperature": self._convert_optional(self.temperature),
"max_tokens": self._convert_optional(self.max_tokens),
"top_p": self._convert_optional(self.top_p),
"frequency_penalty": self._convert_optional(self.frequency_penalty),
"presence_penalty": self._convert_optional(self.presence_penalty),
"chat_args": self.chat_args,
}
def _convert_optional(self, value):
return None if isinstance(value, NotGiven) else value
@classmethod
def create(cls, config: ChatConfigTypes, kwargs: dict = None) -> "ChatConfig":
if isinstance(config, cls):
if kwargs is not None:
return cls(**{**config.__dict__, **kwargs})
else:
return config
elif isinstance(config, dict):
return cls(**config)
elif kwargs:
return cls(**kwargs)
else:
raise NotImplementedError
def get(self, key: str, default: Any = None) -> Any:
return getattr(self, key, default)
def convert(self, provider: str = "speck") -> "ChatConfig":
"""
Convert to another config format
"""
if provider == "openai":
return OpenAIChatConfig(
model=self.model,
stream=self.stream,
_log=self._log,
temperature=self.temperature,
max_tokens=self.max_tokens,
top_p=self.top_p,
frequency_penalty=self.frequency_penalty,
presence_penalty=self.presence_penalty,
**self._kwargs,
)
return self
def log_chat(
self,
*,
log_config: LogConfig,
prompt: Prompt,
response: Response,
provider: str = "speck",
):
config = self.convert()
ChatLogger.log(
log_config=log_config,
provider=provider,
model=str(config.model),
prompt=prompt,
response=response,
**config.chat_args,
)
def encode(self, encoding: str = "utf-8"):
return self.__str__().encode(encoding)
def __str__(self):
return f"ChatConfig(provider={self.provider}, model={self.model}, stream={self.stream}, _log={self._log}, temperature={self.temperature}, max_tokens={self.max_tokens}, top_p={self.top_p}, frequency_penalty={self.frequency_penalty}, presence_penalty={self.presence_penalty}, _kwargs={self._kwargs})"
class OpenAIChatConfig(ChatConfig):
def __init__(
self,
model: OpenAIModel,
stream: bool = False,
_log: bool = True,
temperature: Union[Optional[float], NotGiven] = NOT_GIVEN,
max_tokens: Union[Optional[int], NotGiven] = NOT_GIVEN,
top_p: Union[Optional[float], NotGiven] = NOT_GIVEN,
frequency_penalty: Union[Optional[float], NotGiven] = NOT_GIVEN,
presence_penalty: Union[Optional[float], NotGiven] = NOT_GIVEN,
**config_kwargs,
):
self.model = model
self.stream = stream
self._log = _log
self.temperature = temperature
self.max_tokens = max_tokens
self.top_p = top_p
self.frequency_penalty = frequency_penalty
self.presence_penalty = presence_penalty
self._kwargs = config_kwargs
def convert(self, provider: str = "speck") -> ChatConfig:
"""
Maps config to universal format then converts to another config format
"""
universal_config = ChatConfig(
model=self.model,
stream=self.stream,
_log=self._log,
temperature=self.temperature,
max_tokens=self.max_tokens,
top_p=self.top_p,
frequency_penalty=self.frequency_penalty,
presence_penalty=self.presence_penalty,
**self._kwargs,
)
return universal_config.convert(provider=provider)
class IChatClient(ABC):
def debug_chat(
self, prompt: "Prompt", config: "ChatConfig"
) -> ("Prompt", "ChatConfig"):
| from __future__ import annotations
# from dataclasses import dataclass
NOT_GIVEN = None
class Message(BaseModel):
role: MessageRole
content: str
class SafeDict(dict):
def __missing__(self, key):
return "{" + key + "}" # Returns the key in curly braces as a string
class Prompt(str):
messages: list[Message]
variables: Union[dict[str, str], None] = None
def to_dict(self):
return {
"messages": self.messages,
"variables": self.variables,
}
def __init__(
self,
messages: PromptTypes,
variables: Union[dict[str, str], None] = None,
**kwargs,
):
if isinstance(messages, str):
messages = [Message(role="user", content=messages)]
elif isinstance(messages, Message):
messages = [messages]
elif isinstance(messages, list):
if all(isinstance(message, Message) for message in messages):
pass
elif all(isinstance(message, dict) for message in messages):
messages = [
Message(role=message["role"], content=message["content"])
for message in messages
]
else:
raise ValueError(
f"Invalid type for messages: {type(messages)}\n{messages}"
)
self.messages = messages
self.variables = variables
super().__init__()
@classmethod
def create(
cls, messages: PromptTypes, variables: dict[str, str] = None
) -> "Prompt":
if isinstance(messages, cls):
# Todo: clone object and add variables
return messages
return cls(messages=messages, variables=variables)
@classmethod
def _read(cls, lines: str) -> "Prompt":
# Todo: add config parsing
config = {}
messages = []
current_min_spaces = 0
current_section = None
current_message = []
def add_message():
nonlocal current_message, current_min_spaces
if current_message:
messages.append(
Message(
role=current_section,
content="\n".join(
[m[current_min_spaces:] for m in current_message]
),
)
)
current_message = []
current_min_spaces = 0
for line in lines.split("\n"):
line = line.rstrip("\r")
if line.startswith("<"):
line = line.strip()
add_message()
current_section = line[1:-1].lower()
elif current_section == "config" and "=" in line:
key, value = line.split("=", 1)
config[key.strip()] = value.strip()
elif current_section in ["system", "user", "assistant"]:
min_spaces = len(line) - len(line.lstrip())
if 0 < min_spaces < current_min_spaces or current_min_spaces == 0:
current_min_spaces = min_spaces
current_message.append(line)
add_message()
return cls(messages=messages)
@classmethod
def read(cls, path: str, name: Union[str, None] = None) -> "Prompt":
with open(path, "r") as f:
if name is not None:
prompts = cls.read_all(path)
return prompts[name]
else:
return cls._read(f.read())
@classmethod
def read_all(cls, path: str) -> dict[str, "Prompt"]:
with open(path, "r") as f:
prompts = {}
lines = []
current_prompt_name = None
current_min_spaces = -1
for line in f:
line = line.rstrip("\n").rstrip("\r")
if line.lstrip().startswith("<"):
min_spaces = len(line) - len(line.lstrip())
stripped_line = line.strip()
if stripped_line.startswith("<prompt") and min_spaces == 0:
if current_prompt_name:
prompts[current_prompt_name] = cls._read(
"\n".join([m[current_min_spaces:] for m in lines])
)
current_prompt_name = stripped_line[8:-1].strip()
current_min_spaces = -1
lines = []
elif stripped_line.startswith("</prompt>") and min_spaces == 0:
prompts[current_prompt_name] = cls._read(
"\n".join([m[current_min_spaces:] for m in lines])
)
current_prompt_name = None
current_min_spaces = -1
lines = []
else:
lines.append(line)
if current_min_spaces == -1 or min_spaces < current_min_spaces:
current_min_spaces = min_spaces
else:
lines.append(line)
return prompts
def _file(self):
file = []
for message in self.messages:
file.append(f"<{message.role.lower()}>")
for line in message.content.split("\n"):
file.append(" " * 4 + line)
return "\n".join(file)
@classmethod
def write(cls, prompt: Union["Prompt", dict[str, "Prompt"]], path: str):
with open(path, "w") as f:
if isinstance(prompt, dict):
content = ""
for name, prompt in prompt.items():
content += f"<prompt {name}>\n"
content += "\n".join(
[" " * 4 + line for line in prompt._file().split("\n")]
)
content += "\n</prompt>\n\n"
f.write(content.strip())
else:
f.write(prompt._file())
def __new__(
cls,
messages: PromptTypes,
**kwargs,
):
# Todo: Handle string, Message, and list[Message]
instance = super(Prompt, cls).__new__(cls, str(messages))
return instance
@classmethod
def from_openai(cls, messages: list[dict[str, str]]):
return cls(
messages=[
Message(role=message["role"], content=message["content"])
for message in messages
]
)
def to_list(self):
return [
{
"role": message.role,
"content": message.content.format_map(SafeDict(self.variables or {})),
}
for message in self.messages
]
def to_dict(self):
return {
"messages": [
{"role": message.role, "content": message.content}
for message in self.messages
],
"variables": self.variables or {},
}
@staticmethod
def _apply_variables(
messages: list[Message], variables: dict[str, str]
) -> list[Message]:
return [
Message(
role=message.role,
content=message.content.format_map(SafeDict(variables or {})),
)
for message in messages
]
def _check_duplicate_keys(self, other_variables: dict[str, str]) -> dict[str, str]:
duplicate_keys = set((self.variables or {}).keys()).intersection(
set((other_variables or {}).keys())
)
return {
key: self.variables[key]
for key in duplicate_keys
if self.variables[key] != other_variables[key]
}
def _remove_duplicate_keys_from_messages(
self, other_variables: dict[str, str]
) -> list[Message]:
messages = self.messages
applied_variables = self._check_duplicate_keys(other_variables)
if len(applied_variables) > 0:
messages = self._apply_variables(self.messages, applied_variables)
return messages
def format(self, *args, **kwargs):
# return self.__class__(
# messages=[
# Message(
# role=message.role, content=message.content.format(*args, **kwargs)
# )
# for message in self.messages
# ]
# )
messages = self._remove_duplicate_keys_from_messages(kwargs)
return self.__class__(
messages=[
Message(role=message.role, content=message.content)
for message in messages
],
variables={**SafeDict(self.variables or {}), **kwargs},
)
def __add__(self, other):
if isinstance(other, Message):
return self.__class__(
messages=self.messages + [other], variables={**(self.variables or {})}
)
elif isinstance(other, Prompt):
# Check if there are duplicate keys
messages = self._remove_duplicate_keys_from_messages(other.variables or {})
return self.__class__(
messages=messages + other.messages,
variables={
**SafeDict(self.variables or {}),
**SafeDict(other.variables or {}),
},
)
else:
raise NotImplementedError
def __str__(self):
return (
"\n".join(
[f"{message.role}: {message.content}" for message in self.messages]
)
+ "\n"
+ str(self.variables or {})
)
class Response(BaseModel):
content: str
prompt_tokens: Union[int, None] = None
completion_tokens: Union[int, None] = None
raw: Union[dict, None] = None
def __init__(
self,
content: str,
closed: bool = False,
prompt_tokens: Union[int, None] = None,
completion_tokens: Union[int, None] = None,
raw: Union[dict, None] = None,
**kwargs,
):
super().__init__(
content=content,
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
raw=raw,
)
for key, value in kwargs.items():
setattr(self, key, value)
@classmethod
def create(cls, response: ResponseTypes) -> "Response":
if isinstance(response, cls):
return response
elif isinstance(response, str):
return cls(content=response)
else:
raise NotImplementedError
def __str__(self):
return f"Response({self.content}, raw={self.raw})"
class MessageChunk(BaseModel):
content: Union[str, None]
def encode(self, encoding: str = "utf-8"):
content = self.content or ""
return content.encode(encoding)
class Stream:
# processor that has lambda which returns MessageDelta
def __init__(
self,
client: "Speck",
iterator: Iterator[Any],
kwargs: dict,
log_config: "LogConfig",
processor: Callable[[Any], MessageChunk],
):
self._client = client
self.message: str = ""
self.tokens: int = 0
self._iterator = iterator
self._kwargs = kwargs
self._processor = processor
self._has_logged = False
self._closed = False
self._log_config = log_config
def _log(self):
if not self._has_logged:
self._has_logged = True
kwargs = self._kwargs
kwargs["prompt"] = self._kwargs.get("prompt", [])
kwargs["temperature"] = self._kwargs.get("temperature", "N/A")
kwargs["model"] = self._kwargs.get("model", "N/A")
kwargs["response"] = Response(
content=self.message, raw={}, closed=True, completion_tokens=self.tokens
)
# Todo: add prompt_tokens using tiktoken
ChatLogger.log(log_config=self._log_config, **kwargs)
def _process(self, item) -> MessageChunk:
return self._processor(item)
def __next__(self) -> MessageChunk:
try:
if self._closed:
raise StopIteration
# next_item = None
# while next_item is None:
next_item = next(self._iterator)
item: MessageChunk = self._process(next_item)
if item.content:
self.message += item.content
self.tokens += 1
return item
except StopIteration:
self._log()
raise
def __iter__(self) -> Iterator[MessageChunk]:
return self
def close(self):
try:
self._closed = True
# todo: make this work for packages other than openai
self._iterator.response.close()
except AttributeError:
pass
class LogConfig(BaseModel):
api_key: str
endpoint: str = "https://api.getspeck.ai"
class Config:
extra = "allow"
class ChatConfig:
# Todo: add typed params here
# Todo: Create conversions to other formats
def __init__(
self,
*,
provider: str = None,
model: OpenAIModel,
stream: bool = False,
_log: bool = True,
temperature: Union[Optional[float], NotGiven] = NOT_GIVEN,
max_tokens: Union[Optional[int], NotGiven] = NOT_GIVEN,
top_p: Union[Optional[float], NotGiven] = NOT_GIVEN,
frequency_penalty: Union[Optional[float], NotGiven] = NOT_GIVEN,
presence_penalty: Union[Optional[float], NotGiven] = NOT_GIVEN,
**config_kwargs,
):
if "log_config" in config_kwargs:
del config_kwargs["log_config"]
self.provider = provider
self.model = model
self.stream = stream
self._log = _log
self.temperature = temperature
self.max_tokens = max_tokens
self.top_p = top_p
self.frequency_penalty = frequency_penalty
self.presence_penalty = presence_penalty
self.chat_args = config_kwargs
# If this is modified, update to_dict too
def to_dict(self):
return {
"provider": self.provider,
"model": str(self.model), # Assuming model can be represented as a string
"stream": self.stream,
"_log": self._log,
"temperature": self._convert_optional(self.temperature),
"max_tokens": self._convert_optional(self.max_tokens),
"top_p": self._convert_optional(self.top_p),
"frequency_penalty": self._convert_optional(self.frequency_penalty),
"presence_penalty": self._convert_optional(self.presence_penalty),
"chat_args": self.chat_args,
}
def _convert_optional(self, value):
return None if isinstance(value, NotGiven) else value
@classmethod
def create(cls, config: ChatConfigTypes, kwargs: dict = None) -> "ChatConfig":
if isinstance(config, cls):
if kwargs is not None:
return cls(**{**config.__dict__, **kwargs})
else:
return config
elif isinstance(config, dict):
return cls(**config)
elif kwargs:
return cls(**kwargs)
else:
raise NotImplementedError
def get(self, key: str, default: Any = None) -> Any:
return getattr(self, key, default)
def convert(self, provider: str = "speck") -> "ChatConfig":
"""
Convert to another config format
"""
if provider == "openai":
return OpenAIChatConfig(
model=self.model,
stream=self.stream,
_log=self._log,
temperature=self.temperature,
max_tokens=self.max_tokens,
top_p=self.top_p,
frequency_penalty=self.frequency_penalty,
presence_penalty=self.presence_penalty,
**self._kwargs,
)
return self
def log_chat(
self,
*,
log_config: LogConfig,
prompt: Prompt,
response: Response,
provider: str = "speck",
):
config = self.convert()
ChatLogger.log(
log_config=log_config,
provider=provider,
model=str(config.model),
prompt=prompt,
response=response,
**config.chat_args,
)
def encode(self, encoding: str = "utf-8"):
return self.__str__().encode(encoding)
def __str__(self):
return f"ChatConfig(provider={self.provider}, model={self.model}, stream={self.stream}, _log={self._log}, temperature={self.temperature}, max_tokens={self.max_tokens}, top_p={self.top_p}, frequency_penalty={self.frequency_penalty}, presence_penalty={self.presence_penalty}, _kwargs={self._kwargs})"
class OpenAIChatConfig(ChatConfig):
def __init__(
self,
model: OpenAIModel,
stream: bool = False,
_log: bool = True,
temperature: Union[Optional[float], NotGiven] = NOT_GIVEN,
max_tokens: Union[Optional[int], NotGiven] = NOT_GIVEN,
top_p: Union[Optional[float], NotGiven] = NOT_GIVEN,
frequency_penalty: Union[Optional[float], NotGiven] = NOT_GIVEN,
presence_penalty: Union[Optional[float], NotGiven] = NOT_GIVEN,
**config_kwargs,
):
self.model = model
self.stream = stream
self._log = _log
self.temperature = temperature
self.max_tokens = max_tokens
self.top_p = top_p
self.frequency_penalty = frequency_penalty
self.presence_penalty = presence_penalty
self._kwargs = config_kwargs
def convert(self, provider: str = "speck") -> ChatConfig:
"""
Maps config to universal format then converts to another config format
"""
universal_config = ChatConfig(
model=self.model,
stream=self.stream,
_log=self._log,
temperature=self.temperature,
max_tokens=self.max_tokens,
top_p=self.top_p,
frequency_penalty=self.frequency_penalty,
presence_penalty=self.presence_penalty,
**self._kwargs,
)
return universal_config.convert(provider=provider)
class IChatClient(ABC):
def debug_chat(
self, prompt: "Prompt", config: "ChatConfig"
) -> ("Prompt", "ChatConfig"): | data = run_debug_websocket(self._client, self, prompt, config) | 1 | 2023-11-15 05:46:05+00:00 | 4k |
hahnyuan/ASVD4LLM | binary_search.py | [
{
"identifier": "evaluate_model",
"path": "evaluate.py",
"snippet": "@torch.no_grad()\ndef evaluate_model(\n model,\n tokenizer,\n model_name,\n tasks,\n eval_ppl=\"\",\n num_fewshot=0,\n limit=-1,\n batch_size=1,\n):\n \"\"\"\n model: model name\n limit: number of test ... | import os
import torch
import torch.nn as nn
from evaluate import evaluate_model, evaluate_perplexity
from modules.svd_linear import SVDLinear
from tqdm import tqdm | 3,314 |
def binary_search_truncation_rank(model, sensitivity_dict, calib_loader, args):
module_dict = {name: module for name, module in model.named_modules()}
full_name_dict = {module: name for name, module in model.named_modules()}
linear_info = {}
modules = [model]
while len(modules) > 0:
submodule = modules.pop()
for name, raw_linear in submodule.named_children():
if isinstance(raw_linear, nn.Linear):
full_name = full_name_dict[raw_linear]
linear_info[raw_linear] = {
"father": submodule,
"name": name,
"full_name": full_name,
}
else:
modules.append(raw_linear)
sensitivity_list = []
for layername, v in sensitivity_dict.items():
for ratio, ppl in v.items():
sensitivity_list.append((layername, ratio, ppl))
sorted_sensitive_list = sorted(sensitivity_list, key=lambda x: -x[2])
# binary search
high = len(sorted_sensitive_list) - 1
low = 0
assert args.ppl_target > 0 or args.param_ratio_target > 0
input_ids = torch.cat([_["input_ids"] for _ in calib_loader], 0)
while low < high:
mid = (low + high) // 2
layers_min_ratio = {layername: 1 for layername in sensitivity_dict.keys()}
for layername, ratio, ppl in sorted_sensitive_list[mid:]:
layers_min_ratio[layername] = min(layers_min_ratio[layername], ratio)
tot_params = 0
compress_params = 0
if args.ppl_target > 0:
for layername, ratio in layers_min_ratio.items():
raw_linear = module_dict[layername]
info = linear_info[raw_linear]
svd_linear = SVDLinear.from_linear(
raw_linear,
param_ratio=ratio,
alpha=args.alpha,
act_aware=args.act_aware,
sigma_fuse=args.sigma_fuse,
)
setattr(info["father"], info["name"], svd_linear)
tot_params += raw_linear.weight.numel()
compress_params += raw_linear.weight.numel() * ratio
|
def binary_search_truncation_rank(model, sensitivity_dict, calib_loader, args):
module_dict = {name: module for name, module in model.named_modules()}
full_name_dict = {module: name for name, module in model.named_modules()}
linear_info = {}
modules = [model]
while len(modules) > 0:
submodule = modules.pop()
for name, raw_linear in submodule.named_children():
if isinstance(raw_linear, nn.Linear):
full_name = full_name_dict[raw_linear]
linear_info[raw_linear] = {
"father": submodule,
"name": name,
"full_name": full_name,
}
else:
modules.append(raw_linear)
sensitivity_list = []
for layername, v in sensitivity_dict.items():
for ratio, ppl in v.items():
sensitivity_list.append((layername, ratio, ppl))
sorted_sensitive_list = sorted(sensitivity_list, key=lambda x: -x[2])
# binary search
high = len(sorted_sensitive_list) - 1
low = 0
assert args.ppl_target > 0 or args.param_ratio_target > 0
input_ids = torch.cat([_["input_ids"] for _ in calib_loader], 0)
while low < high:
mid = (low + high) // 2
layers_min_ratio = {layername: 1 for layername in sensitivity_dict.keys()}
for layername, ratio, ppl in sorted_sensitive_list[mid:]:
layers_min_ratio[layername] = min(layers_min_ratio[layername], ratio)
tot_params = 0
compress_params = 0
if args.ppl_target > 0:
for layername, ratio in layers_min_ratio.items():
raw_linear = module_dict[layername]
info = linear_info[raw_linear]
svd_linear = SVDLinear.from_linear(
raw_linear,
param_ratio=ratio,
alpha=args.alpha,
act_aware=args.act_aware,
sigma_fuse=args.sigma_fuse,
)
setattr(info["father"], info["name"], svd_linear)
tot_params += raw_linear.weight.numel()
compress_params += raw_linear.weight.numel() * ratio | ppl = evaluate_perplexity(model, input_ids, args.n_calib_samples) | 1 | 2023-11-10 02:18:36+00:00 | 4k |
chaiNNer-org/spandrel | src/spandrel/__helpers/loader.py | [
{
"identifier": "canonicalize_state_dict",
"path": "src/spandrel/__helpers/canonicalize.py",
"snippet": "def canonicalize_state_dict(state_dict: StateDict) -> StateDict:\n \"\"\"\n Canonicalize a state dict.\n\n This function is used to canonicalize a state dict, so that it can be\n used for... | import os
import torch
from pathlib import Path
from safetensors.torch import load_file
from .canonicalize import canonicalize_state_dict
from .main_registry import MAIN_REGISTRY
from .model_descriptor import ModelDescriptor, StateDict
from .registry import ArchRegistry
from .unpickler import RestrictedUnpickle | 2,515 | from __future__ import annotations
class ModelLoader:
"""Class for automatically loading a pth file into any architecture"""
def __init__(
self,
device: str | torch.device | None = None,
registry: ArchRegistry = MAIN_REGISTRY,
):
if isinstance(device, str):
device = torch.device(device)
self.device: torch.device = device or torch.device("cpu")
self.registry: ArchRegistry = registry
"""
The architecture registry to use for loading models.
*Note:* Unless initialized with a custom registry, this is the global main registry (`MAIN_REGISTRY`).
Modifying this registry will affect all `ModelLoader` instances without a custom registry.
"""
def load_from_file(self, path: str | Path) -> ModelDescriptor:
"""
Load a model from the given file path.
Throws a `ValueError` if the file extension is not supported.
Throws an `UnsupportedModelError` if the model architecture is not supported.
"""
state_dict = self.load_state_dict_from_file(path)
return self.load_from_state_dict(state_dict)
def load_state_dict_from_file(self, path: str | Path) -> StateDict:
"""
Load the state dict of a model from the given file path.
State dicts are typically only useful to pass them into the `load`
function of a specific architecture.
Throws a `ValueError` if the file extension is not supported.
"""
extension = os.path.splitext(path)[1].lower()
state_dict: StateDict
if extension == ".pt":
state_dict = self._load_torchscript(path)
elif extension == ".pth":
state_dict = self._load_pth(path)
elif extension == ".ckpt":
state_dict = self._load_ckpt(path)
elif extension == ".safetensors":
state_dict = self._load_safetensors(path)
else:
raise ValueError(
f"Unsupported model file extension {extension}. Please try a supported model type."
)
return canonicalize_state_dict(state_dict)
def load_from_state_dict(self, state_dict: StateDict) -> ModelDescriptor:
"""
Load a model from the given state dict.
Throws an `UnsupportedModelError` if the model architecture is not supported.
"""
return self.registry.load(state_dict).to(self.device)
def _load_pth(self, path: str | Path) -> StateDict:
return torch.load(
path,
map_location=self.device,
| from __future__ import annotations
class ModelLoader:
"""Class for automatically loading a pth file into any architecture"""
def __init__(
self,
device: str | torch.device | None = None,
registry: ArchRegistry = MAIN_REGISTRY,
):
if isinstance(device, str):
device = torch.device(device)
self.device: torch.device = device or torch.device("cpu")
self.registry: ArchRegistry = registry
"""
The architecture registry to use for loading models.
*Note:* Unless initialized with a custom registry, this is the global main registry (`MAIN_REGISTRY`).
Modifying this registry will affect all `ModelLoader` instances without a custom registry.
"""
def load_from_file(self, path: str | Path) -> ModelDescriptor:
"""
Load a model from the given file path.
Throws a `ValueError` if the file extension is not supported.
Throws an `UnsupportedModelError` if the model architecture is not supported.
"""
state_dict = self.load_state_dict_from_file(path)
return self.load_from_state_dict(state_dict)
def load_state_dict_from_file(self, path: str | Path) -> StateDict:
"""
Load the state dict of a model from the given file path.
State dicts are typically only useful to pass them into the `load`
function of a specific architecture.
Throws a `ValueError` if the file extension is not supported.
"""
extension = os.path.splitext(path)[1].lower()
state_dict: StateDict
if extension == ".pt":
state_dict = self._load_torchscript(path)
elif extension == ".pth":
state_dict = self._load_pth(path)
elif extension == ".ckpt":
state_dict = self._load_ckpt(path)
elif extension == ".safetensors":
state_dict = self._load_safetensors(path)
else:
raise ValueError(
f"Unsupported model file extension {extension}. Please try a supported model type."
)
return canonicalize_state_dict(state_dict)
def load_from_state_dict(self, state_dict: StateDict) -> ModelDescriptor:
"""
Load a model from the given state dict.
Throws an `UnsupportedModelError` if the model architecture is not supported.
"""
return self.registry.load(state_dict).to(self.device)
def _load_pth(self, path: str | Path) -> StateDict:
return torch.load(
path,
map_location=self.device, | pickle_module=RestrictedUnpickle, # type: ignore | 4 | 2023-11-17 01:11:47+00:00 | 4k |
ottoweiss/pdf-to-audiobook | main.py | [
{
"identifier": "get_audiobook",
"path": "src/audiobook.py",
"snippet": "def get_audiobook(json_file, book_title=\"audiobook\", voice=\"onyx\", speed=\"1.0\"):\n book_directory = f\"{book_title}\"\n atexit.register(save_full, book_title)\n\n if not os.path.exists(book_directory):\n os.ma... | from src.audiobook import get_audiobook
from src.clean_pdf import get_rewrite
from src.pdf_to_json import extract_text_from_pdf
from colorama import Fore, Style
import os
import time | 1,712 |
def input_q(text):
print(Fore.YELLOW + text, end="")
inp = input()
print(Style.RESET_ALL, end="")
if inp == ":q":
exit()
return inp
def print_info(message):
print(Fore.CYAN + message + Style.RESET_ALL)
def print_error(message):
print(Fore.RED + "ERROR: " + message + Style.RESET_ALL)
def print_success(message):
print(Fore.GREEN + message + Style.RESET_ALL)
if __name__ == "__main__":
print_info("Enter :q to quit at any time.\n")
print_info("Before Continuing, ensure your Openai API key is in the config.py file.\n")
file_included = False
while not file_included:
pdf_file_q = input_q("Have you added the pdf file to this folder? (y/[n]): ")
if pdf_file_q.lower() == "y":
correct_pdf_file_name = False
while not correct_pdf_file_name:
pdf_file_name = input_q("Enter pdf file name: ")
if os.path.exists(pdf_file_name):
correct_pdf_file_name = True
else:
print_error("File not in folder. Please try again.")
file_included = True
else:
print_info("\nDownload File Here then Add to Folder: https://singlelogin.re/\n")
time.sleep(3)
correct_page_range = False
while not correct_page_range:
try:
page_start = int(input_q("What page should the audiobook start?: ").strip())
page_end = int(input_q("What page should the audiobook end?: ").strip())
title = input_q("Enter Your Book Title: ").strip()
|
def input_q(text):
print(Fore.YELLOW + text, end="")
inp = input()
print(Style.RESET_ALL, end="")
if inp == ":q":
exit()
return inp
def print_info(message):
print(Fore.CYAN + message + Style.RESET_ALL)
def print_error(message):
print(Fore.RED + "ERROR: " + message + Style.RESET_ALL)
def print_success(message):
print(Fore.GREEN + message + Style.RESET_ALL)
if __name__ == "__main__":
print_info("Enter :q to quit at any time.\n")
print_info("Before Continuing, ensure your Openai API key is in the config.py file.\n")
file_included = False
while not file_included:
pdf_file_q = input_q("Have you added the pdf file to this folder? (y/[n]): ")
if pdf_file_q.lower() == "y":
correct_pdf_file_name = False
while not correct_pdf_file_name:
pdf_file_name = input_q("Enter pdf file name: ")
if os.path.exists(pdf_file_name):
correct_pdf_file_name = True
else:
print_error("File not in folder. Please try again.")
file_included = True
else:
print_info("\nDownload File Here then Add to Folder: https://singlelogin.re/\n")
time.sleep(3)
correct_page_range = False
while not correct_page_range:
try:
page_start = int(input_q("What page should the audiobook start?: ").strip())
page_end = int(input_q("What page should the audiobook end?: ").strip())
title = input_q("Enter Your Book Title: ").strip() | cost, e_time = extract_text_from_pdf(pdf_file_name, {title: (page_start, page_end)}) | 2 | 2023-11-16 20:37:24+00:00 | 4k |
GoldenThrust/Virtual-Bank | api/transactions/views.py | [
{
"identifier": "Transaction",
"path": "api/transactions/models.py",
"snippet": "class Transaction(models.Model):\n TRANSACTION_TYPES = [\n ('DEPOSIT', 'Deposit'),\n ('TRANSFER', 'Transfer'),\n ('DEBIT_CARD', 'Debit Card'),\n ('PAYMENT', 'Payment'),\n ]\n\n account =... | from rest_framework import generics
from datetime import datetime
from notifications.utils import process_notifications
from django.utils.timezone import localtime
from debit_cards.utils import luhn_checksum
from .models import Transaction
from accounts.models import Account
from deposits.models import Deposit
from transfers.models import Transfer
from .serializers import (
TransactionSerializer,
TransferTransactionSerializer,
DebitCardPaymentSerializer,
TransactionHistorySerializer,
)
from debit_cards.models import DebitCardTransaction, DebitCard
from rest_framework import permissions, status
from rest_framework.response import Response
from rest_framework import exceptions | 3,237 | expiry_date = serializer.validated_data.pop("expiry_date")
transaction_amount = serializer.validated_data.get("amount")
# Validation of expiry date
try:
month, year = expiry_date.split("/")
month = int(month)
year = int(year)
current_year = int(str(datetime.utcnow().year)[2:])
current_month = datetime.utcnow().month
if not (1 <= month <= 12):
raise DateError("Invalid month")
elif year < current_year or (
year == current_year and month < current_month
):
raise DateError("Card has expired")
elif not (year <= 99):
raise DateError("Invalid year")
except DateError as e:
raise exceptions.PermissionDenied(str(e))
except ValueError:
raise exceptions.PermissionDenied("Invalid expiry date")
# validate card number using luhn algorithm
if luhn_checksum(card_number) != 0:
raise exceptions.PermissionDenied("Invalid card number")
card = DebitCard.objects.filter(
card_number=card_number,
cvv=cvv,
expiration_date__year=f"20{year}",
expiration_date__month=month,
).first()
if not card:
print(card)
raise exceptions.PermissionDenied("Invalid card")
if int(account_number) == int(card.account.number):
#notification
notification_message = "The debit card transaction could not be completed."
process_notifications(
self.request.user, "transaction_notification", notification_message
)
raise exceptions.PermissionDenied(
"Sender and transaction partner accounts cannot be the same"
)
self.transaction_partner_account_number = card.account.number
if card.account.balance >= transaction_amount:
transaction_partner_account_name = f'{card.account.user.first_name} {card.acount.user.last_name}'
serializer.save(transaction_type="DEBIT_CARD", account=account)
# Update Account Balances
card.account.balance -= transaction_amount
account.balance += transaction_amount
card.account.save()
account.save()
# Create Transfer
transfer = DebitCardTransaction.objects.create(
transaction=serializer.instance,
transaction_partner_account=card.account,
)
# notification
notification_message = f"You've successfully initiated a debit card transaction. {transaction_amount} was debited from your account and sent to {user_name}'s account."
process_notifications(
card.account.user, "transaction_notification", notification_message
)
# notification
notification_message = f"You've received {transaction_amount} from {transaction_partner_account_name} through a debit card transaction."
process_notifications(
self.request.user, "transaction_notification", notification_message
)
else:
# notification
notification_message = f"The debit card transaction from {user_name} could not be completed due to insufficient funds in their account."
process_notifications(
self.request.user, "transaction_notification", notification_message
)
# notification
notification_message = "Your debit card transaction couldn't be completed due to insufficient funds."
process_notifications(
card.account.user, "transaction_notification", notification_message
)
raise exceptions.PermissionDenied("Insufficient funds")
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
serialized_data = serializer.data
user = Account.objects.get(number=self.transaction_partner_account_number).user
serialized_data[
"transaction_partner_name"
] = f"{user.first_name} {user.last_name}"
serialized_data["transaction_partner_account_number"] = int(
self.transaction_partner_account_number
)
headers = self.get_success_headers(serializer.data)
return Response(
serialized_data, status=status.HTTP_201_CREATED, headers=headers
)
class TransactionHistory(generics.ListAPIView):
queryset = Transaction.objects.all()
|
# Models and Serializers
# from payments.models import Payment
class DateError(Exception):
pass
class TransactionList(generics.ListCreateAPIView):
queryset = Transaction.objects.all()
serializer_class = TransactionSerializer
permission_classes = [permissions.IsAdminUser]
class TransactionDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Transaction.objects.all()
serializer_class = TransactionSerializer
permission_classes = [permissions.IsAdminUser]
class TransactionDepositCreate(generics.CreateAPIView):
queryset = Transaction.objects.all()
serializer_class = TransactionSerializer
permission_classes = [permissions.IsAuthenticated]
def perform_create(self, serializer):
account_number = serializer.validated_data.get("account_number")
account = Account.objects.filter(number=account_number).first()
if not account:
raise exceptions.NotFound("Account not found")
if account.user != self.request.user:
raise exceptions.PermissionDenied("Account does not belong to this user")
serializer.save(transaction_type="DEPOSIT", account=account)
# Update Account Balance
transaction_amount = serializer.validated_data.get("amount")
account.balance += transaction_amount
account.save()
# Create Deposit
deposit = Deposit.objects.create(transaction=serializer.instance)
# notification
notification_message = f"A deposit of {transaction_amount} has been credited to your account ({account_number})."
process_notifications(
self.request.user, "transaction_notification", notification_message
)
class TransactionTransferCreate(generics.CreateAPIView):
queryset = Transaction.objects.all()
serializer_class = TransferTransactionSerializer
permission_classes = [permissions.IsAuthenticated]
transaction_partner_account_number = None
def perform_create(self, serializer):
account_number = serializer.validated_data.get("account_number")
account = Account.objects.filter(number=account_number).first()
user = self.request.user
user_name = f"{user.first_name} {user.last_name}"
if not account:
raise exceptions.NotFound("Account not found")
if account.user != user:
# account.user.is_active = False
# account.user.save()
# notification
notification_message = f"{user_name} attempted a transfer using your account ({account.number}). For security purposes, the action has been flagged."
process_notifications(account.user, "security_notification", notification_message)
raise exceptions.PermissionDenied("Account does not belong to this user")
transaction_amount = serializer.validated_data.get("amount")
self.transaction_partner_account_number = serializer.validated_data.pop(
"transaction_partner_account_number"
)
if int(account_number) == int(self.transaction_partner_account_number):
# notification
notification_message = "The transfer could not be completed."
process_notifications(
self.request.user, "transaction_notification", notification_message
)
raise exceptions.PermissionDenied(
"Sender and transaction partner accounts cannot be identical."
)
transaction_partner_account = Account.objects.filter(
number=self.transaction_partner_account_number
).first()
if not transaction_partner_account:
# notification
notification_message = "The transfer could not be completed due to an invalid transaction partner account number."
process_notifications(
self.request.user, "transaction_notification", notification_message
)
raise exceptions.NotFound("Transaction partner Account not found")
if account.balance >= transaction_amount:
transaction_partner_account_name = f'{transaction_partner_account.user.first_name} {transaction_partner_account.user.last_name}'
serializer.save(transaction_type="TRANSFER", account=account)
# Update Account Balances
account.balance -= transaction_amount
transaction_partner_account.balance += transaction_amount
account.save()
transaction_partner_account.save()
# Create Transfer
transfer = Transfer.objects.create(
transaction=serializer.instance,
transaction_partner_account=transaction_partner_account,
)
# notification
notification_message = f"The transfer of {transaction_amount} to {transaction_partner_account_name}'s account was successful."
process_notifications(
self.request.user, "transaction_notification", notification_message
)
# notification
notification_message = f"{user_name} has sent {transaction_amount} to your account ({transaction_partner_account.number})."
process_notifications(
transaction_partner_account.user, "transaction_notification", notification_message
)
else:
# notification
notification_message = "The transfer could not be completed due to insufficient funds."
process_notifications(
self.request.user, "transaction_notification", notification_message
)
raise exceptions.PermissionDenied("Insufficient funds")
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
serialized_data = serializer.data
user = Account.objects.get(number=self.transaction_partner_account_number).user
serialized_data[
"transaction_partner_name"
] = f"{user.first_name} {user.last_name}"
serialized_data["transaction_partner_account_number"] = int(
self.transaction_partner_account_number
)
headers = self.get_success_headers(serializer.data)
return Response(
serialized_data, status=status.HTTP_201_CREATED, headers=headers
)
class TransactionDebitCardCreate(generics.CreateAPIView):
queryset = Transaction.objects.all()
serializer_class = DebitCardPaymentSerializer
permission_classes = [permissions.IsAuthenticated]
card_owner = None
transaction_partner_account_number = None
def perform_create(self, serializer):
account_number = serializer.validated_data.get("account_number")
account = Account.objects.filter(number=account_number).first()
user = self.request.user
user_name = f"{user.first_name} {user.last_name}"
if not account:
raise exceptions.NotFound("Account not found")
if account.user != self.request.user:
raise exceptions.PermissionDenied("Account does not belong to this user")
transaction_amount = serializer.validated_data.get("amount")
card_number = serializer.validated_data.pop("card_number")
cvv = serializer.validated_data.pop("cvv")
expiry_date = serializer.validated_data.pop("expiry_date")
transaction_amount = serializer.validated_data.get("amount")
# Validation of expiry date
try:
month, year = expiry_date.split("/")
month = int(month)
year = int(year)
current_year = int(str(datetime.utcnow().year)[2:])
current_month = datetime.utcnow().month
if not (1 <= month <= 12):
raise DateError("Invalid month")
elif year < current_year or (
year == current_year and month < current_month
):
raise DateError("Card has expired")
elif not (year <= 99):
raise DateError("Invalid year")
except DateError as e:
raise exceptions.PermissionDenied(str(e))
except ValueError:
raise exceptions.PermissionDenied("Invalid expiry date")
# validate card number using luhn algorithm
if luhn_checksum(card_number) != 0:
raise exceptions.PermissionDenied("Invalid card number")
card = DebitCard.objects.filter(
card_number=card_number,
cvv=cvv,
expiration_date__year=f"20{year}",
expiration_date__month=month,
).first()
if not card:
print(card)
raise exceptions.PermissionDenied("Invalid card")
if int(account_number) == int(card.account.number):
#notification
notification_message = "The debit card transaction could not be completed."
process_notifications(
self.request.user, "transaction_notification", notification_message
)
raise exceptions.PermissionDenied(
"Sender and transaction partner accounts cannot be the same"
)
self.transaction_partner_account_number = card.account.number
if card.account.balance >= transaction_amount:
transaction_partner_account_name = f'{card.account.user.first_name} {card.acount.user.last_name}'
serializer.save(transaction_type="DEBIT_CARD", account=account)
# Update Account Balances
card.account.balance -= transaction_amount
account.balance += transaction_amount
card.account.save()
account.save()
# Create Transfer
transfer = DebitCardTransaction.objects.create(
transaction=serializer.instance,
transaction_partner_account=card.account,
)
# notification
notification_message = f"You've successfully initiated a debit card transaction. {transaction_amount} was debited from your account and sent to {user_name}'s account."
process_notifications(
card.account.user, "transaction_notification", notification_message
)
# notification
notification_message = f"You've received {transaction_amount} from {transaction_partner_account_name} through a debit card transaction."
process_notifications(
self.request.user, "transaction_notification", notification_message
)
else:
# notification
notification_message = f"The debit card transaction from {user_name} could not be completed due to insufficient funds in their account."
process_notifications(
self.request.user, "transaction_notification", notification_message
)
# notification
notification_message = "Your debit card transaction couldn't be completed due to insufficient funds."
process_notifications(
card.account.user, "transaction_notification", notification_message
)
raise exceptions.PermissionDenied("Insufficient funds")
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
serialized_data = serializer.data
user = Account.objects.get(number=self.transaction_partner_account_number).user
serialized_data[
"transaction_partner_name"
] = f"{user.first_name} {user.last_name}"
serialized_data["transaction_partner_account_number"] = int(
self.transaction_partner_account_number
)
headers = self.get_success_headers(serializer.data)
return Response(
serialized_data, status=status.HTTP_201_CREATED, headers=headers
)
class TransactionHistory(generics.ListAPIView):
queryset = Transaction.objects.all() | serializer_class = TransactionHistorySerializer | 4 | 2023-11-10 12:39:38+00:00 | 4k |
Mj23978/OpenServer | openserver/server/chat/completions.py | [
{
"identifier": "logger",
"path": "openserver/core/utils/utils.py",
"snippet": "def trim_string(string, count: int) -> str:\ndef run_with_time(func):"
},
{
"identifier": "extract_json_from_string",
"path": "openserver/core/utils/json.py",
"snippet": "def extract_json_from_string(text: st... | import json
import os
import random
import string
import time
from pathlib import Path
from typing import Any, Dict, List
from flask import Request, jsonify, request
from langchain.schema import BaseMessage
from openserver.core.utils import extract_json_from_string, base_messages_to_default, logger
from openserver.core.config import ChatConfig, PromptConfig
from openserver.core.llm_models.base import LLmInputInterface
from openserver.core.llm_models.llm_model_factory import LLMFactory
from openserver.core.utils.cost import completion_price_calculator
from openserver.server.app import app
from openserver.server.utils import llm_result_to_str, num_tokens_from_string | 3,038 |
class ChatCompletionsRequest:
def __init__(self, request: Request):
try:
self.model: str = request.get_json().get("model", "gpt-3.5-turbo")
self.stream: bool = request.get_json().get("stream", False)
self.api_key: str | None = request.get_json().get("api_key") or (request.authorization.token if request.authorization is not None else None)
self.messages: List[Dict[str, Any]
] = request.get_json().get("messages")
self.functions = request.get_json().get("functions")
self.n_gpu_layers: int = request.get_json().get("n_gpu_layers", 99)
self.temperature: float = request.get_json().get("temperature", 0.4)
self.max_tokens: int = request.get_json().get("max_tokens", 1000)
self.top_p: int = request.get_json().get("top_p", 1)
self.cache: bool = request.get_json().get("cache", False)
self.n_ctx: int = request.get_json().get("n_ctx", 8196)
except Exception as e:
return jsonify({'reason': "request data error", 'error': str(e)}), 500
@app.route("/chat/completions", methods=["POST"])
def chat_completions():
try:
request_data = ChatCompletionsRequest(request)
available_functions = False
if "functions" in request.get_json():
available_functions = True
configs = ChatConfig(with_envs=True)
provider = configs.get_chat_providers(
request_data.model, available_functions)
logger.info(provider)
chat_input = LLmInputInterface(
api_key=request_data.api_key or provider.args.get("api_key_name"),
model=provider.key or provider.name,
model_kwargs={
"chat_format": "mistral",
},
streaming=request_data.stream,
n_gpu_layers=request_data.n_gpu_layers,
temperature=request_data.temperature,
max_tokens=request_data.max_tokens,
top_p=request_data.top_p,
cache=request_data.cache,
n_ctx=request_data.n_ctx,
base_url=provider.args.get("base_url")
)
messages = [BaseMessage(
type=message["role"], content=message["content"]) for message in request_data.messages]
messages = base_messages_to_default(messages)
if available_functions is True:
configs = PromptConfig()
new_messages = configs.extract_text(configs.prompt_template(
), prompt=messages[-1].content, functions=request_data.functions)
messages.pop()
messages = messages + new_messages
ROOT_DIR: str = os.path.dirname(Path(__file__).parent.parent.parent)
chat_input.grammer_path = ROOT_DIR + "/docs/json.gbnf"
chat_input.f16_kv = True
chatProvider = LLMFactory.get_chat_model(
input=chat_input, provider_name=provider.provider)
response = chatProvider.compelete(
prompts=[messages])
response_str = llm_result_to_str(response)
completion_id = "".join(random.choices(
string.ascii_letters + string.digits, k=28))
completion_timestamp = int(time.time())
if not request_data.stream:
inp_token = num_tokens_from_string(
"".join([message.content for message in messages]))
out_token = num_tokens_from_string(response_str)
function_out = None
if available_functions is True:
function_out = extract_json_from_string(response_str)
res = {
"id": f"chatcmpl-{completion_id}",
"object": "chat.completion",
"created": completion_timestamp,
"model": provider.name,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": response_str,
},
"finish_reason": "stop",
}
],
"usage": {
"prompt_tokens": inp_token,
"completion_tokens": out_token,
"total_tokens": inp_token + out_token,
|
class ChatCompletionsRequest:
def __init__(self, request: Request):
try:
self.model: str = request.get_json().get("model", "gpt-3.5-turbo")
self.stream: bool = request.get_json().get("stream", False)
self.api_key: str | None = request.get_json().get("api_key") or (request.authorization.token if request.authorization is not None else None)
self.messages: List[Dict[str, Any]
] = request.get_json().get("messages")
self.functions = request.get_json().get("functions")
self.n_gpu_layers: int = request.get_json().get("n_gpu_layers", 99)
self.temperature: float = request.get_json().get("temperature", 0.4)
self.max_tokens: int = request.get_json().get("max_tokens", 1000)
self.top_p: int = request.get_json().get("top_p", 1)
self.cache: bool = request.get_json().get("cache", False)
self.n_ctx: int = request.get_json().get("n_ctx", 8196)
except Exception as e:
return jsonify({'reason': "request data error", 'error': str(e)}), 500
@app.route("/chat/completions", methods=["POST"])
def chat_completions():
try:
request_data = ChatCompletionsRequest(request)
available_functions = False
if "functions" in request.get_json():
available_functions = True
configs = ChatConfig(with_envs=True)
provider = configs.get_chat_providers(
request_data.model, available_functions)
logger.info(provider)
chat_input = LLmInputInterface(
api_key=request_data.api_key or provider.args.get("api_key_name"),
model=provider.key or provider.name,
model_kwargs={
"chat_format": "mistral",
},
streaming=request_data.stream,
n_gpu_layers=request_data.n_gpu_layers,
temperature=request_data.temperature,
max_tokens=request_data.max_tokens,
top_p=request_data.top_p,
cache=request_data.cache,
n_ctx=request_data.n_ctx,
base_url=provider.args.get("base_url")
)
messages = [BaseMessage(
type=message["role"], content=message["content"]) for message in request_data.messages]
messages = base_messages_to_default(messages)
if available_functions is True:
configs = PromptConfig()
new_messages = configs.extract_text(configs.prompt_template(
), prompt=messages[-1].content, functions=request_data.functions)
messages.pop()
messages = messages + new_messages
ROOT_DIR: str = os.path.dirname(Path(__file__).parent.parent.parent)
chat_input.grammer_path = ROOT_DIR + "/docs/json.gbnf"
chat_input.f16_kv = True
chatProvider = LLMFactory.get_chat_model(
input=chat_input, provider_name=provider.provider)
response = chatProvider.compelete(
prompts=[messages])
response_str = llm_result_to_str(response)
completion_id = "".join(random.choices(
string.ascii_letters + string.digits, k=28))
completion_timestamp = int(time.time())
if not request_data.stream:
inp_token = num_tokens_from_string(
"".join([message.content for message in messages]))
out_token = num_tokens_from_string(response_str)
function_out = None
if available_functions is True:
function_out = extract_json_from_string(response_str)
res = {
"id": f"chatcmpl-{completion_id}",
"object": "chat.completion",
"created": completion_timestamp,
"model": provider.name,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": response_str,
},
"finish_reason": "stop",
}
],
"usage": {
"prompt_tokens": inp_token,
"completion_tokens": out_token,
"total_tokens": inp_token + out_token, | "cost": "{:.6f}".format(completion_price_calculator(provider.cost.input, provider.cost.output, inp_token, out_token)) | 7 | 2023-11-11 00:32:31+00:00 | 4k |
AI-sandbox/HyperFast | hyperfast/hyperfast.py | [
{
"identifier": "config",
"path": "hyperfast/config.py",
"snippet": ""
},
{
"identifier": "seed_everything",
"path": "hyperfast/utils.py",
"snippet": "def seed_everything(seed: int):\n random.seed(seed)\n os.environ[\"PYTHONHASHSEED\"] = str(seed)\n np.random.seed(seed)\n tor... | import os
import math
import torch
import requests
import numpy as np
import pandas as pd
import torch.nn.functional as F
from torch import Tensor
from types import SimpleNamespace
from .config import config
from sklearn.base import BaseEstimator
from sklearn.utils.validation import check_X_y, check_array, check_is_fitted
from sklearn.impute import SimpleImputer
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from .utils import (
seed_everything,
transform_data_for_main_network,
forward_main_network,
nn_bias_logits,
fine_tune_main_network,
)
from .model import HyperFast | 2,694 |
class HyperFastClassifier(BaseEstimator):
"""
A scikit-learn-like interface for the HyperFast model.
Attributes:
device (str): Device to run the model on.
n_ensemble (int): Number of ensemble models to use.
batch_size (int): Size of the batch for weight prediction and ensembling.
nn_bias (bool): Whether to use nearest neighbor bias.
optimization (str): Strategy for optimization, can be None, 'optimize', or 'ensemble_optimize'.
optimize_steps (int): Number of optimization steps.
torch_pca (bool): Whether to use PyTorch-based PCA optimized for GPU (fast) or scikit-learn PCA (slower).
seed (int): Random seed for reproducibility.
"""
def __init__(
self,
device="cuda:0",
n_ensemble=16,
batch_size=2048,
nn_bias=False,
optimization="ensemble_optimize",
optimize_steps=64,
torch_pca=True,
seed=3,
):
self.device = device
self.n_ensemble = n_ensemble
self.batch_size = batch_size
self.nn_bias = nn_bias
self.optimization = optimization
self.optimize_steps = optimize_steps
self.torch_pca = torch_pca
self.seed = seed
seed_everything(self.seed)
|
class HyperFastClassifier(BaseEstimator):
"""
A scikit-learn-like interface for the HyperFast model.
Attributes:
device (str): Device to run the model on.
n_ensemble (int): Number of ensemble models to use.
batch_size (int): Size of the batch for weight prediction and ensembling.
nn_bias (bool): Whether to use nearest neighbor bias.
optimization (str): Strategy for optimization, can be None, 'optimize', or 'ensemble_optimize'.
optimize_steps (int): Number of optimization steps.
torch_pca (bool): Whether to use PyTorch-based PCA optimized for GPU (fast) or scikit-learn PCA (slower).
seed (int): Random seed for reproducibility.
"""
def __init__(
self,
device="cuda:0",
n_ensemble=16,
batch_size=2048,
nn_bias=False,
optimization="ensemble_optimize",
optimize_steps=64,
torch_pca=True,
seed=3,
):
self.device = device
self.n_ensemble = n_ensemble
self.batch_size = batch_size
self.nn_bias = nn_bias
self.optimization = optimization
self.optimize_steps = optimize_steps
self.torch_pca = torch_pca
self.seed = seed
seed_everything(self.seed) | self._cfg = self._load_config(config, self.device, self.torch_pca, self.nn_bias) | 0 | 2023-11-14 05:56:47+00:00 | 4k |
TCLResearchEurope/torch-dag | node_api_conversion/convert_cell_to_dag_module.py | [
{
"identifier": "from_nd_converter",
"path": "node_api_conversion/from_nd_converter.py",
"snippet": "def adjust_padding(padding, kernel_size):\ndef convert_node(node: nd.nodes, inst: nd.nodes.NodeInstance = None) -> torch.nn.Module:\ndef _(node: nd.cells.Cell, inst: nd.nodes.NodeInstance = None) -> torc... | import argparse
import logging
import node_api as nd
import modelhub_client as mh
from node_api_conversion import from_nd_converter
from torch_dag.visualization.visualize_dag import DagVisualizer
from node_api_conversion.utils import log_cell_characteristics | 3,475 | #
# Copyright © TCL Research Europe. All rights reserved.
#
logger = logging.getLogger(__name__)
def find_icns_to_remove(cell: nd.cells.Cell):
result = []
for icn in cell.inner_cell_nodes:
if isinstance(icn.node, nd.ops.Activation):
if icn.node.activation_name in (None, 'none', 'identity'):
result.append(icn)
if isinstance(icn.node, nd.ops.Sum) and len(icn.predecessors) == 1:
result.append(icn)
if isinstance(icn.node, nd.ops.Concat) and len(icn.predecessors) == 1:
result.append(icn)
if isinstance(icn.node, nd.ops.Mul) and len(icn.predecessors) == 1:
result.append(icn)
if isinstance(icn.node, nd.cells.Cell):
result.extend(find_icns_to_remove(icn.node))
return result
def clean_up(cell: nd.cells.Cell):
to_remove = find_icns_to_remove(cell)
for icn in to_remove:
icn.cell.remove_node(icn)
logger.info(f'Removing {icn} with class {icn.node.__class__.__name__}')
def parse_args():
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('--model_path')
arg_parser.add_argument('--hub_name')
arg_parser.add_argument('--saving_path')
arg_parser.add_argument(
'--input_shape',
type=int,
nargs='+',
default=(1, 320, 320, 3),
)
args = arg_parser.parse_args()
return args
def main():
args = parse_args()
if args.hub_name:
model = mh.api.Model.get(args.hub_name)
cell, _ = model.load_cell()
else:
cell, _ = nd.io.load_cell(args.model_path)
input_shape = tuple(args.input_shape)
cell = cell.flatten()
cell.predict()
clean_up(cell)
nd.cells_utils.fuse_padding_nodes(cell, input_size=input_shape)
| #
# Copyright © TCL Research Europe. All rights reserved.
#
logger = logging.getLogger(__name__)
def find_icns_to_remove(cell: nd.cells.Cell):
result = []
for icn in cell.inner_cell_nodes:
if isinstance(icn.node, nd.ops.Activation):
if icn.node.activation_name in (None, 'none', 'identity'):
result.append(icn)
if isinstance(icn.node, nd.ops.Sum) and len(icn.predecessors) == 1:
result.append(icn)
if isinstance(icn.node, nd.ops.Concat) and len(icn.predecessors) == 1:
result.append(icn)
if isinstance(icn.node, nd.ops.Mul) and len(icn.predecessors) == 1:
result.append(icn)
if isinstance(icn.node, nd.cells.Cell):
result.extend(find_icns_to_remove(icn.node))
return result
def clean_up(cell: nd.cells.Cell):
to_remove = find_icns_to_remove(cell)
for icn in to_remove:
icn.cell.remove_node(icn)
logger.info(f'Removing {icn} with class {icn.node.__class__.__name__}')
def parse_args():
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('--model_path')
arg_parser.add_argument('--hub_name')
arg_parser.add_argument('--saving_path')
arg_parser.add_argument(
'--input_shape',
type=int,
nargs='+',
default=(1, 320, 320, 3),
)
args = arg_parser.parse_args()
return args
def main():
args = parse_args()
if args.hub_name:
model = mh.api.Model.get(args.hub_name)
cell, _ = model.load_cell()
else:
cell, _ = nd.io.load_cell(args.model_path)
input_shape = tuple(args.input_shape)
cell = cell.flatten()
cell.predict()
clean_up(cell)
nd.cells_utils.fuse_padding_nodes(cell, input_size=input_shape) | log_cell_characteristics(cell, input_shape[1:]) | 2 | 2023-11-17 15:36:44+00:00 | 4k |
timlrx/simple-ai-agents | simple_ai_agents/cli.py | [
{
"identifier": "ChatAgent",
"path": "simple_ai_agents/chat_agent.py",
"snippet": "class ChatAgent(BaseModel):\n \"\"\"\n A chatbot class that provides additional functionality\n for creating and managing chat sessions.\n\n Args:\n character (str, optional): The name of the chatbot fo... | import sys
import click
from dotenv import load_dotenv
from simple_ai_agents.chat_agent import ChatAgent
from simple_ai_agents.prompts import SYSTEM_PROMPT | 3,551 |
load_dotenv()
@click.command()
@click.option("--character", default=None, help="Specify the character")
@click.option("--prime/--no-prime", default=False, help="Enable priming")
@click.option(
"-m",
"--model",
default="gpt-3.5-turbo",
help="""Specify the LLM model e.g. gpt-3.5-turbo, ollama/mistral.
Uses gpt-3.5-turbo by default.""",
)
@click.option("--temperature", default=0.7, help="LLM temperature. Default is 0.7.")
|
load_dotenv()
@click.command()
@click.option("--character", default=None, help="Specify the character")
@click.option("--prime/--no-prime", default=False, help="Enable priming")
@click.option(
"-m",
"--model",
default="gpt-3.5-turbo",
help="""Specify the LLM model e.g. gpt-3.5-turbo, ollama/mistral.
Uses gpt-3.5-turbo by default.""",
)
@click.option("--temperature", default=0.7, help="LLM temperature. Default is 0.7.") | @click.option("-s", "--system", default=SYSTEM_PROMPT, help="System prompt") | 1 | 2023-11-10 06:01:25+00:00 | 4k |
DIAGNijmegen/HoVer-UNet | train/apply_postprocessing.py | [
{
"identifier": "DatasetPannuke",
"path": "data/pannuke_distillation_dataset.py",
"snippet": "class DatasetPannuke(Dataset):\n \"\"\"\n Distillaton pannuke dataset\n \"\"\"\n\n def __init__(self, path: str, mode: str = 'train', true_labels: bool = False,\n hovernet_prediction... | import colorsys
import json
import os
import random
import cv2
import numpy as np
import segmentation_models_pytorch as smp
import torch
import torch.nn.functional as F
from multiprocessing import Pool
from time import time
from torch.utils.data import DataLoader
from tqdm import tqdm
from data.pannuke_distillation_dataset import DatasetPannuke
from models.HoVerNet.post_proc import process | 2,460 |
def random_colors(N, bright=True):
"""Generate random colors.
To get visually distinct colors, generate them in HSV space then
convert to RGB.
"""
brightness = 1.0 if bright else 0.7
hsv = [(i / N, 1, brightness) for i in range(N)]
colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))
random.shuffle(colors)
return colors
def visualize_instances_dict(
input_image, inst_dict, draw_dot=False, type_colour=None, line_thickness=2
):
"""Overlays segmentation results (dictionary) on image as contours.
Args:
input_image: input image
inst_dict: dict of output prediction, defined as in this library
draw_dot: to draw a dot for each centroid
type_colour: a dict of {type_id : (type_name, colour)} ,
`type_id` is from 0-N and `colour` is a tuple of (R, G, B)
line_thickness: line thickness of contours
"""
# overlay = np.copy((input_image))
overlay = np.zeros(input_image.shape)
inst_rng_colors = random_colors(len(inst_dict))
inst_rng_colors = np.array(inst_rng_colors) * 255
inst_rng_colors = inst_rng_colors.astype(np.uint8)
for idx, [inst_id, inst_info] in enumerate(inst_dict.items()):
inst_contour = inst_info["contour"]
if "type" in inst_info and type_colour is not None:
inst_colour = type_colour[inst_info["type"]][1]
else:
inst_colour = (inst_rng_colors[idx]).tolist()
cv2.drawContours(overlay, [inst_contour], -1, inst_colour, line_thickness)
if draw_dot:
inst_centroid = inst_info["centroid"]
inst_centroid = tuple([int(v) for v in inst_centroid])
overlay = cv2.circle(overlay, inst_centroid, 3, (255, 0, 0), -1)
return overlay
def create_mask(x, _pred):
instance_map, _centroids = x
mask = np.zeros(instance_map.shape + (6,))
for idx, info in _centroids.items():
try:
mask[..., info['type']][instance_map == idx] = idx
mask[..., 0][instance_map == idx] = 1
except Exception:
print(_pred[-1])
return mask
def _postprocess(_pred):
x = process(_pred[1], nr_types=6)
mask = create_mask(x, _pred)
return _pred[0], x, _pred[2], mask
def apply_postprocessing(path_weights, path_test, model):
model.load_state_dict(torch.load(path_weights)['model_state_dict'])
model.eval()
|
def random_colors(N, bright=True):
"""Generate random colors.
To get visually distinct colors, generate them in HSV space then
convert to RGB.
"""
brightness = 1.0 if bright else 0.7
hsv = [(i / N, 1, brightness) for i in range(N)]
colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))
random.shuffle(colors)
return colors
def visualize_instances_dict(
input_image, inst_dict, draw_dot=False, type_colour=None, line_thickness=2
):
"""Overlays segmentation results (dictionary) on image as contours.
Args:
input_image: input image
inst_dict: dict of output prediction, defined as in this library
draw_dot: to draw a dot for each centroid
type_colour: a dict of {type_id : (type_name, colour)} ,
`type_id` is from 0-N and `colour` is a tuple of (R, G, B)
line_thickness: line thickness of contours
"""
# overlay = np.copy((input_image))
overlay = np.zeros(input_image.shape)
inst_rng_colors = random_colors(len(inst_dict))
inst_rng_colors = np.array(inst_rng_colors) * 255
inst_rng_colors = inst_rng_colors.astype(np.uint8)
for idx, [inst_id, inst_info] in enumerate(inst_dict.items()):
inst_contour = inst_info["contour"]
if "type" in inst_info and type_colour is not None:
inst_colour = type_colour[inst_info["type"]][1]
else:
inst_colour = (inst_rng_colors[idx]).tolist()
cv2.drawContours(overlay, [inst_contour], -1, inst_colour, line_thickness)
if draw_dot:
inst_centroid = inst_info["centroid"]
inst_centroid = tuple([int(v) for v in inst_centroid])
overlay = cv2.circle(overlay, inst_centroid, 3, (255, 0, 0), -1)
return overlay
def create_mask(x, _pred):
instance_map, _centroids = x
mask = np.zeros(instance_map.shape + (6,))
for idx, info in _centroids.items():
try:
mask[..., info['type']][instance_map == idx] = idx
mask[..., 0][instance_map == idx] = 1
except Exception:
print(_pred[-1])
return mask
def _postprocess(_pred):
x = process(_pred[1], nr_types=6)
mask = create_mask(x, _pred)
return _pred[0], x, _pred[2], mask
def apply_postprocessing(path_weights, path_test, model):
model.load_state_dict(torch.load(path_weights)['model_state_dict'])
model.eval() | data_infer = DatasetPannuke(path_test, mode='infer') | 0 | 2023-11-10 09:37:29+00:00 | 4k |
StanislavPetrovV/3D-Number-Renderer-with-UMAP | renderer.py | [
{
"identifier": "ShaderProgram",
"path": "shader_program.py",
"snippet": "class ShaderProgram:\n def __init__(self, renderer):\n self.app = renderer.app\n self.ctx = renderer.ctx\n self.camera = renderer.camera\n\n # -------- shaders -------- #\n self.axis = self.ge... | from shader_program import ShaderProgram
from camera import Camera
from meshes.point_cloud_mesh import PointCloudMesh
from meshes.axis_mesh import AxisMesh | 2,066 |
class Renderer:
def __init__(self, app):
self.app = app
self.ctx = app.ctx
#
self.camera = Camera(app)
|
class Renderer:
def __init__(self, app):
self.app = app
self.ctx = app.ctx
#
self.camera = Camera(app) | self.shader_program = ShaderProgram(renderer=self) | 0 | 2023-11-11 10:35:37+00:00 | 4k |
fofr/cog-sdxl-lcm-multi-controlnet-lora | predict.py | [
{
"identifier": "WeightsManager",
"path": "weights_manager.py",
"snippet": "class WeightsManager:\n def __init__(self, predictor):\n self.predictor = predictor\n self.weights_cache = WeightsDownloadCache()\n\n def load_trained_weights(self, weights, pipe):\n from no_init impor... | import os
import time
import numpy as np
import torch
from typing import List, Optional
from cog import BasePredictor, Input, Path
from diffusers import (
DiffusionPipeline,
LCMScheduler,
StableDiffusionXLImg2ImgPipeline,
StableDiffusionXLInpaintPipeline,
StableDiffusionXLControlNetPipeline,
StableDiffusionXLControlNetInpaintPipeline,
StableDiffusionXLControlNetImg2ImgPipeline,
)
from diffusers.pipelines.stable_diffusion.safety_checker import (
StableDiffusionSafetyChecker,
)
from transformers import CLIPImageProcessor
from weights_manager import WeightsManager
from weights_downloader import WeightsDownloader
from controlnet import ControlNet
from sizing_strategy import SizingStrategy | 2,900 |
SDXL_MODEL_CACHE = "./sdxl-cache"
REFINER_MODEL_CACHE = "./refiner-cache"
SAFETY_CACHE = "./safety-cache"
LCM_CACHE = "./lcm-cache"
FEATURE_EXTRACTOR = "./feature-extractor"
SDXL_URL = "https://weights.replicate.delivery/default/sdxl/sdxl-vae-upcast-fix.tar"
REFINER_URL = (
"https://weights.replicate.delivery/default/sdxl/refiner-no-vae-no-encoder-1.0.tar"
)
SAFETY_URL = "https://weights.replicate.delivery/default/sdxl/safety-1.0.tar"
class Predictor(BasePredictor):
def load_trained_weights(self, weights, pipe):
self.weights_manager.load_trained_weights(weights, pipe)
def build_controlnet_pipeline(self, pipeline_class, controlnet_models):
pipe = pipeline_class.from_pretrained(
SDXL_MODEL_CACHE,
torch_dtype=torch.float16,
use_safetensors=True,
variant="fp16",
vae=self.txt2img_pipe.vae,
text_encoder=self.txt2img_pipe.text_encoder,
text_encoder_2=self.txt2img_pipe.text_encoder_2,
tokenizer=self.txt2img_pipe.tokenizer,
tokenizer_2=self.txt2img_pipe.tokenizer_2,
unet=self.txt2img_pipe.unet,
scheduler=self.txt2img_pipe.scheduler,
controlnet=self.controlnet.get_models(controlnet_models),
)
pipe.to("cuda")
return pipe
def setup(self, weights: Optional[Path] = None):
"""Load the model into memory to make running multiple predictions efficient"""
start = time.time()
self.sizing_strategy = SizingStrategy()
self.weights_manager = WeightsManager(self)
self.tuned_model = False
self.tuned_weights = None
if str(weights) == "weights":
weights = None
print("Loading safety checker...")
|
SDXL_MODEL_CACHE = "./sdxl-cache"
REFINER_MODEL_CACHE = "./refiner-cache"
SAFETY_CACHE = "./safety-cache"
LCM_CACHE = "./lcm-cache"
FEATURE_EXTRACTOR = "./feature-extractor"
SDXL_URL = "https://weights.replicate.delivery/default/sdxl/sdxl-vae-upcast-fix.tar"
REFINER_URL = (
"https://weights.replicate.delivery/default/sdxl/refiner-no-vae-no-encoder-1.0.tar"
)
SAFETY_URL = "https://weights.replicate.delivery/default/sdxl/safety-1.0.tar"
class Predictor(BasePredictor):
def load_trained_weights(self, weights, pipe):
self.weights_manager.load_trained_weights(weights, pipe)
def build_controlnet_pipeline(self, pipeline_class, controlnet_models):
pipe = pipeline_class.from_pretrained(
SDXL_MODEL_CACHE,
torch_dtype=torch.float16,
use_safetensors=True,
variant="fp16",
vae=self.txt2img_pipe.vae,
text_encoder=self.txt2img_pipe.text_encoder,
text_encoder_2=self.txt2img_pipe.text_encoder_2,
tokenizer=self.txt2img_pipe.tokenizer,
tokenizer_2=self.txt2img_pipe.tokenizer_2,
unet=self.txt2img_pipe.unet,
scheduler=self.txt2img_pipe.scheduler,
controlnet=self.controlnet.get_models(controlnet_models),
)
pipe.to("cuda")
return pipe
def setup(self, weights: Optional[Path] = None):
"""Load the model into memory to make running multiple predictions efficient"""
start = time.time()
self.sizing_strategy = SizingStrategy()
self.weights_manager = WeightsManager(self)
self.tuned_model = False
self.tuned_weights = None
if str(weights) == "weights":
weights = None
print("Loading safety checker...") | WeightsDownloader.download_if_not_exists(SAFETY_URL, SAFETY_CACHE) | 1 | 2023-11-16 11:11:27+00:00 | 4k |
joyn-gg/discord.http | discord_http/http.py | [
{
"identifier": "NotFound",
"path": "discord_http/errors.py",
"snippet": "class NotFound(HTTPException):\n \"\"\" Raised whenever a HTTP request returns 404 \"\"\"\n pass"
},
{
"identifier": "DiscordServerError",
"path": "discord_http/errors.py",
"snippet": "class DiscordServerErro... | import aiohttp
import asyncio
import json
import logging
import sys
from aiohttp.client_exceptions import ContentTypeError
from collections import deque
from typing import (
Optional, Any, Union, Self, overload,
Literal, TypeVar, Generic, TYPE_CHECKING
)
from .errors import (
NotFound, DiscordServerError,
Forbidden, HTTPException
)
from .user import User
from .user import User | 2,307 | @overload
async def query(
self,
method: MethodTypes,
path: str,
*,
res_method: Literal["read"] = "read",
**kwargs
) -> HTTPResponse[bytes]:
...
@overload
async def query(
self,
method: MethodTypes,
path: str,
*,
res_method: Literal["text"] = "text",
**kwargs
) -> HTTPResponse[str]:
...
async def query(
self,
method: MethodTypes,
path: str,
*,
res_method: ResMethodTypes = "json",
**kwargs
) -> HTTPResponse:
"""
Make a request to the Discord API
Parameters
----------
method: `str`
Which HTTP method to use
path: `str`
The path to make the request to
res_method: `str`
The method to use to get the response
Returns
-------
`HTTPResponse`
The response from the request
Raises
------
`ValueError`
Invalid HTTP method
`DiscordServerError`
Something went wrong on Discord's end
`Forbidden`
You are not allowed to do this
`NotFound`
The resource was not found
`HTTPException`
Something went wrong
`RuntimeError`
Unreachable code, reached max tries (5)
"""
if "headers" not in kwargs:
kwargs["headers"] = {}
if "Authorization" not in kwargs["headers"]:
kwargs["headers"]["Authorization"] = f"Bot {self.token}"
if res_method == "json" and "Content-Type" not in kwargs["headers"]:
kwargs["headers"]["Content-Type"] = "application/json"
kwargs["headers"]["User-Agent"] = "discord.http Python/{0} aiohttp/{1}".format(
".".join(str(i) for i in sys.version_info[:3]),
aiohttp.__version__
)
reason = kwargs.pop("reason", None)
if reason:
kwargs["headers"]["X-Audit-Log-Reason"] = reason
_api_url = self.api_url
if kwargs.pop("webhook", False):
_api_url = self.base_url
ratelimit = self.get_ratelimit(f"{method} {path}")
async with ratelimit:
for tries in range(5):
try:
r: HTTPResponse = await query(
method,
f"{_api_url}{path}",
res_method=res_method,
**kwargs
)
_log.debug(f"HTTP {method.upper()} ({r.status}): {path}")
match r.status:
case x if x >= 200 and x <= 299:
ratelimit.update(r)
return r
case 429:
retry_after: float = r.response["retry_after"]
_log.warning(f"Ratelimit hit ({path}), waiting {retry_after}s...")
await asyncio.sleep(retry_after)
continue
case x if x in (500, 502, 503, 504):
# Try again, maybe it will work next time, surely...
await asyncio.sleep(1 + tries * 2)
continue
# The lovely exception hell
case x if x >= 500:
raise DiscordServerError(r)
case 403:
raise Forbidden(r)
case 404:
|
if TYPE_CHECKING:
MethodTypes = Literal["GET", "POST", "DELETE", "PUT", "HEAD", "PATCH", "OPTIONS"]
ResMethodTypes = Literal["text", "read", "json"]
ResponseT = TypeVar("ResponseT")
_log = logging.getLogger(__name__)
__all__ = (
"DiscordAPI",
"HTTPResponse",
)
class HTTPResponse(Generic[ResponseT]):
def __init__(
self,
*,
status: int,
response: ResponseT,
reason: str,
res_method: ResMethodTypes,
headers: dict[str, str],
):
self.status = status
self.response = response
self.res_method = res_method
self.reason = reason
self.headers = headers
def __repr__(self) -> str:
return f"<HTTPResponse status={self.status} res_method='{self.res_method}'>"
@overload
async def query(
method: MethodTypes,
url: str,
*,
res_method: Literal["text"],
) -> HTTPResponse[str]:
...
@overload
async def query(
method: MethodTypes,
url: str,
*,
res_method: Literal["json"],
) -> HTTPResponse[dict[Any, Any]]:
...
@overload
async def query(
method: MethodTypes,
url: str,
*,
res_method: Literal["read"],
) -> HTTPResponse[bytes]:
...
async def query(
method: MethodTypes,
url: str,
*,
res_method: ResMethodTypes = "text",
**kwargs
) -> HTTPResponse:
"""
Make a request using the aiohttp library
Parameters
----------
method: `Optional[str]`
The HTTP method to use, defaults to GET
url: `str`
The URL to make the request to
res_method: `Optional[str]`
The method to use to get the response, defaults to text
Returns
-------
`HTTPResponse`
The response from the request
"""
session = aiohttp.ClientSession()
if not res_method:
res_method = "text"
session_method = getattr(session, str(method).lower(), None)
if not session_method:
raise ValueError(f"Invalid HTTP method: {method}")
if res_method not in ("text", "read", "json"):
raise ValueError(
f"Invalid res_method: {res_method}, "
"must be either text, read or json"
)
async with session_method(str(url), **kwargs) as res:
try:
r = await getattr(res, res_method.lower())()
except ContentTypeError:
if res_method == "json":
try:
r = json.loads(await res.text())
except json.JSONDecodeError:
# Give up trying, something is really wrong...
r = await res.text()
res_method = "text"
output = HTTPResponse(
status=res.status,
response=r, # type: ignore
res_method=res_method,
reason=res.reason,
headers=res.headers
)
await session.close()
return output
class Ratelimit:
def __init__(self, key: str):
self._key: str = key
self.limit: int = 1
self.outgoing: int = 0
self.remaining = self.limit
self.reset_after: float = 0.0
self.expires: Optional[float] = None
self._loop: asyncio.AbstractEventLoop = asyncio.get_running_loop()
self._lock = asyncio.Lock()
self._last_request: float = self._loop.time()
self._pending_requests: deque[asyncio.Future[Any]] = deque()
def reset(self) -> None:
""" Reset the ratelimit """
self.remaining = self.limit - self.outgoing
self.expires = None
self.reset_after = 0.0
def update(self, response: HTTPResponse) -> None:
""" Update the ratelimit with the response headers """
self.remaining = int(response.headers.get("x-ratelimit-remaining", 0))
self.reset_after = float(response.headers.get("x-ratelimit-reset-after", 0))
self.expires = self._loop.time() + self.reset_after
def _wake_next(self) -> None:
while self._pending_requests:
future = self._pending_requests.popleft()
if not future.done():
future.set_result(None)
break
def _wake(self, count: int = 1) -> None:
awaken = 0
while self._pending_requests:
future = self._pending_requests.popleft()
if not future.done():
future.set_result(None)
awaken += 1
if awaken >= count:
break
async def _refresh(self):
async with self._lock:
_log.debug(
f"Ratelimit bucket hit ({self._key}), "
f"waiting {self.reset_after}s..."
)
await asyncio.sleep(self.reset_after)
_log.debug(f"Ratelimit bucket released ({self._key})")
self.reset()
self._wake(self.remaining)
def is_expired(self) -> bool:
return (
self.expires is not None and
self._loop.time() > self.expires
)
def is_inactive(self) -> bool:
return (
(self._loop.time() - self._last_request) >= 300 and
len(self._pending_requests) == 0
)
async def _queue_up(self) -> None:
self._last_request = self._loop.time()
if self.is_expired():
self.reset()
while self.remaining <= 0:
future = self._loop.create_future()
self._pending_requests.append(future)
try:
await future
except Exception:
future.cancel()
if self.remaining > 0 and not future.cancelled():
self._wake_next()
raise
self.remaining -= 1
self.outgoing += 1
async def __aenter__(self) -> Self:
await self._queue_up()
return self
async def __aexit__(self, type, value, traceback) -> None:
self.outgoing -= 1
tokens = self.remaining - self.outgoing
if not self._lock.locked():
if tokens <= 0:
await self._refresh()
elif self._pending_requests:
self._wake(tokens)
class DiscordAPI:
def __init__(
self,
*,
token: str,
application_id: Optional[int],
api_version: Optional[int] = None
):
self.token: str = token
self.application_id: Optional[int] = application_id
self.api_version: int = api_version or 10
if not isinstance(self.api_version, int):
raise TypeError("api_version must be an integer")
self.base_url: str = "https://discord.com/api"
self.api_url: str = f"{self.base_url}/v{self.api_version}"
self._buckets: dict[str, Ratelimit] = {}
def _clear_old_ratelimits(self) -> None:
if len(self._buckets) <= 256:
return
for key in [k for k, v in self._buckets.items() if v.is_inactive()]:
try:
del self._buckets[key]
except KeyError:
pass
def get_ratelimit(self, key: str) -> Ratelimit:
try:
value = self._buckets[key]
except KeyError:
self._buckets[key] = value = Ratelimit(key)
self._clear_old_ratelimits()
return value
@overload
async def query(
self,
method: MethodTypes,
path: str,
*,
res_method: Literal["json"] = "json",
**kwargs
) -> HTTPResponse[dict[Any, Any]]:
...
@overload
async def query(
self,
method: MethodTypes,
path: str,
*,
res_method: Literal["read"] = "read",
**kwargs
) -> HTTPResponse[bytes]:
...
@overload
async def query(
self,
method: MethodTypes,
path: str,
*,
res_method: Literal["text"] = "text",
**kwargs
) -> HTTPResponse[str]:
...
async def query(
self,
method: MethodTypes,
path: str,
*,
res_method: ResMethodTypes = "json",
**kwargs
) -> HTTPResponse:
"""
Make a request to the Discord API
Parameters
----------
method: `str`
Which HTTP method to use
path: `str`
The path to make the request to
res_method: `str`
The method to use to get the response
Returns
-------
`HTTPResponse`
The response from the request
Raises
------
`ValueError`
Invalid HTTP method
`DiscordServerError`
Something went wrong on Discord's end
`Forbidden`
You are not allowed to do this
`NotFound`
The resource was not found
`HTTPException`
Something went wrong
`RuntimeError`
Unreachable code, reached max tries (5)
"""
if "headers" not in kwargs:
kwargs["headers"] = {}
if "Authorization" not in kwargs["headers"]:
kwargs["headers"]["Authorization"] = f"Bot {self.token}"
if res_method == "json" and "Content-Type" not in kwargs["headers"]:
kwargs["headers"]["Content-Type"] = "application/json"
kwargs["headers"]["User-Agent"] = "discord.http Python/{0} aiohttp/{1}".format(
".".join(str(i) for i in sys.version_info[:3]),
aiohttp.__version__
)
reason = kwargs.pop("reason", None)
if reason:
kwargs["headers"]["X-Audit-Log-Reason"] = reason
_api_url = self.api_url
if kwargs.pop("webhook", False):
_api_url = self.base_url
ratelimit = self.get_ratelimit(f"{method} {path}")
async with ratelimit:
for tries in range(5):
try:
r: HTTPResponse = await query(
method,
f"{_api_url}{path}",
res_method=res_method,
**kwargs
)
_log.debug(f"HTTP {method.upper()} ({r.status}): {path}")
match r.status:
case x if x >= 200 and x <= 299:
ratelimit.update(r)
return r
case 429:
retry_after: float = r.response["retry_after"]
_log.warning(f"Ratelimit hit ({path}), waiting {retry_after}s...")
await asyncio.sleep(retry_after)
continue
case x if x in (500, 502, 503, 504):
# Try again, maybe it will work next time, surely...
await asyncio.sleep(1 + tries * 2)
continue
# The lovely exception hell
case x if x >= 500:
raise DiscordServerError(r)
case 403:
raise Forbidden(r)
case 404: | raise NotFound(r) | 0 | 2023-11-14 12:50:42+00:00 | 4k |
Ganymede-Bio/bio-curve-fit | tests/test_four_pl_logistic.py | [
{
"identifier": "FourPLLogistic",
"path": "bio_curve_fit/logistic.py",
"snippet": "class FourPLLogistic(BaseEstimator, RegressorMixin, BaseStandardCurve):\n def __init__(\n self,\n A=None,\n B=None,\n C=None,\n D=None,\n LLOD=None,\n ULOD=None,\n ... | import numpy as np
import pandas as pd
import pytest
from bio_curve_fit.logistic import FourPLLogistic
from bio_curve_fit.plotting import plot_standard_curve | 3,536 |
# set a seed for reproducibility
np.random.seed(42)
def test_fit_and_plot():
TEST_PARAMS = [1.0, 1.0, 2.0, 3.0]
x_data = np.logspace(0.00001, 7, 100, base=np.e) # type: ignore
# generate y-data based on the test parameters
|
# set a seed for reproducibility
np.random.seed(42)
def test_fit_and_plot():
TEST_PARAMS = [1.0, 1.0, 2.0, 3.0]
x_data = np.logspace(0.00001, 7, 100, base=np.e) # type: ignore
# generate y-data based on the test parameters | y_data = FourPLLogistic.four_param_logistic( | 0 | 2023-11-13 15:06:15+00:00 | 4k |
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,816 |
# 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)
start_time = time.time()
heuristic_model.fit(X_train, y_train, random_state=random_state)
runtime = time.time() - start_time
y_pred_heuristic = heuristic_model.predict(X_test)
auc_score_heuristic = roc_auc_score(y_test, y_pred_heuristic)
# Record heuristic model results
result_heuristic = {
"model_name": "heuristic",
"n_features": int(n_features * n_bins),
"n_samples": n_samples,
"n_informative": n_informative,
"depth": depth,
"AUC Score": auc_score_heuristic,
"Runtime (seconds)": runtime,
}
results.append(result_heuristic)
save_results(results, log_filename)
for _lambda in _lambda_range:
# BackboneDecisionTree model iterations for 'backbone' solution
for alpha, beta, num_subproblems, num_iterations in product(
alpha_range, beta_range, num_subproblems_range, num_iterations_range
):
|
# 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)
start_time = time.time()
heuristic_model.fit(X_train, y_train, random_state=random_state)
runtime = time.time() - start_time
y_pred_heuristic = heuristic_model.predict(X_test)
auc_score_heuristic = roc_auc_score(y_test, y_pred_heuristic)
# Record heuristic model results
result_heuristic = {
"model_name": "heuristic",
"n_features": int(n_features * n_bins),
"n_samples": n_samples,
"n_informative": n_informative,
"depth": depth,
"AUC Score": auc_score_heuristic,
"Runtime (seconds)": runtime,
}
results.append(result_heuristic)
save_results(results, log_filename)
for _lambda in _lambda_range:
# BackboneDecisionTree model iterations for 'backbone' solution
for alpha, beta, num_subproblems, num_iterations in product(
alpha_range, beta_range, num_subproblems_range, num_iterations_range
): | backbone_model = BackboneDecisionTree( | 0 | 2023-11-18 14:28:12+00:00 | 4k |
openclimatefix/Open-Source-Quartz-Solar-Forecast | quartz_solar_forecast/eval/forecast.py | [
{
"identifier": "get_nwp",
"path": "quartz_solar_forecast/data.py",
"snippet": "def get_nwp(site: PVSite, ts: datetime, nwp_source: str = \"icon\") -> xr.Dataset:\n \"\"\"\n Get GFS NWP data for a point time space and time\n\n :param site: the PV site\n :param ts: the timestamp for when you ... | import os
import pandas as pd
import xarray as xr
from psp.data_sources.nwp import NwpDataSource
from psp.data_sources.pv import NetcdfPvDataSource
from psp.serialization import load_model
from psp.typings import X
from quartz_solar_forecast.data import get_nwp, make_pv_data
from quartz_solar_forecast.pydantic_models import PVSite
from quartz_solar_forecast.forecasts.v1 import forecast_v1
from quartz_solar_forecast.data import format_nwp_data
from datetime import datetime | 2,428 |
dir_path = os.path.dirname(os.path.realpath(__file__))
def run_forecast(pv_df: pd.DataFrame, nwp_df: pd.DataFrame, nwp_source="ICON") -> pd.DataFrame:
"""
Run the forecast from NWP data
:param pv_df: the PV site data. This should have columns timestamp, id, latitude, longitude, and capacity
:param nwp_df: all the nwp data for the site and location. This shoulw have the following rows
- timestamp: the timestamp of the site
- temperature_2m
- precipitation
- shortwave_radiation
- direct_radiation",
- cloudcover_low",
- cloudcover_mid",
- cloudcover_high",
maybe more
"""
# load model only once
model = load_model(f"{dir_path}/../models/model-0.3.0.pkl")
all_predictions = []
for i in range(len(pv_df)):
print(f"Running forecast for {i} of {len(pv_df)}")
pv_row = pv_df.iloc[i]
site = PVSite(
latitude=pv_row["latitude"],
longitude=pv_row["longitude"],
capacity_kwp=pv_row["capacity"],
)
nwp_site_df = nwp_df[
(nwp_df["pv_id"] == pv_row.pv_id) & (nwp_df["timestamp"] == pv_row.timestamp)
]
pv_id = pv_df["pv_id"][i]
ts = pv_df["timestamp"][i]
# format
for c in ["timestamp", "latitude", "longitude", "pv_id"]:
if c in nwp_site_df.columns:
nwp_site_df = nwp_site_df.drop(columns=c)
nwp_site_df.set_index("time", inplace=True, drop=True)
if isinstance(ts, str):
ts = datetime.fromisoformat(ts)
# make pv and nwp data from GFS
# TODO move this to model
print("Making pv and nwp data")
nwp_xr = format_nwp_data(df=nwp_site_df, nwp_source=nwp_source, site=site)
pv_xr = make_pv_data(site=site, ts=ts)
# run model
print('Running model')
|
dir_path = os.path.dirname(os.path.realpath(__file__))
def run_forecast(pv_df: pd.DataFrame, nwp_df: pd.DataFrame, nwp_source="ICON") -> pd.DataFrame:
"""
Run the forecast from NWP data
:param pv_df: the PV site data. This should have columns timestamp, id, latitude, longitude, and capacity
:param nwp_df: all the nwp data for the site and location. This shoulw have the following rows
- timestamp: the timestamp of the site
- temperature_2m
- precipitation
- shortwave_radiation
- direct_radiation",
- cloudcover_low",
- cloudcover_mid",
- cloudcover_high",
maybe more
"""
# load model only once
model = load_model(f"{dir_path}/../models/model-0.3.0.pkl")
all_predictions = []
for i in range(len(pv_df)):
print(f"Running forecast for {i} of {len(pv_df)}")
pv_row = pv_df.iloc[i]
site = PVSite(
latitude=pv_row["latitude"],
longitude=pv_row["longitude"],
capacity_kwp=pv_row["capacity"],
)
nwp_site_df = nwp_df[
(nwp_df["pv_id"] == pv_row.pv_id) & (nwp_df["timestamp"] == pv_row.timestamp)
]
pv_id = pv_df["pv_id"][i]
ts = pv_df["timestamp"][i]
# format
for c in ["timestamp", "latitude", "longitude", "pv_id"]:
if c in nwp_site_df.columns:
nwp_site_df = nwp_site_df.drop(columns=c)
nwp_site_df.set_index("time", inplace=True, drop=True)
if isinstance(ts, str):
ts = datetime.fromisoformat(ts)
# make pv and nwp data from GFS
# TODO move this to model
print("Making pv and nwp data")
nwp_xr = format_nwp_data(df=nwp_site_df, nwp_source=nwp_source, site=site)
pv_xr = make_pv_data(site=site, ts=ts)
# run model
print('Running model') | pred_df = forecast_v1(nwp_source, nwp_xr, pv_xr, ts, model=model) | 3 | 2023-11-16 07:37:42+00:00 | 4k |
newcastleuniversity/DISPEL | tests/providers/generic/activity/test_turning.py | [
{
"identifier": "Turn",
"path": "dispel/providers/generic/activity/turning.py",
"snippet": "class Turn:\n \"\"\"Class to encapsulate turns and turn related gyroscope data.\n\n Parameters\n ----------\n start\n The start date time of the turn.\n end\n The end date time of the... | import pandas as pd
import pytest
from dispel.providers.generic.activity.turning import Turn, el_gohary_detect_turns | 1,662 | """Tests for :mod:`dispel.providers.generic.activity.turning`."""
@pytest.fixture
def example_turn_data():
"""Get example turn data."""
index = pd.date_range("now", periods=61, freq="20ms")
values = [0] * 10 + list(range(20)) + [20] + list(reversed(range(20))) + [0] * 10
return pd.Series(values, index=index)
def test_turn_expand(example_turn_data):
"""Test :meth:`dispel.providers.generic.activity.turning.Turn.expand`."""
index = example_turn_data.index
| """Tests for :mod:`dispel.providers.generic.activity.turning`."""
@pytest.fixture
def example_turn_data():
"""Get example turn data."""
index = pd.date_range("now", periods=61, freq="20ms")
values = [0] * 10 + list(range(20)) + [20] + list(reversed(range(20))) + [0] * 10
return pd.Series(values, index=index)
def test_turn_expand(example_turn_data):
"""Test :meth:`dispel.providers.generic.activity.turning.Turn.expand`."""
index = example_turn_data.index | turn = Turn(index[30], index[30], example_turn_data) | 0 | 2023-11-14 10:06:46+00:00 | 4k |
runDMCA/home-assistant-mazda | custom_components/mazda/pymazda/connection.py | [
{
"identifier": "decrypt_aes128cbc_buffer_to_str",
"path": "custom_components/mazda/pymazda/crypto_utils.py",
"snippet": "def decrypt_aes128cbc_buffer_to_str(data, key, iv): # noqa: D103\n cipher = Cipher(algorithms.AES(key.encode(\"ascii\")), modes.CBC(iv.encode(\"ascii\")))\n decryptor = cipher... | import asyncio # noqa: D100
import base64
import hashlib
import json
import logging
import ssl
import time
import aiohttp
from urllib.parse import urlencode
from .crypto_utils import (
decrypt_aes128cbc_buffer_to_str,
encrypt_aes128cbc_buffer_to_base64_str,
encrypt_rsaecbpkcs1_padding,
generate_usher_device_id_from_seed,
generate_uuid_from_seed,
)
from .exceptions import (
MazdaAccountLockedException,
MazdaAPIEncryptionException,
MazdaAuthenticationException,
MazdaConfigException,
MazdaException,
MazdaLoginFailedException,
MazdaRequestInProgressException,
MazdaTokenExpiredException,
)
from .sensordata.sensor_data_builder import SensorDataBuilder | 3,266 |
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ssl_context.load_default_certs()
ssl_context.set_ciphers(
"DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
)
REGION_CONFIG = {
"MNAO": {
"app_code": "202007270941270111799",
"base_url": "https://0cxo7m58.mazda.com/prod/",
"usher_url": "https://ptznwbh8.mazda.com/appapi/v1/",
},
"MME": {
"app_code": "202008100250281064816",
"base_url": "https://e9stj7g7.mazda.com/prod/",
"usher_url": "https://rz97suam.mazda.com/appapi/v1/",
},
"MJO": {
"app_code": "202009170613074283422",
"base_url": "https://wcs9p6wj.mazda.com/prod/",
"usher_url": "https://c5ulfwxr.mazda.com/appapi/v1/",
},
}
IV = "0102030405060708"
SIGNATURE_MD5 = "C383D8C4D279B78130AD52DC71D95CAA"
APP_PACKAGE_ID = "com.interrait.mymazda"
USER_AGENT_BASE_API = "MyMazda-Android/8.5.2"
USER_AGENT_USHER_API = "MyMazda/8.5.2 (Google Pixel 3a; Android 11)"
APP_OS = "Android"
APP_VERSION = "8.5.2"
USHER_SDK_VERSION = "11.3.0700.001"
MAX_RETRIES = 4
class Connection:
"""Main class for handling MyMazda API connection."""
def __init__(self, email, password, region, websession=None): # noqa: D107
self.email = email
self.password = password
if region in REGION_CONFIG:
region_config = REGION_CONFIG[region]
self.app_code = region_config["app_code"]
self.base_url = region_config["base_url"]
self.usher_url = region_config["usher_url"]
else:
raise MazdaConfigException("Invalid region")
|
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ssl_context.load_default_certs()
ssl_context.set_ciphers(
"DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
)
REGION_CONFIG = {
"MNAO": {
"app_code": "202007270941270111799",
"base_url": "https://0cxo7m58.mazda.com/prod/",
"usher_url": "https://ptznwbh8.mazda.com/appapi/v1/",
},
"MME": {
"app_code": "202008100250281064816",
"base_url": "https://e9stj7g7.mazda.com/prod/",
"usher_url": "https://rz97suam.mazda.com/appapi/v1/",
},
"MJO": {
"app_code": "202009170613074283422",
"base_url": "https://wcs9p6wj.mazda.com/prod/",
"usher_url": "https://c5ulfwxr.mazda.com/appapi/v1/",
},
}
IV = "0102030405060708"
SIGNATURE_MD5 = "C383D8C4D279B78130AD52DC71D95CAA"
APP_PACKAGE_ID = "com.interrait.mymazda"
USER_AGENT_BASE_API = "MyMazda-Android/8.5.2"
USER_AGENT_USHER_API = "MyMazda/8.5.2 (Google Pixel 3a; Android 11)"
APP_OS = "Android"
APP_VERSION = "8.5.2"
USHER_SDK_VERSION = "11.3.0700.001"
MAX_RETRIES = 4
class Connection:
"""Main class for handling MyMazda API connection."""
def __init__(self, email, password, region, websession=None): # noqa: D107
self.email = email
self.password = password
if region in REGION_CONFIG:
region_config = REGION_CONFIG[region]
self.app_code = region_config["app_code"]
self.base_url = region_config["base_url"]
self.usher_url = region_config["usher_url"]
else:
raise MazdaConfigException("Invalid region")
| self.base_api_device_id = generate_uuid_from_seed(email) | 4 | 2023-11-14 01:42:43+00:00 | 4k |
NevermindNilas/TheAnimeScripter | src/cugan/cugan.py | [
{
"identifier": "UpCunet2x",
"path": "src/cugan/cugan_arch.py",
"snippet": "class UpCunet2x(nn.Module): # 完美tile,全程无损\n def __init__(self, in_channels=3, out_channels=3):\n super(UpCunet2x, self).__init__()\n self.unet1 = UNet1(in_channels, out_channels, deconv=True)\n self.unet... | from .cugan_arch import UpCunet2x, UpCunet3x, UpCunet4x, UpCunet2x_fast
from realcugan_ncnn_py import Realcugan
import os
import requests
import torch
import torch.nn.functional as F | 1,897 |
class Cugan:
def __init__(self, upscale_method, upscale_factor, cugan_kind, half, width, height):
self.upscale_method = upscale_method
self.upscale_factor = upscale_factor
self.cugan_kind = cugan_kind
self.half = half
self.width = width
self.height = height
self.handle_models()
def handle_models(self):
if self.upscale_method == "shufflecugan":
self.model = UpCunet2x_fast(in_channels=3, out_channels=3)
self.filename = "sudo_shuffle_cugan_9.584.969.pth"
else:
model_path_prefix = "cugan"
model_path_suffix = "-latest"
model_path_middle = f"up{self.upscale_factor}x"
|
class Cugan:
def __init__(self, upscale_method, upscale_factor, cugan_kind, half, width, height):
self.upscale_method = upscale_method
self.upscale_factor = upscale_factor
self.cugan_kind = cugan_kind
self.half = half
self.width = width
self.height = height
self.handle_models()
def handle_models(self):
if self.upscale_method == "shufflecugan":
self.model = UpCunet2x_fast(in_channels=3, out_channels=3)
self.filename = "sudo_shuffle_cugan_9.584.969.pth"
else:
model_path_prefix = "cugan"
model_path_suffix = "-latest"
model_path_middle = f"up{self.upscale_factor}x" | model_map = {2: UpCunet2x, 3: UpCunet3x, 4: UpCunet4x} | 1 | 2023-11-14 22:10:11+00:00 | 4k |
ubertidavide/fastbots | tests/test_firefox_bot.py | [
{
"identifier": "FirefoxBot",
"path": "fastbots/firefox_bot.py",
"snippet": "class FirefoxBot(Bot):\n \"\"\"\n Firefox Bot\n\n Class representing the Firefox Bot implementation.\n\n Attributes:\n _driver (WebDriver): The WebDriver instance for Firefox.\n _wait (WebDriverWait): ... | import pytest
from configparser import ConfigParser
from pathlib import Path
from seleniumwire.webdriver import Firefox
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.webdriver.remote.webdriver import WebDriver
from fastbots.firefox_bot import FirefoxBot
from fastbots import config, Payload | 2,009 |
@pytest.fixture
def bot():
with FirefoxBot() as bot:
yield bot
def test_driver(bot):
assert isinstance(bot.driver, WebDriver)
def test_wait(bot):
assert isinstance(bot.wait, WebDriverWait)
def test_payload(bot):
|
@pytest.fixture
def bot():
with FirefoxBot() as bot:
yield bot
def test_driver(bot):
assert isinstance(bot.driver, WebDriver)
def test_wait(bot):
assert isinstance(bot.wait, WebDriverWait)
def test_payload(bot): | assert isinstance(bot.payload, Payload) | 2 | 2023-11-16 00:12:09+00:00 | 4k |
intel/llm-on-ray | rlhf/rl_algo/ppo/ppo_rlhf.py | [
{
"identifier": "generate_response",
"path": "common/agentenv/rlhf_env.py",
"snippet": "def generate_response(\n model: torch.nn.Module, \n *, \n input_ids: torch.tensor, \n max_length:int, \n eos_token_id: int\n):\n \"\"\"Generate a response using the model.\"\"\"\n generated_seque... | import torch
import numpy as np
import sys, os
from typing import List, Optional, Type, Union, TYPE_CHECKING
from ray.rllib.algorithms import Algorithm, AlgorithmConfig
from ray.rllib.algorithms.ppo import PPO
from ray.rllib.policy.policy import Policy
from ray.rllib.policy.sample_batch import SampleBatch, concat_samples, DEFAULT_POLICY_ID
from ray.rllib.core.learner.learner_group import LearnerGroup
from ray.rllib.evaluation.postprocessing import Postprocessing
from ray.rllib.utils.metrics import (
NUM_AGENT_STEPS_SAMPLED, NUM_ENV_STEPS_SAMPLED, LEARNER_STATS_KEY
)
from ray.rllib.evaluation.metrics import RolloutMetrics
from common.agentenv.rlhf_env import generate_response
from .rlhf_buffer import Buffer, BufferItem
from ray.rllib.evaluation.metrics import (
collect_episodes,
collect_metrics,
summarize_episodes,
) | 1,886 |
sys.path.append(os.path.join(os.path.dirname(__file__), '../../../'))
class RLHFSampler:
"""This sampler is a local sampler for LLMEnv.
The underlying env is an LLMEnv which creates a batch of prompts and the agent has
to generate a response for each prompt. Then the env evaluate those responses and
returns a reward signal.
"""
def __init__(self, module, env):
self._env = env
self._module = module
self.max_generation_length = self._env.max_generation_length
def sample(self, batch_size: int, **kwargs) -> SampleBatch:
# TODO (Kourosh): Can we use batch inference here?
|
sys.path.append(os.path.join(os.path.dirname(__file__), '../../../'))
class RLHFSampler:
"""This sampler is a local sampler for LLMEnv.
The underlying env is an LLMEnv which creates a batch of prompts and the agent has
to generate a response for each prompt. Then the env evaluate those responses and
returns a reward signal.
"""
def __init__(self, module, env):
self._env = env
self._module = module
self.max_generation_length = self._env.max_generation_length
def sample(self, batch_size: int, **kwargs) -> SampleBatch:
# TODO (Kourosh): Can we use batch inference here? | batches = Buffer() | 1 | 2023-11-13 05:08:21+00:00 | 4k |
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 | 2,141 | '''
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]
responses_dict = dict()
for _, api in enumerate(apis_reviewer):
records_thisapi = []
for prompt in prompts:
response = api.chat(prompt['prompt'])
result = parse_response(response, self.parser_type, self.nominal_list, self.nominal_ticks)
item = {"response": response, "result": result}
item.update(prompt)
records_thisapi.append(item)
responses_dict[api.model_name] = records_thisapi
return responses_dict
def peer_review_batch(self, reviewers, prompts) -> None:
'''
used in full evaluate strategy
reviewers: LLM config list
save the evaluate responses of each reviewer on seperated file
'''
apis_reviewer = [Auto_API.instantiate_api(config_api['api_type'], config_api) for config_api in reviewers]
os.makedirs(f"{self.save_dir}/evaluation_responses", exist_ok=True)
for _, api in enumerate(apis_reviewer):
path_out = f"{self.save_dir}/evaluation_responses/{self.task_name}_{api.model_name}.json"
if os.path.exists(path_out):
data = open(path_out).readlines()
else:
data = []
if len(data) < len(prompts):
fout = open(path_out, 'w')
for line in data:
fout.write(line)
for prompt in prompts[len(data):]:
response_orig = api.chat(prompt['prompt'])
result_parse = parse_response(response_orig, self.parser_type, self.nominal_list, self.nominal_ticks)
line = {"response": response_orig, 'result': result_parse}
line.update(prompt)
line = json.dumps(line)
data.append(line)
fout.write(line + '\n')
fout.close()
return None
class EvalDataLoader:
def __init__(self, args) -> None:
self.task_name = args['task_name']
self.mode = args['mode'] # pointwise, pairwise
'''
In pointwise mode, the prompt is required to include key "#source" (the LLM to generate the response). The expected evaulate response is an integer or float number;
In pairwise mode, the prompt is required to include key "#source1" (the LLM 1 to generate the response) and key "#source2" (the LLM 2 to generate the response). The expected evaluate response is three possible token, meaning -1 (1 is better), 0 (tied), 1 (2 is better) respectively
'''
# self.dirpath = args['dirpath_response'] # the load path for the response results
self.save_dir = args['save_dir'] # the evaluation result save dir, In full strategy, the evaluation save filename = [save_dir] / evaluation_responses / [task_name]_[model_name].json, each line is one result with json {modelA: modelA_name, modelB: modelB_name, task_id: task_id, response: str, result: int/float}; in gaming strategy, the evaluation save filename = [save_dir] / evaluation_responses / [task_name]__[game strategy].json, each line is one compete result with json {modelA: modelA_name, modelB: modelB_name, task_ids: list, response: {reviewer_name: {responses: list, results: list} for each reviewer}}
self.path_evaluate_prompt = args['path_evaluate_prompt'] if 'path_evaluate_prompt' in args else None # the path of evaluate prompt template. In the prompt template, using {{key}} for the replacement of the key. For example, in the prompt "You need answer a question: {{question}}", the "question" field need to be included in the data
### load task data and response data
path_config_task_data = args['config_task_data']
if not os.path.exists(path_config_task_data):
raise FileExistsError("Load task_data config failed: file not exist!")
config_task = yaml.load(open(path_config_task_data, 'r'), Loader=yaml.FullLoader) # single task config
| '''
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]
responses_dict = dict()
for _, api in enumerate(apis_reviewer):
records_thisapi = []
for prompt in prompts:
response = api.chat(prompt['prompt'])
result = parse_response(response, self.parser_type, self.nominal_list, self.nominal_ticks)
item = {"response": response, "result": result}
item.update(prompt)
records_thisapi.append(item)
responses_dict[api.model_name] = records_thisapi
return responses_dict
def peer_review_batch(self, reviewers, prompts) -> None:
'''
used in full evaluate strategy
reviewers: LLM config list
save the evaluate responses of each reviewer on seperated file
'''
apis_reviewer = [Auto_API.instantiate_api(config_api['api_type'], config_api) for config_api in reviewers]
os.makedirs(f"{self.save_dir}/evaluation_responses", exist_ok=True)
for _, api in enumerate(apis_reviewer):
path_out = f"{self.save_dir}/evaluation_responses/{self.task_name}_{api.model_name}.json"
if os.path.exists(path_out):
data = open(path_out).readlines()
else:
data = []
if len(data) < len(prompts):
fout = open(path_out, 'w')
for line in data:
fout.write(line)
for prompt in prompts[len(data):]:
response_orig = api.chat(prompt['prompt'])
result_parse = parse_response(response_orig, self.parser_type, self.nominal_list, self.nominal_ticks)
line = {"response": response_orig, 'result': result_parse}
line.update(prompt)
line = json.dumps(line)
data.append(line)
fout.write(line + '\n')
fout.close()
return None
class EvalDataLoader:
def __init__(self, args) -> None:
self.task_name = args['task_name']
self.mode = args['mode'] # pointwise, pairwise
'''
In pointwise mode, the prompt is required to include key "#source" (the LLM to generate the response). The expected evaulate response is an integer or float number;
In pairwise mode, the prompt is required to include key "#source1" (the LLM 1 to generate the response) and key "#source2" (the LLM 2 to generate the response). The expected evaluate response is three possible token, meaning -1 (1 is better), 0 (tied), 1 (2 is better) respectively
'''
# self.dirpath = args['dirpath_response'] # the load path for the response results
self.save_dir = args['save_dir'] # the evaluation result save dir, In full strategy, the evaluation save filename = [save_dir] / evaluation_responses / [task_name]_[model_name].json, each line is one result with json {modelA: modelA_name, modelB: modelB_name, task_id: task_id, response: str, result: int/float}; in gaming strategy, the evaluation save filename = [save_dir] / evaluation_responses / [task_name]__[game strategy].json, each line is one compete result with json {modelA: modelA_name, modelB: modelB_name, task_ids: list, response: {reviewer_name: {responses: list, results: list} for each reviewer}}
self.path_evaluate_prompt = args['path_evaluate_prompt'] if 'path_evaluate_prompt' in args else None # the path of evaluate prompt template. In the prompt template, using {{key}} for the replacement of the key. For example, in the prompt "You need answer a question: {{question}}", the "question" field need to be included in the data
### load task data and response data
path_config_task_data = args['config_task_data']
if not os.path.exists(path_config_task_data):
raise FileExistsError("Load task_data config failed: file not exist!")
config_task = yaml.load(open(path_config_task_data, 'r'), Loader=yaml.FullLoader) # single task config | data_loader = DataLoader(config_task) # a task data loader | 0 | 2023-11-16 18:40:23+00:00 | 4k |
python-thread/thread | src/thread/decorators/_threaded.py | [
{
"identifier": "Thread",
"path": "src/thread/thread.py",
"snippet": "class Thread(threading.Thread, Generic[_Target_P, _Target_T]):\n \"\"\"\n Wraps python's `threading.Thread` class\n ---------------------------------------\n\n Type-Safe and provides more functionality on top\n \"\"\"\n\n status... | from functools import wraps
from ..thread import Thread
from .._types import Overflow_In, Data_In
from typing import Callable, Mapping, Sequence, Optional, Union, overload
from typing_extensions import ParamSpec, TypeVar | 2,383 | """
## Threaded
Documentation: https://thread.ngjx.org
"""
T = TypeVar('T')
P = ParamSpec('P')
TargetFunction = Callable[P, T]
NoParamReturn = Callable[P, Thread[P, T]]
WithParamReturn = Callable[[TargetFunction[P, T]], NoParamReturn[P, T]]
FullParamReturn = Callable[P, Thread[P, T]]
@overload
def threaded(__function: TargetFunction[P, T]) -> NoParamReturn[P, T]: ...
@overload
def threaded(
*,
| """
## Threaded
Documentation: https://thread.ngjx.org
"""
T = TypeVar('T')
P = ParamSpec('P')
TargetFunction = Callable[P, T]
NoParamReturn = Callable[P, Thread[P, T]]
WithParamReturn = Callable[[TargetFunction[P, T]], NoParamReturn[P, T]]
FullParamReturn = Callable[P, Thread[P, T]]
@overload
def threaded(__function: TargetFunction[P, T]) -> NoParamReturn[P, T]: ...
@overload
def threaded(
*, | args: Sequence[Data_In] = (), | 1 | 2023-11-12 21:01:21+00:00 | 4k |
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,697 | #!/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)
def all(self, cls=None):
"""returns a dictionary
Return:
returns a dictionary of __object
"""
dic = {}
if cls:
if type(cls) is str:
cls = eval(cls)
query = self.__session.query(cls)
for elem in query:
key = "{}.{}".format(type(elem).__name__, elem.id)
dic[key] = elem
else:
| #!/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)
def all(self, cls=None):
"""returns a dictionary
Return:
returns a dictionary of __object
"""
dic = {}
if cls:
if type(cls) is str:
cls = eval(cls)
query = self.__session.query(cls)
for elem in query:
key = "{}.{}".format(type(elem).__name__, elem.id)
dic[key] = elem
else: | lista = [State, City, User, Place, Review, Amenity] | 6 | 2023-11-17 07:59:13+00:00 | 4k |
believethehype/nostrdvm | nostr_dvm/tasks/advanced_search.py | [
{
"identifier": "DVMTaskInterface",
"path": "nostr_dvm/interfaces/dvmtaskinterface.py",
"snippet": "class DVMTaskInterface:\n NAME: str\n KIND: int\n TASK: str = \"\"\n FIX_COST: float = 0\n PER_UNIT_COST: float = 0\n PRIVATE_KEY: str\n PUBLIC_KEY: str\n DVM = DVM\n SUPPORTS_E... | import json
import os
from datetime import timedelta
from nostr_sdk import Client, Timestamp, PublicKey, Tag, Keys, Options, SecretKey, ClientSigner
from nostr_dvm.interfaces.dvmtaskinterface import DVMTaskInterface, process_venv
from nostr_dvm.utils.admin_utils import AdminConfig
from nostr_dvm.utils.definitions import EventDefinitions
from nostr_dvm.utils.dvmconfig import DVMConfig, build_default_config
from nostr_dvm.utils.nip89_utils import NIP89Config, check_and_set_d_tag
from nostr_dvm.utils.output_utils import post_process_list_to_events
from nostr_sdk import Filter | 3,385 |
"""
This File contains a Module to search for notes
Accepted Inputs: a search query
Outputs: A list of events
Params: None
"""
class AdvancedSearch(DVMTaskInterface):
KIND: int = EventDefinitions.KIND_NIP90_CONTENT_SEARCH
TASK: str = "search-content"
FIX_COST: float = 0
dvm_config: DVMConfig
dependencies = [("nostr-dvm", "nostr-dvm")]
def __init__(self, name, dvm_config: DVMConfig, nip89config: NIP89Config,
|
"""
This File contains a Module to search for notes
Accepted Inputs: a search query
Outputs: A list of events
Params: None
"""
class AdvancedSearch(DVMTaskInterface):
KIND: int = EventDefinitions.KIND_NIP90_CONTENT_SEARCH
TASK: str = "search-content"
FIX_COST: float = 0
dvm_config: DVMConfig
dependencies = [("nostr-dvm", "nostr-dvm")]
def __init__(self, name, dvm_config: DVMConfig, nip89config: NIP89Config, | admin_config: AdminConfig = None, options=None): | 2 | 2023-11-17 18:32:56+00:00 | 4k |
zouXH-god/meme_web | meme_generator/meme.py | [
{
"identifier": "ArgModelMismatch",
"path": "meme_generator/exception.py",
"snippet": "class ArgModelMismatch(ArgMismatch):\n status_code: int = 552\n\n def __init__(self, meme_key: str, error_message: str):\n self.error_message = error_message\n message = f\"Argument model validatio... | import copy
from argparse import ArgumentError, ArgumentParser
from contextvars import ContextVar
from dataclasses import dataclass, field
from io import BytesIO
from pathlib import Path
from typing import (
IO,
Any,
Awaitable,
Callable,
Dict,
List,
Literal,
Optional,
Type,
TypeVar,
Union,
cast,
)
from pil_utils import BuildImage
from pydantic import BaseModel, ValidationError
from .exception import (
ArgModelMismatch,
ArgParserExit,
ImageNumberMismatch,
OpenImageFailed,
ParserExit,
TextNumberMismatch,
TextOrNameNotEnough,
)
from .utils import is_coroutine_callable, random_image, random_text, run_sync | 2,013 |
class UserInfo(BaseModel):
name: str = ""
gender: Literal["male", "female", "unknown"] = "unknown"
class MemeArgsModel(BaseModel):
user_infos: List[UserInfo] = []
ArgsModel = TypeVar("ArgsModel", bound=MemeArgsModel)
MemeFunction = Union[
Callable[[List[BuildImage], List[str], ArgsModel], BytesIO],
Callable[[List[BuildImage], List[str], ArgsModel], Awaitable[BytesIO]],
]
parser_message: ContextVar[str] = ContextVar("parser_message")
class MemeArgsParser(ArgumentParser):
"""`shell_like` 命令参数解析器,解析出错时不会退出程序。
用法:
用法与 `argparse.ArgumentParser` 相同,
参考文档: [argparse](https://docs.python.org/3/library/argparse.html)
"""
def _print_message(self, message: str, file: Optional[IO[str]] = None):
if (msg := parser_message.get(None)) is not None:
parser_message.set(msg + message)
else:
super()._print_message(message, file)
def exit(self, status: int = 0, message: Optional[str] = None):
if message:
self._print_message(message)
raise ParserExit(status=status, error_message=parser_message.get(None))
@dataclass
class MemeArgsType:
parser: MemeArgsParser
model: Type[MemeArgsModel]
instances: List[MemeArgsModel] = field(default_factory=list)
@dataclass
class MemeParamsType:
min_images: int = 0
max_images: int = 0
min_texts: int = 0
max_texts: int = 0
default_texts: List[str] = field(default_factory=list)
args_type: Optional[MemeArgsType] = None
@dataclass
class Meme:
key: str
function: MemeFunction
params_type: MemeParamsType
keywords: List[str] = field(default_factory=list)
patterns: List[str] = field(default_factory=list)
async def __call__(
self,
*,
images: Union[List[str], List[Path], List[bytes], List[BytesIO]] = [],
texts: List[str] = [],
args: Dict[str, Any] = {},
) -> BytesIO:
if not (
self.params_type.min_images <= len(images) <= self.params_type.max_images
):
raise ImageNumberMismatch(
self.key, self.params_type.min_images, self.params_type.max_images
)
if not (self.params_type.min_texts <= len(texts) <= self.params_type.max_texts):
raise TextNumberMismatch(
self.key, self.params_type.min_texts, self.params_type.max_texts
)
if args_type := self.params_type.args_type:
args_model = args_type.model
else:
args_model = MemeArgsModel
try:
model = args_model.parse_obj(args)
except ValidationError as e:
raise ArgModelMismatch(self.key, str(e))
imgs: List[BuildImage] = []
try:
for image in images:
if isinstance(image, bytes):
image = BytesIO(image)
imgs.append(BuildImage.open(image))
except Exception as e:
|
class UserInfo(BaseModel):
name: str = ""
gender: Literal["male", "female", "unknown"] = "unknown"
class MemeArgsModel(BaseModel):
user_infos: List[UserInfo] = []
ArgsModel = TypeVar("ArgsModel", bound=MemeArgsModel)
MemeFunction = Union[
Callable[[List[BuildImage], List[str], ArgsModel], BytesIO],
Callable[[List[BuildImage], List[str], ArgsModel], Awaitable[BytesIO]],
]
parser_message: ContextVar[str] = ContextVar("parser_message")
class MemeArgsParser(ArgumentParser):
"""`shell_like` 命令参数解析器,解析出错时不会退出程序。
用法:
用法与 `argparse.ArgumentParser` 相同,
参考文档: [argparse](https://docs.python.org/3/library/argparse.html)
"""
def _print_message(self, message: str, file: Optional[IO[str]] = None):
if (msg := parser_message.get(None)) is not None:
parser_message.set(msg + message)
else:
super()._print_message(message, file)
def exit(self, status: int = 0, message: Optional[str] = None):
if message:
self._print_message(message)
raise ParserExit(status=status, error_message=parser_message.get(None))
@dataclass
class MemeArgsType:
parser: MemeArgsParser
model: Type[MemeArgsModel]
instances: List[MemeArgsModel] = field(default_factory=list)
@dataclass
class MemeParamsType:
min_images: int = 0
max_images: int = 0
min_texts: int = 0
max_texts: int = 0
default_texts: List[str] = field(default_factory=list)
args_type: Optional[MemeArgsType] = None
@dataclass
class Meme:
key: str
function: MemeFunction
params_type: MemeParamsType
keywords: List[str] = field(default_factory=list)
patterns: List[str] = field(default_factory=list)
async def __call__(
self,
*,
images: Union[List[str], List[Path], List[bytes], List[BytesIO]] = [],
texts: List[str] = [],
args: Dict[str, Any] = {},
) -> BytesIO:
if not (
self.params_type.min_images <= len(images) <= self.params_type.max_images
):
raise ImageNumberMismatch(
self.key, self.params_type.min_images, self.params_type.max_images
)
if not (self.params_type.min_texts <= len(texts) <= self.params_type.max_texts):
raise TextNumberMismatch(
self.key, self.params_type.min_texts, self.params_type.max_texts
)
if args_type := self.params_type.args_type:
args_model = args_type.model
else:
args_model = MemeArgsModel
try:
model = args_model.parse_obj(args)
except ValidationError as e:
raise ArgModelMismatch(self.key, str(e))
imgs: List[BuildImage] = []
try:
for image in images:
if isinstance(image, bytes):
image = BytesIO(image)
imgs.append(BuildImage.open(image))
except Exception as e: | raise OpenImageFailed(str(e)) | 3 | 2023-11-12 12:31:53+00:00 | 4k |
OKC13/General-Documents-Layout-parser | hubconf.py | [
{
"identifier": "Model",
"path": "models/yolo.py",
"snippet": "class Model(nn.Module):\n def __init__(self, model_cfg='yolov5s.yaml', ch=3, nc=None): # model, input channels, number of classes\n super(Model, self).__init__()\n if type(model_cfg) is dict:\n self.md = model_cf... | import torch
from models.yolo import Model
from utils import google_utils | 1,705 | """File for accessing YOLOv5 via PyTorch Hub https://pytorch.org/hub/
Usage:
import torch
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True, channels=3, classes=80)
"""
dependencies = ['torch', 'yaml']
def create(name, pretrained, channels, classes):
"""Creates a specified YOLOv5 model
Arguments:
name (str): name of model, i.e. 'yolov5s'
pretrained (bool): load pretrained weights into the model
channels (int): number of input channels
classes (int): number of model classes
Returns:
pytorch model
"""
model = Model('/home/wangjiawei/yolov3/YOLOv5/models/%s.yaml' % name, channels, classes)
if pretrained:
ckpt = '/home/wangjiawei/yolov3/YOLOv5/weights/%s.pt' % name # checkpoint filename
| """File for accessing YOLOv5 via PyTorch Hub https://pytorch.org/hub/
Usage:
import torch
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True, channels=3, classes=80)
"""
dependencies = ['torch', 'yaml']
def create(name, pretrained, channels, classes):
"""Creates a specified YOLOv5 model
Arguments:
name (str): name of model, i.e. 'yolov5s'
pretrained (bool): load pretrained weights into the model
channels (int): number of input channels
classes (int): number of model classes
Returns:
pytorch model
"""
model = Model('/home/wangjiawei/yolov3/YOLOv5/models/%s.yaml' % name, channels, classes)
if pretrained:
ckpt = '/home/wangjiawei/yolov3/YOLOv5/weights/%s.pt' % name # checkpoint filename | google_utils.attempt_download(ckpt) # download if not found locally | 1 | 2023-11-16 08:37:10+00:00 | 4k |
tensorpix/benchmarking-cv-models | src/train.py | [
{
"identifier": "log",
"path": "src/log.py",
"snippet": "def setup_custom_logger(name: str = \"benchmark\"):"
},
{
"identifier": "BenchmarkCallback",
"path": "src/callbacks.py",
"snippet": "class BenchmarkCallback(Callback):\n def __init__(\n self,\n model_name: str,\n ... | import argparse
import segmentation_models_pytorch as smp
import torch
from lightning import Trainer
from pip._internal.operations import freeze
from torch.utils.data import DataLoader
from torchvision.models import (
convnext_base,
efficientnet_v2_m,
mobilenet_v3_large,
resnet50,
resnext50_32x4d,
swin_b,
vgg16,
vit_b_16,
)
from src import log
from src.callbacks import BenchmarkCallback
from src.data.in_memory_dataset import InMemoryDataset
from src.models.lightning_modules import LitClassification | 1,931 |
logger = log.setup_custom_logger()
ARCHITECTURES = {
"resnet50": resnet50,
"convnext": convnext_base,
"vgg16": vgg16,
"efficient_net_v2": efficientnet_v2_m,
"mobilenet_v3": mobilenet_v3_large,
"resnext50": resnext50_32x4d,
"swin": swin_b,
"vit": vit_b_16,
"unet_resnet50": smp.Unet
# TODO "ssd_vgg16": ssd300_vgg16,
# TODO "fasterrcnn_resnet50_v2": fasterrcnn_resnet50_fpn_v2,
}
def print_requirements():
pkgs = freeze.freeze()
for pkg in pkgs:
logger.info(pkg)
def main(args):
if args.list_requirements:
print_requirements()
args_dict = vars(args)
logger.info(f"User Arguments {args_dict}")
dataset = InMemoryDataset(width=args.width, height=args.width)
data_loader = DataLoader(
dataset,
num_workers=args.n_workers,
batch_size=args.batch_size,
shuffle=True,
pin_memory=True,
drop_last=True,
)
trainer = Trainer(
accelerator=args.accelerator,
strategy="ddp",
precision=args.precision,
limit_train_batches=args.n_iters + args.warmup_steps,
max_epochs=1,
logger=False,
enable_checkpointing=False,
callbacks=[
BenchmarkCallback(
warmup_steps=args.warmup_steps,
model_name=args.model,
precision=args.precision,
workers=args.n_workers,
)
],
devices=torch.cuda.device_count(),
)
if args.model in ARCHITECTURES:
if args.model == "unet_resnet50":
model = ARCHITECTURES[args.model](
encoder_name="resnet50", encoder_weights=None
)
else:
model = ARCHITECTURES[args.model]()
else:
raise ValueError("Architecture not supported.")
|
logger = log.setup_custom_logger()
ARCHITECTURES = {
"resnet50": resnet50,
"convnext": convnext_base,
"vgg16": vgg16,
"efficient_net_v2": efficientnet_v2_m,
"mobilenet_v3": mobilenet_v3_large,
"resnext50": resnext50_32x4d,
"swin": swin_b,
"vit": vit_b_16,
"unet_resnet50": smp.Unet
# TODO "ssd_vgg16": ssd300_vgg16,
# TODO "fasterrcnn_resnet50_v2": fasterrcnn_resnet50_fpn_v2,
}
def print_requirements():
pkgs = freeze.freeze()
for pkg in pkgs:
logger.info(pkg)
def main(args):
if args.list_requirements:
print_requirements()
args_dict = vars(args)
logger.info(f"User Arguments {args_dict}")
dataset = InMemoryDataset(width=args.width, height=args.width)
data_loader = DataLoader(
dataset,
num_workers=args.n_workers,
batch_size=args.batch_size,
shuffle=True,
pin_memory=True,
drop_last=True,
)
trainer = Trainer(
accelerator=args.accelerator,
strategy="ddp",
precision=args.precision,
limit_train_batches=args.n_iters + args.warmup_steps,
max_epochs=1,
logger=False,
enable_checkpointing=False,
callbacks=[
BenchmarkCallback(
warmup_steps=args.warmup_steps,
model_name=args.model,
precision=args.precision,
workers=args.n_workers,
)
],
devices=torch.cuda.device_count(),
)
if args.model in ARCHITECTURES:
if args.model == "unet_resnet50":
model = ARCHITECTURES[args.model](
encoder_name="resnet50", encoder_weights=None
)
else:
model = ARCHITECTURES[args.model]()
else:
raise ValueError("Architecture not supported.")
| model = LitClassification(model=model) | 3 | 2023-11-10 11:45:09+00:00 | 4k |
embrake/Aquilify | aquilify/core/__status.py | [
{
"identifier": "NotFound",
"path": "aquilify/exception/base.py",
"snippet": "class NotFound(Response, HTTPException):\n def __init__(self, status_code=404):\n super().__init__(error404(), status_code=status_code, content_type=\"text/html\")"
},
{
"identifier": "Unauthorized",
"pat... | from ..exception.base import (
NotFound, Unauthorized, Forbidden, BadGateway, InternalServerError, MethodNotAllowed, BadRequest,
NotAcceptable, ProxyAuthenticationRequired, RequestTimeout, Conflict, Gone, LengthRequired, PreconditionFailed,
RequestURITooLong, UnsupportedMediaType, RequestedRangeNotSatisfiable, ExpectationFailed, UnprocessableEntity,
MisdirectedRequest, Locked, FailedDependency, UpgradeRequired, TooManyRequests, RequestHeaderFieldsTooLarge,
UnavailableForLegalReasons, ServiceUnavailable, NotImplemented,GatewayTimeout, HTTPVersionNotSupported,
VariantAlsoNegotiates,InsufficientStorage, LoopDetected, NotExtended, NetworkAuthenticationRequired, PaymentRequired,
PayloadTooLarge, ImATeapot, PreconditionRequired
) | 3,045 |
exception_dict = {
400: BadRequest,
401: Unauthorized,
402: PaymentRequired,
403: Forbidden,
404: NotFound,
405: MethodNotAllowed,
406: NotAcceptable,
407: ProxyAuthenticationRequired,
408: RequestTimeout,
409: Conflict,
410: Gone,
411: LengthRequired,
412: PreconditionFailed,
413: PayloadTooLarge,
414: RequestURITooLong,
415: UnsupportedMediaType,
416: RequestedRangeNotSatisfiable,
|
exception_dict = {
400: BadRequest,
401: Unauthorized,
402: PaymentRequired,
403: Forbidden,
404: NotFound,
405: MethodNotAllowed,
406: NotAcceptable,
407: ProxyAuthenticationRequired,
408: RequestTimeout,
409: Conflict,
410: Gone,
411: LengthRequired,
412: PreconditionFailed,
413: PayloadTooLarge,
414: RequestURITooLong,
415: UnsupportedMediaType,
416: RequestedRangeNotSatisfiable, | 417: ExpectationFailed, | 17 | 2023-11-16 08:26:02+00:00 | 4k |
Viicos/django-autotyping | src/django_autotyping/stubbing/codemods/create_overload_codemod.py | [
{
"identifier": "InsertAfterImportsVisitor",
"path": "src/django_autotyping/stubbing/codemods/base.py",
"snippet": "class InsertAfterImportsVisitor(ContextAwareTransformer):\n \"\"\"Insert a list of statements after imports.\"\"\"\n\n CONTEXT_KEY = \"InsertAfterImportsVisitor\"\n\n @classmethod... | from typing import TYPE_CHECKING, cast
from django.db.models import Field
from libcst import helpers
from libcst.codemod import CodemodContext
from libcst.metadata import ScopeProvider
from django_autotyping.typing import FlattenFunctionDef
from .base import InsertAfterImportsVisitor, StubVisitorBasedCodemod
from .constants import OVERLOAD_DECORATOR
from .utils import TypedDictAttribute, build_typed_dict, get_param
from ..django_context import DjangoStubbingContext
import libcst as cst
import libcst.matchers as m | 2,346 | from __future__ import annotations
if TYPE_CHECKING:
# Matchers:
MANAGER_QS_CLASS_DEF_MATCHER = m.ClassDef(
name=m.SaveMatchedNode(m.Name("BaseManager") | m.Name("_QuerySet"), "cls_name")
)
"""Matches the `BaseManager` and `_QuerySet` class definitions."""
MODEL_CLASS_DEF_MATCHER = m.ClassDef(name=m.SaveMatchedNode(m.Name("Model"), "cls_name"))
"""Matches the `Model` class definition."""
CREATE_DEF_MATCHER = m.FunctionDef(name=m.Name("create") | m.Name("acreate"))
"""Matches the `create` and `acreate` method definitions."""
INIT_DEF_MATCHER = m.FunctionDef(name=m.Name("__init__"))
"""Matches the `__init__` method definition."""
class CreateOverloadCodemod(StubVisitorBasedCodemod):
"""A codemod that will add overloads to methods creating an instance of a model.
**Rule identifier**: `DJAS002`.
**Related settings**:
-[`MODEL_FIELDS_OPTIONAL`][django_autotyping.app_settings.StubsGenerationSettings.MODEL_FIELDS_OPTIONAL].
```python
MyModel(...) # Signature is provided.
MyModel.objects.create(...) # Signature is provided.
```
??? abstract "Implementation"
This codemod makes use of the [PEP 692][pep-0692]. If your type checker/LSP supports it,
documentation is provided for each field if [`help_text`][django.db.models.Field.help_text] was set.
"""
METADATA_DEPENDENCIES = {ScopeProvider}
STUB_FILES = {"db/models/manager.pyi", "db/models/query.pyi", "db/models/base.pyi"}
def __init__(self, context: CodemodContext) -> None:
super().__init__(context)
self.add_model_imports()
model_typed_dicts = _build_model_kwargs(self.django_context, self.stubs_settings.MODEL_FIELDS_OPTIONAL)
| from __future__ import annotations
if TYPE_CHECKING:
# Matchers:
MANAGER_QS_CLASS_DEF_MATCHER = m.ClassDef(
name=m.SaveMatchedNode(m.Name("BaseManager") | m.Name("_QuerySet"), "cls_name")
)
"""Matches the `BaseManager` and `_QuerySet` class definitions."""
MODEL_CLASS_DEF_MATCHER = m.ClassDef(name=m.SaveMatchedNode(m.Name("Model"), "cls_name"))
"""Matches the `Model` class definition."""
CREATE_DEF_MATCHER = m.FunctionDef(name=m.Name("create") | m.Name("acreate"))
"""Matches the `create` and `acreate` method definitions."""
INIT_DEF_MATCHER = m.FunctionDef(name=m.Name("__init__"))
"""Matches the `__init__` method definition."""
class CreateOverloadCodemod(StubVisitorBasedCodemod):
"""A codemod that will add overloads to methods creating an instance of a model.
**Rule identifier**: `DJAS002`.
**Related settings**:
-[`MODEL_FIELDS_OPTIONAL`][django_autotyping.app_settings.StubsGenerationSettings.MODEL_FIELDS_OPTIONAL].
```python
MyModel(...) # Signature is provided.
MyModel.objects.create(...) # Signature is provided.
```
??? abstract "Implementation"
This codemod makes use of the [PEP 692][pep-0692]. If your type checker/LSP supports it,
documentation is provided for each field if [`help_text`][django.db.models.Field.help_text] was set.
"""
METADATA_DEPENDENCIES = {ScopeProvider}
STUB_FILES = {"db/models/manager.pyi", "db/models/query.pyi", "db/models/base.pyi"}
def __init__(self, context: CodemodContext) -> None:
super().__init__(context)
self.add_model_imports()
model_typed_dicts = _build_model_kwargs(self.django_context, self.stubs_settings.MODEL_FIELDS_OPTIONAL) | InsertAfterImportsVisitor.insert_after_imports(context, model_typed_dicts) | 0 | 2023-11-11 20:42:05+00:00 | 4k |
IBM/oper8 | tests/watch_manager/python_watch_manager/filters/test_filters.py | [
{
"identifier": "KubeEventType",
"path": "oper8/deploy_manager/kube_event.py",
"snippet": "class KubeEventType(Enum):\n \"\"\"Enum for all possible kubernetes event types\"\"\"\n\n DELETED = \"DELETED\"\n MODIFIED = \"MODIFIED\"\n ADDED = \"ADDED\""
},
{
"identifier": "ReadyReason",
... | from oper8.deploy_manager.kube_event import KubeEventType
from oper8.status import ReadyReason, make_application_status
from oper8.test_helpers.pwm_helpers import make_managed_object
from oper8.watch_manager.python_watch_manager.filters.filters import (
AnnotationFilter,
CreationDeletionFilter,
DependentWatchFilter,
GenerationFilter,
LabelFilter,
NoGenerationFilter,
PauseFilter,
ResourceVersionFilter,
SubsystemStatusFilter,
UserAnnotationFilter,
) | 3,504 | """
Tests for the Filter classes
"""
# Local
## Helpers #####################################################################
def test_filter_creation_deletion():
resource = make_managed_object()
filter = CreationDeletionFilter(resource)
| """
Tests for the Filter classes
"""
# Local
## Helpers #####################################################################
def test_filter_creation_deletion():
resource = make_managed_object()
filter = CreationDeletionFilter(resource)
| assert filter.update_and_test(resource, KubeEventType.ADDED) | 0 | 2023-11-15 16:43:29+00:00 | 4k |
ariebovenberg/whenever | tests/test_utc_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 copy import copy, deepcopy
from datetime import datetime as py_datetime
from datetime import timedelta, timezone
from freezegun import freeze_time
from hypothesis import given
from hypothesis.strategies import text
from pytest import approx
from whenever import (
AwareDateTime,
InvalidFormat,
LocalDateTime,
NaiveDateTime,
OffsetDateTime,
UTCDateTime,
ZonedDateTime,
hours,
)
from .common import (
AlwaysEqual,
AlwaysLarger,
AlwaysSmaller,
NeverEqual,
local_ams_tz,
local_nyc_tz,
) | 1,615 | assert d.hour == 5
assert d.minute == 12
assert d.second == 30
assert d.microsecond == 450
assert d.offset == timedelta()
assert d.tzinfo == timezone.utc
def test_optionality(self):
assert (
UTCDateTime(2020, 8, 15, 12)
== UTCDateTime(2020, 8, 15, 12, 0)
== UTCDateTime(2020, 8, 15, 12, 0, 0)
== UTCDateTime(2020, 8, 15, 12, 0, 0, 0)
)
def test_invalid(self):
with pytest.raises(ValueError, match="microsecond must"):
UTCDateTime(2020, 8, 15, 12, 8, 30, 1_000_000)
def test_kwargs(self):
d = UTCDateTime(
year=2020, month=8, day=15, hour=5, minute=12, second=30
)
assert d == UTCDateTime(2020, 8, 15, 5, 12, 30)
def test_immutable():
d = UTCDateTime(2020, 8, 15)
with pytest.raises(AttributeError):
d.year = 2021 # type: ignore[misc]
@pytest.mark.parametrize(
"d, expected",
[
(
UTCDateTime(2020, 8, 15, 23, 12, 9, 987_654),
"2020-08-15T23:12:09.987654Z",
),
(UTCDateTime(2020, 8, 15, 23, 12, 9), "2020-08-15T23:12:09Z"),
],
)
def test_canonical_str(d: UTCDateTime, expected: str):
assert str(d) == expected
assert d.canonical_str() == expected
class TestFromCanonicalStr:
def test_valid(self):
assert UTCDateTime.from_canonical_str(
"2020-08-15T12:08:30Z"
) == UTCDateTime(2020, 8, 15, 12, 8, 30)
def test_valid_three_fractions(self):
assert UTCDateTime.from_canonical_str(
"2020-08-15T12:08:30.349Z"
) == UTCDateTime(2020, 8, 15, 12, 8, 30, 349_000)
def test_valid_six_fractions(self):
assert UTCDateTime.from_canonical_str(
"2020-08-15T12:08:30.349123Z"
) == UTCDateTime(2020, 8, 15, 12, 8, 30, 349_123)
def test_single_space_instead_of_T(self):
assert UTCDateTime.from_canonical_str(
"2020-08-15 12:08:30Z"
) == UTCDateTime(2020, 8, 15, 12, 8, 30)
def test_unpadded(self):
with pytest.raises(InvalidFormat):
UTCDateTime.from_canonical_str("2020-8-15T12:8:30Z")
def test_overly_precise_fraction(self):
with pytest.raises(InvalidFormat):
UTCDateTime.from_canonical_str("2020-08-15T12:08:30.123456789123Z")
def test_invalid_lowercase_z(self):
with pytest.raises(InvalidFormat):
UTCDateTime.from_canonical_str("2020-08-15T12:08:30z")
def test_no_trailing_z(self):
with pytest.raises(InvalidFormat):
UTCDateTime.from_canonical_str("2020-08-15T12:08:30")
def test_no_seconds(self):
with pytest.raises(InvalidFormat):
UTCDateTime.from_canonical_str("2020-08-15T12:08Z")
def test_empty(self):
with pytest.raises(InvalidFormat):
UTCDateTime.from_canonical_str("")
def test_garbage(self):
with pytest.raises(InvalidFormat):
UTCDateTime.from_canonical_str("garbage")
@given(text())
def test_fuzzing(self, s: str):
with pytest.raises(InvalidFormat):
UTCDateTime.from_canonical_str(s)
class TestEquality:
def test_same(self):
d = UTCDateTime(2020, 8, 15)
same = d.replace()
assert d == same
assert not d != same
assert hash(d) == hash(same)
def test_different(self):
d = UTCDateTime(2020, 8, 15)
different = d.replace(year=2021)
assert d != different
assert not d == different
assert hash(d) != hash(different)
def test_notimplemented(self):
d = UTCDateTime(2020, 8, 15)
assert d == AlwaysEqual()
|
class TestInit:
def test_basic(self):
d = UTCDateTime(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 d.offset == timedelta()
assert d.tzinfo == timezone.utc
def test_optionality(self):
assert (
UTCDateTime(2020, 8, 15, 12)
== UTCDateTime(2020, 8, 15, 12, 0)
== UTCDateTime(2020, 8, 15, 12, 0, 0)
== UTCDateTime(2020, 8, 15, 12, 0, 0, 0)
)
def test_invalid(self):
with pytest.raises(ValueError, match="microsecond must"):
UTCDateTime(2020, 8, 15, 12, 8, 30, 1_000_000)
def test_kwargs(self):
d = UTCDateTime(
year=2020, month=8, day=15, hour=5, minute=12, second=30
)
assert d == UTCDateTime(2020, 8, 15, 5, 12, 30)
def test_immutable():
d = UTCDateTime(2020, 8, 15)
with pytest.raises(AttributeError):
d.year = 2021 # type: ignore[misc]
@pytest.mark.parametrize(
"d, expected",
[
(
UTCDateTime(2020, 8, 15, 23, 12, 9, 987_654),
"2020-08-15T23:12:09.987654Z",
),
(UTCDateTime(2020, 8, 15, 23, 12, 9), "2020-08-15T23:12:09Z"),
],
)
def test_canonical_str(d: UTCDateTime, expected: str):
assert str(d) == expected
assert d.canonical_str() == expected
class TestFromCanonicalStr:
def test_valid(self):
assert UTCDateTime.from_canonical_str(
"2020-08-15T12:08:30Z"
) == UTCDateTime(2020, 8, 15, 12, 8, 30)
def test_valid_three_fractions(self):
assert UTCDateTime.from_canonical_str(
"2020-08-15T12:08:30.349Z"
) == UTCDateTime(2020, 8, 15, 12, 8, 30, 349_000)
def test_valid_six_fractions(self):
assert UTCDateTime.from_canonical_str(
"2020-08-15T12:08:30.349123Z"
) == UTCDateTime(2020, 8, 15, 12, 8, 30, 349_123)
def test_single_space_instead_of_T(self):
assert UTCDateTime.from_canonical_str(
"2020-08-15 12:08:30Z"
) == UTCDateTime(2020, 8, 15, 12, 8, 30)
def test_unpadded(self):
with pytest.raises(InvalidFormat):
UTCDateTime.from_canonical_str("2020-8-15T12:8:30Z")
def test_overly_precise_fraction(self):
with pytest.raises(InvalidFormat):
UTCDateTime.from_canonical_str("2020-08-15T12:08:30.123456789123Z")
def test_invalid_lowercase_z(self):
with pytest.raises(InvalidFormat):
UTCDateTime.from_canonical_str("2020-08-15T12:08:30z")
def test_no_trailing_z(self):
with pytest.raises(InvalidFormat):
UTCDateTime.from_canonical_str("2020-08-15T12:08:30")
def test_no_seconds(self):
with pytest.raises(InvalidFormat):
UTCDateTime.from_canonical_str("2020-08-15T12:08Z")
def test_empty(self):
with pytest.raises(InvalidFormat):
UTCDateTime.from_canonical_str("")
def test_garbage(self):
with pytest.raises(InvalidFormat):
UTCDateTime.from_canonical_str("garbage")
@given(text())
def test_fuzzing(self, s: str):
with pytest.raises(InvalidFormat):
UTCDateTime.from_canonical_str(s)
class TestEquality:
def test_same(self):
d = UTCDateTime(2020, 8, 15)
same = d.replace()
assert d == same
assert not d != same
assert hash(d) == hash(same)
def test_different(self):
d = UTCDateTime(2020, 8, 15)
different = d.replace(year=2021)
assert d != different
assert not d == different
assert hash(d) != hash(different)
def test_notimplemented(self):
d = UTCDateTime(2020, 8, 15)
assert d == AlwaysEqual() | assert d != NeverEqual() | 3 | 2023-11-10 21:08:49+00:00 | 4k |
tonylampada/jarvisportal | jarvisportal/gptexec.py | [
{
"identifier": "GPT",
"path": "jarvisportal/gpt.py",
"snippet": "class GPT:\n def __init__(self, assistant_id):\n self.client = OpenAI()\n # self.thread_id = self._get_or_create_thread_id() # expensive :(\n self.thread_id = self._create_thread_id()\n self.assistant_id = a... | import sys
import os
import jarvisportal.listentomic as listentomic
import jarvisportal.listentomic as listentomic
from jarvisportal.gpt import GPT
from jarvisportal.llamaapichat import Chat as LlamaApiChat
from jarvisportal.actions import exec_actions, definitions | 2,235 |
usr = '\U0001F600'
bot = '\U0001F916'
mic = '\U0001F3A4'
def main():
args = sys.argv[1:]
engine = os.getenv("CHAT_ENGINE", "gpt")
if engine == "gpt":
if len(args) != 1:
print("Usage: gptexec.py <assistant_id>")
exit(1)
assistant_id = args[0]
bot = GPT(assistant_id)
elif engine == "llamaapi":
bot = LlamaApiChat(definitions)
try:
while True:
chatLoop(bot)
except KeyboardInterrupt:
print("\n====================================")
print("Thank you for using GPTExec. Come back soon. ;)")
print("====================================")
def _user_input():
if os.getenv("GPTEXEC_VOICE") == "1":
userInput = listentomic.listen_and_transcribe(detectsilence=True)
print(f"{usr} User: {userInput}")
else:
userInput = input(f"{usr} Type your message (or send an empty one to switch to voice input): \n")
if userInput.strip() == "":
print(f"{mic} Switching to voice input")
userInput = listentomic.listen_and_transcribe(detectsilence=False)
print(f"{usr} User: {userInput}")
return userInput
def chatLoop(bot):
userInput = _user_input()
print("waiting...")
bot.send_chat(userInput)
answer = None
while answer is None or not answer.get('is_final'):
print("waiting...")
answer = bot.next_answer()
print("=========================================================")
if answer["type"] == "action":
|
usr = '\U0001F600'
bot = '\U0001F916'
mic = '\U0001F3A4'
def main():
args = sys.argv[1:]
engine = os.getenv("CHAT_ENGINE", "gpt")
if engine == "gpt":
if len(args) != 1:
print("Usage: gptexec.py <assistant_id>")
exit(1)
assistant_id = args[0]
bot = GPT(assistant_id)
elif engine == "llamaapi":
bot = LlamaApiChat(definitions)
try:
while True:
chatLoop(bot)
except KeyboardInterrupt:
print("\n====================================")
print("Thank you for using GPTExec. Come back soon. ;)")
print("====================================")
def _user_input():
if os.getenv("GPTEXEC_VOICE") == "1":
userInput = listentomic.listen_and_transcribe(detectsilence=True)
print(f"{usr} User: {userInput}")
else:
userInput = input(f"{usr} Type your message (or send an empty one to switch to voice input): \n")
if userInput.strip() == "":
print(f"{mic} Switching to voice input")
userInput = listentomic.listen_and_transcribe(detectsilence=False)
print(f"{usr} User: {userInput}")
return userInput
def chatLoop(bot):
userInput = _user_input()
print("waiting...")
bot.send_chat(userInput)
answer = None
while answer is None or not answer.get('is_final'):
print("waiting...")
answer = bot.next_answer()
print("=========================================================")
if answer["type"] == "action": | action_results = exec_actions(answer["actions"], ask=True) | 2 | 2023-11-14 17:27:01+00:00 | 4k |
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.