index
int64
0
50.7k
project_path
stringclasses
279 values
completion_path
stringlengths
57
199
signature_postion
stringlengths
3
11
class_position
stringlengths
3
11
function_name
stringlengths
1
62
class_name
stringlengths
0
55
body_position
stringlengths
3
11
body_position_with_comments
stringlengths
3
11
masked_class
stringlengths
14
8.32k
masked_class_with_comment
stringlengths
14
8.32k
func_body
stringlengths
9
6.72k
func_body_with_comment
stringlengths
9
6.72k
len_func_body
int64
1
643
len_input
int64
10
2.02k
len_output
int64
4
1.9k
total
int64
20
2.05k
file_code
stringlengths
14
442k
file_code_with_comment
stringlengths
14
442k
6,087
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models.py
1113,1114
1101,1131
forward
MultiPeriodDiscriminatorV2
1114,1131
1114,1131
class MultiPeriodDiscriminatorV2(torch.nn.Module): def __init__(self, use_spectral_norm=False): super(MultiPeriodDiscriminatorV2, self).__init__() # periods = [2, 3, 5, 7, 11, 17] periods = [2, 3, 5, 7, 11, 17, 23, 37] discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] ...
class MultiPeriodDiscriminatorV2(torch.nn.Module): def __init__(self, use_spectral_norm=False): super(MultiPeriodDiscriminatorV2, self).__init__() # periods = [2, 3, 5, 7, 11, 17] periods = [2, 3, 5, 7, 11, 17, 23, 37] discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] ...
y_d_rs = [] # y_d_gs = [] fmap_rs = [] fmap_gs = [] for i, d in enumerate(self.discriminators): y_d_r, fmap_r = d(y) y_d_g, fmap_g = d(y_hat) # for j in range(len(fmap_r)): # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g...
y_d_rs = [] # y_d_gs = [] fmap_rs = [] fmap_gs = [] for i, d in enumerate(self.discriminators): y_d_r, fmap_r = d(y) y_d_g, fmap_g = d(y_hat) # for j in range(len(fmap_r)): # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g...
42
220
247
467
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,088
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models.py
178,181
148,204
forward
PosteriorEncoder
181,191
181,191
class PosteriorEncoder(nn.Module): def __init__( self, in_channels, out_channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, ): super(PosteriorEncoder, self).__init__() self.in_channels = in_channels ...
class PosteriorEncoder(nn.Module): def __init__( self, in_channels, out_channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, ): super(PosteriorEncoder, self).__init__() self.in_channels = in_channels ...
x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to( x.dtype ) x = self.pre(x) * x_mask x = self.enc(x, x_mask, g=g) stats = self.proj(x) * x_mask m, logs = torch.split(stats, self.out_channels, dim=1) z = (m + torch.randn_like(...
x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to( x.dtype ) x = self.pre(x) * x_mask x = self.enc(x, x_mask, g=g) stats = self.proj(x) * x_mask m, logs = torch.split(stats, self.out_channels, dim=1) z = (m + torch.randn_like(...
42
464
168
632
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,089
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models.py
117,124
82,148
forward
ResidualCouplingBlock
124,132
124,132
class ResidualCouplingBlock(nn.Module): def __init__( self, channels, hidden_channels, kernel_size, dilation_rate, n_layers, n_flows=4, gin_channels=0, ): super(ResidualCouplingBlock, self).__init__() self.channels = channels ...
class ResidualCouplingBlock(nn.Module): def __init__( self, channels, hidden_channels, kernel_size, dilation_rate, n_layers, n_flows=4, gin_channels=0, ): super(ResidualCouplingBlock, self).__init__() self.channels = channels ...
if not reverse: for flow in self.flows: x, _ = flow(x, x_mask, g=g, reverse=reverse) else: for flow in self.flows[::-1]: x, _ = flow.forward(x, x_mask, g=g, reverse=reverse) return x
if not reverse: for flow in self.flows: x, _ = flow(x, x_mask, g=g, reverse=reverse) else: for flow in self.flows[::-1]: x, _ = flow.forward(x, x_mask, g=g, reverse=reverse) return x
28
530
95
625
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,090
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models.py
353,354
312,410
forward
SineGen
360,410
354,410
class SineGen(torch.nn.Module): """Definition of sine generator SineGen(samp_rate, harmonic_num = 0, sine_amp = 0.1, noise_std = 0.003, voiced_threshold = 0, flag_for_pulse=False) samp_rate: sampling rate in Hz harmonic_num: number of harmonic overtones (default 0) ...
class SineGen(torch.nn.Module): """Definition of sine generator SineGen(samp_rate, harmonic_num = 0, sine_amp = 0.1, noise_std = 0.003, voiced_threshold = 0, flag_for_pulse=False) samp_rate: sampling rate in Hz harmonic_num: number of harmonic overtones (default 0) ...
with torch.no_grad(): f0 = f0[:, None].transpose(1, 2) f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, device=f0.device) # fundamental component f0_buf[:, :, 0] = f0[:, :, 0] for idx in range(self.harmonic_num): f0_buf[:, :, id...
"""sine_tensor, uv = forward(f0) input F0: tensor(batchsize=1, length, dim=1) f0 for unvoiced steps should be 0 output sine_tensor: tensor(batchsize=1, length, dim) output uv: tensor(batchsize=1, length, 1) """ with torch.no_grad(): f0 = f0[:...
198
605
835
1,440
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,091
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models.py
452,453
410,467
forward
SourceModuleHnNSF
453,467
453,467
class SourceModuleHnNSF(torch.nn.Module): """SourceModule for hn-nsf SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1, add_noise_std=0.003, voiced_threshod=0) sampling_rate: sampling_rate in Hz harmonic_num: number of harmonic above F0 (default: 0) sine_amp: amplitude of sin...
class SourceModuleHnNSF(torch.nn.Module): """SourceModule for hn-nsf SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1, add_noise_std=0.003, voiced_threshod=0) sampling_rate: sampling_rate in Hz harmonic_num: number of harmonic above F0 (default: 0) sine_amp: amplitude of sin...
# if self.ddtype ==-1: # self.ddtype = self.l_linear.weight.dtype sine_wavs, uv, _ = self.l_sin_gen(x, upp) # print(x.dtype,sine_wavs.dtype,self.l_linear.weight.dtype) # if self.is_half: # sine_wavs = sine_wavs.half() # sine_merge = self.l_tanh(self.l_line...
# if self.ddtype ==-1: # self.ddtype = self.l_linear.weight.dtype sine_wavs, uv, _ = self.l_sin_gen(x, upp) # print(x.dtype,sine_wavs.dtype,self.l_linear.weight.dtype) # if self.is_half: # sine_wavs = sine_wavs.half() # sine_merge = self.l_tanh(self.l_line...
47
553
280
833
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,094
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models.py
54,61
19,82
forward
TextEncoder
61,82
61,82
class TextEncoder(nn.Module): def __init__( self, in_channels, out_channels, hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, f0=True, ): super(TextEncoder, self).__init__() self.out_chann...
class TextEncoder(nn.Module): def __init__( self, in_channels, out_channels, hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, f0=True, ): super(TextEncoder, self).__init__() self.out_chann...
if pitch is None: x = self.emb_phone(phone) else: x = self.emb_phone(phone) + self.emb_pitch(pitch) x = x * math.sqrt(self.hidden_channels) # [b, t, h] x = self.lrelu(x) x = torch.transpose(x, 1, -1) # [b, h, t] x_mask = torch.unsqueeze(commons.s...
if pitch is None: x = self.emb_phone(phone) else: x = self.emb_phone(phone) + self.emb_pitch(pitch) x = x * math.sqrt(self.hidden_channels) # [b, t, h] x = self.lrelu(x) x = torch.transpose(x, 1, -1) # [b, h, t] x_mask = torch.unsqueeze(commons.s...
83
437
308
745
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,095
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models_onnx.py
857,858
800,882
forward
DiscriminatorP
858,882
858,882
class DiscriminatorP(torch.nn.Module): def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False): super(DiscriminatorP, self).__init__() self.period = period self.use_spectral_norm = use_spectral_norm norm_f = weight_norm if use_spectral_norm == False else spectral...
class DiscriminatorP(torch.nn.Module): def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False): super(DiscriminatorP, self).__init__() self.period = period self.use_spectral_norm = use_spectral_norm norm_f = weight_norm if use_spectral_norm == False else spectral...
fmap = [] # 1d to 2d b, c, t = x.shape if t % self.period != 0: # pad first n_pad = self.period - (t % self.period) if has_xpu and x.dtype == torch.bfloat16: x = F.pad(x.to(dtype=torch.float16), (0, n_pad), "reflect").to( dtyp...
fmap = [] # 1d to 2d b, c, t = x.shape if t % self.period != 0: # pad first n_pad = self.period - (t % self.period) if has_xpu and x.dtype == torch.bfloat16: x = F.pad(x.to(dtype=torch.float16), (0, n_pad), "reflect").to( dtyp...
86
530
312
842
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,096
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models_onnx.py
786,787
770,800
forward
DiscriminatorS
787,800
787,800
class DiscriminatorS(torch.nn.Module): def __init__(self, use_spectral_norm=False): super(DiscriminatorS, self).__init__() norm_f = weight_norm if use_spectral_norm == False else spectral_norm self.convs = nn.ModuleList( [ norm_f(Conv1d(1, 16, 15, 1, padding=7)), ...
class DiscriminatorS(torch.nn.Module): def __init__(self, use_spectral_norm=False): super(DiscriminatorS, self).__init__() norm_f = weight_norm if use_spectral_norm == False else spectral_norm self.convs = nn.ModuleList( [ norm_f(Conv1d(1, 16, 15, 1, padding=7)), ...
fmap = [] for l in self.convs: x = l(x) x = F.leaky_relu(x, modules.LRELU_SLOPE) fmap.append(x) x = self.conv_post(x) fmap.append(x) x = torch.flatten(x, 1, -1) return x, fmap
fmap = [] for l in self.convs: x = l(x) x = F.leaky_relu(x, modules.LRELU_SLOPE) fmap.append(x) x = self.conv_post(x) fmap.append(x) x = torch.flatten(x, 1, -1) return x, fmap
27
355
121
476
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,097
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models_onnx.py
249,250
201,299
forward
Generator
250,270
250,270
class Generator(torch.nn.Module): def __init__( self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=0, ): super(Generator, se...
class Generator(torch.nn.Module): def __init__( self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=0, ): super(Generator, se...
x = self.conv_pre(x) if g is not None: x = x + self.cond(g) for i in range(self.num_upsamples): x = F.leaky_relu(x, modules.LRELU_SLOPE) x = self.ups[i](x) xs = None for j in range(self.num_kernels): if xs is None: ...
x = self.conv_pre(x) if g is not None: x = x + self.cond(g) for i in range(self.num_upsamples): x = F.leaky_relu(x, modules.LRELU_SLOPE) x = self.ups[i](x) xs = None for j in range(self.num_kernels): if xs is None: ...
66
921
239
1,160
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,098
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models_onnx.py
528,529
454,587
forward
GeneratorNSF
529,559
529,559
class GeneratorNSF(torch.nn.Module): def __init__( self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels, sr, is_half=False...
class GeneratorNSF(torch.nn.Module): def __init__( self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels, sr, is_half=False...
har_source, noi_source, uv = self.m_source(f0, self.upp) har_source = har_source.transpose(1, 2) x = self.conv_pre(x) if g is not None: x = x + self.cond(g) # torch.jit.script() does not support direct indexing of torch modules # That's why I wrote this ...
har_source, noi_source, uv = self.m_source(f0, self.upp) har_source = har_source.transpose(1, 2) x = self.conv_pre(x) if g is not None: x = x + self.cond(g) # torch.jit.script() does not support direct indexing of torch modules # That's why I wrote this ...
135
1,223
435
1,658
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,099
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models_onnx.py
722,723
710,740
forward
MultiPeriodDiscriminator
723,740
723,740
class MultiPeriodDiscriminator(torch.nn.Module): def __init__(self, use_spectral_norm=False): super(MultiPeriodDiscriminator, self).__init__() periods = [2, 3, 5, 7, 11, 17] # periods = [3, 5, 7, 11, 17, 23, 37] discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] d...
class MultiPeriodDiscriminator(torch.nn.Module): def __init__(self, use_spectral_norm=False): super(MultiPeriodDiscriminator, self).__init__() periods = [2, 3, 5, 7, 11, 17] # periods = [3, 5, 7, 11, 17, 23, 37] discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] d...
y_d_rs = [] # y_d_gs = [] fmap_rs = [] fmap_gs = [] for i, d in enumerate(self.discriminators): y_d_r, fmap_r = d(y) y_d_g, fmap_g = d(y_hat) # for j in range(len(fmap_r)): # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g...
y_d_rs = [] # y_d_gs = [] fmap_rs = [] fmap_gs = [] for i, d in enumerate(self.discriminators): y_d_r, fmap_r = d(y) y_d_g, fmap_g = d(y_hat) # for j in range(len(fmap_r)): # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g...
42
213
247
460
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,100
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models_onnx.py
752,753
740,770
forward
MultiPeriodDiscriminatorV2
753,770
753,770
class MultiPeriodDiscriminatorV2(torch.nn.Module): def __init__(self, use_spectral_norm=False): super(MultiPeriodDiscriminatorV2, self).__init__() # periods = [2, 3, 5, 7, 11, 17] periods = [2, 3, 5, 7, 11, 17, 23, 37] discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] ...
class MultiPeriodDiscriminatorV2(torch.nn.Module): def __init__(self, use_spectral_norm=False): super(MultiPeriodDiscriminatorV2, self).__init__() # periods = [2, 3, 5, 7, 11, 17] periods = [2, 3, 5, 7, 11, 17, 23, 37] discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] ...
y_d_rs = [] # y_d_gs = [] fmap_rs = [] fmap_gs = [] for i, d in enumerate(self.discriminators): y_d_r, fmap_r = d(y) y_d_g, fmap_g = d(y_hat) # for j in range(len(fmap_r)): # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g...
y_d_rs = [] # y_d_gs = [] fmap_rs = [] fmap_gs = [] for i, d in enumerate(self.discriminators): y_d_r, fmap_r = d(y) y_d_g, fmap_g = d(y_hat) # for j in range(len(fmap_r)): # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g...
42
220
247
467
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,101
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models_onnx.py
175,178
145,201
forward
PosteriorEncoder
178,188
178,188
class PosteriorEncoder(nn.Module): def __init__( self, in_channels, out_channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, ): super(PosteriorEncoder, self).__init__() self.in_channels = in_channels ...
class PosteriorEncoder(nn.Module): def __init__( self, in_channels, out_channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, ): super(PosteriorEncoder, self).__init__() self.in_channels = in_channels ...
x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to( x.dtype ) x = self.pre(x) * x_mask x = self.enc(x, x_mask, g=g) stats = self.proj(x) * x_mask m, logs = torch.split(stats, self.out_channels, dim=1) z = (m + torch.randn_like(...
x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to( x.dtype ) x = self.pre(x) * x_mask x = self.enc(x, x_mask, g=g) stats = self.proj(x) * x_mask m, logs = torch.split(stats, self.out_channels, dim=1) z = (m + torch.randn_like(...
42
464
168
632
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,102
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models_onnx.py
114,121
79,145
forward
ResidualCouplingBlock
121,129
121,129
class ResidualCouplingBlock(nn.Module): def __init__( self, channels, hidden_channels, kernel_size, dilation_rate, n_layers, n_flows=4, gin_channels=0, ): super(ResidualCouplingBlock, self).__init__() self.channels = channels ...
class ResidualCouplingBlock(nn.Module): def __init__( self, channels, hidden_channels, kernel_size, dilation_rate, n_layers, n_flows=4, gin_channels=0, ): super(ResidualCouplingBlock, self).__init__() self.channels = channels ...
if not reverse: for flow in self.flows: x, _ = flow(x, x_mask, g=g, reverse=reverse) else: for flow in reversed(self.flows): x, _ = flow.forward(x, x_mask, g=g, reverse=reverse) return x
if not reverse: for flow in self.flows: x, _ = flow(x, x_mask, g=g, reverse=reverse) else: for flow in reversed(self.flows): x, _ = flow.forward(x, x_mask, g=g, reverse=reverse) return x
28
530
94
624
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,103
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models_onnx.py
340,341
299,397
forward
SineGen
347,397
341,397
class SineGen(torch.nn.Module): """Definition of sine generator SineGen(samp_rate, harmonic_num = 0, sine_amp = 0.1, noise_std = 0.003, voiced_threshold = 0, flag_for_pulse=False) samp_rate: sampling rate in Hz harmonic_num: number of harmonic overtones (default 0) ...
class SineGen(torch.nn.Module): """Definition of sine generator SineGen(samp_rate, harmonic_num = 0, sine_amp = 0.1, noise_std = 0.003, voiced_threshold = 0, flag_for_pulse=False) samp_rate: sampling rate in Hz harmonic_num: number of harmonic overtones (default 0) ...
with torch.no_grad(): f0 = f0[:, None].transpose(1, 2) f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, device=f0.device) # fundamental component f0_buf[:, :, 0] = f0[:, :, 0] for idx in range(self.harmonic_num): f0_buf[:, :, id...
"""sine_tensor, uv = forward(f0) input F0: tensor(batchsize=1, length, dim=1) f0 for unvoiced steps should be 0 output sine_tensor: tensor(batchsize=1, length, dim) output uv: tensor(batchsize=1, length, 1) """ with torch.no_grad(): f0 = f0[:...
198
605
835
1,440
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,104
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models_onnx.py
439,440
397,454
forward
SourceModuleHnNSF
440,454
440,454
class SourceModuleHnNSF(torch.nn.Module): """SourceModule for hn-nsf SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1, add_noise_std=0.003, voiced_threshod=0) sampling_rate: sampling_rate in Hz harmonic_num: number of harmonic above F0 (default: 0) sine_amp: amplitude of sin...
class SourceModuleHnNSF(torch.nn.Module): """SourceModule for hn-nsf SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1, add_noise_std=0.003, voiced_threshod=0) sampling_rate: sampling_rate in Hz harmonic_num: number of harmonic above F0 (default: 0) sine_amp: amplitude of sin...
# if self.ddtype ==-1: # self.ddtype = self.l_linear.weight.dtype sine_wavs, uv, _ = self.l_sin_gen(x, upp) # print(x.dtype,sine_wavs.dtype,self.l_linear.weight.dtype) # if self.is_half: # sine_wavs = sine_wavs.half() # sine_merge = self.l_tanh(self.l_line...
# if self.ddtype ==-1: # self.ddtype = self.l_linear.weight.dtype sine_wavs, uv, _ = self.l_sin_gen(x, upp) # print(x.dtype,sine_wavs.dtype,self.l_linear.weight.dtype) # if self.is_half: # sine_wavs = sine_wavs.half() # sine_merge = self.l_tanh(self.l_line...
47
553
280
833
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,105
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models_onnx.py
693,694
594,710
forward
SynthesizerTrnMsNSFsidM
694,710
694,710
class SynthesizerTrnMsNSFsidM(nn.Module): def __init__( self, spec_channels, segment_size, inter_channels, hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, resblock, resblock_kernel_sizes, ...
class SynthesizerTrnMsNSFsidM(nn.Module): def __init__( self, spec_channels, segment_size, inter_channels, hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, resblock, resblock_kernel_sizes, ...
if self.speaker_map is not None: # [N, S] * [S, B, 1, H] g = g.reshape((g.shape[0], g.shape[1], 1, 1, 1)) # [N, S, B, 1, 1] g = g * self.speaker_map # [N, S, B, 1, H] g = torch.sum(g, dim=1) # [N, 1, B, 1, H] g = g.transpose(0, -1).transpose(0, -2).squeeze(0...
if self.speaker_map is not None: # [N, S] * [S, B, 1, H] g = g.reshape((g.shape[0], g.shape[1], 1, 1, 1)) # [N, S, B, 1, 1] g = g * self.speaker_map # [N, S, B, 1, H] g = torch.sum(g, dim=1) # [N, 1, B, 1, H] g = g.transpose(0, -1).transpose(0, -2).squeeze(0...
97
1,066
344
1,410
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,106
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models_onnx.py
56,63
21,79
forward
TextEncoder
63,79
63,79
class TextEncoder(nn.Module): def __init__( self, in_channels, out_channels, hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, f0=True, ): super(TextEncoder, self).__init__() self.out_chann...
class TextEncoder(nn.Module): def __init__( self, in_channels, out_channels, hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, f0=True, ): super(TextEncoder, self).__init__() self.out_chann...
if pitch is None: x = self.emb_phone(phone) else: x = self.emb_phone(phone) + self.emb_pitch(pitch) x = x * math.sqrt(self.hidden_channels) # [b, t, h] x = self.lrelu(x) x = torch.transpose(x, 1, -1) # [b, h, t] x_mask = torch.unsqueeze(commons.s...
if pitch is None: x = self.emb_phone(phone) else: x = self.emb_phone(phone) + self.emb_pitch(pitch) x = x * math.sqrt(self.hidden_channels) # [b, t, h] x = self.lrelu(x) x = torch.transpose(x, 1, -1) # [b, h, t] x_mask = torch.unsqueeze(commons.s...
62
437
239
676
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,107
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/modules.py
579,586
552,616
forward
ConvFlow
586,616
586,616
class ConvFlow(nn.Module): def __init__( self, in_channels, filter_channels, kernel_size, n_layers, num_bins=10, tail_bound=5.0, ): super(ConvFlow, self).__init__() self.in_channels = in_channels self.filter_channels = filter_channe...
class ConvFlow(nn.Module): def __init__( self, in_channels, filter_channels, kernel_size, n_layers, num_bins=10, tail_bound=5.0, ): super(ConvFlow, self).__init__() self.in_channels = in_channels self.filter_channels = filter_channe...
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.nu...
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.nu...
105
375
429
804
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
6,108
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/modules.py
77,78
35,87
forward
ConvReluNorm
78,87
78,87
class ConvReluNorm(nn.Module): def __init__( self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout, ): super(ConvReluNorm, self).__init__() self.in_channels = in_channels self.hidden_channels = hidden_ch...
class ConvReluNorm(nn.Module): def __init__( self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout, ): super(ConvReluNorm, self).__init__() self.in_channels = in_channels self.hidden_channels = hidden_ch...
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
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
27
478
98
576
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
6,109
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/modules.py
121,122
87,136
forward
DDSConv
122,136
122,136
class DDSConv(nn.Module): """ Dialted and Depth-Separable Convolution """ def __init__(self, channels, kernel_size, n_layers, p_dropout=0.0): super(DDSConv, self).__init__() self.channels = channels self.kernel_size = kernel_size self.n_layers = n_layers self.p_d...
class DDSConv(nn.Module): """ Dialted and Depth-Separable Convolution """ def __init__(self, channels, kernel_size, n_layers, p_dropout=0.0): super(DDSConv, self).__init__() self.channels = channels self.kernel_size = kernel_size self.n_layers = n_layers self.p_d...
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)...
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)...
46
401
159
560
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
6,110
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/modules.py
466,467
459,477
forward
ElementwiseAffine
467,477
467,477
class ElementwiseAffine(nn.Module): def __init__(self, channels): super(ElementwiseAffine, self).__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, **k...
class ElementwiseAffine(nn.Module): def __init__(self, channels): super(ElementwiseAffine, self).__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, **k...
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
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
37
124
113
237
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
6,111
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/modules.py
444,451
440,459
forward
Flip
451,459
451,459
class Flip(nn.Module): # torch.jit.script() Compiled functions \ # can't take variable number of arguments or \ # use keyword-only arguments with defaults def forward( self, x: torch.Tensor, x_mask: torch.Tensor, g: Optional[torch.Tensor] = None, reverse: bool = F...
class Flip(nn.Module): # torch.jit.script() Compiled functions \ # can't take variable number of arguments or \ # use keyword-only arguments with defaults def forward( self, x: torch.Tensor, x_mask: torch.Tensor, g: Optional[torch.Tensor] = None, reverse: bool = F...
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, torch.zeros([1], device=x.device)
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, torch.zeros([1], device=x.device)
19
134
94
228
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
6,112
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/modules.py
29,30
20,35
forward
LayerNorm
30,35
30,35
class LayerNorm(nn.Module): def __init__(self, channels, eps=1e-5): super(LayerNorm, self).__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): FILL_FUNC_...
class LayerNorm(nn.Module): def __init__(self, channels, eps=1e-5): super(LayerNorm, self).__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): FILL_FUNC_...
x = x.transpose(1, -1) x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps) return x.transpose(1, -1)
x = x.transpose(1, -1) x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps) return x.transpose(1, -1)
14
117
65
182
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
6,113
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/modules.py
424,431
423,440
forward
Log
431,440
431,440
class Log(nn.Module): def forward( self, x: torch.Tensor, x_mask: torch.Tensor, g: Optional[torch.Tensor] = None, reverse: bool = False, ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: FILL_FUNC_BODY
class Log(nn.Module): def forward( self, x: torch.Tensor, x_mask: torch.Tensor, g: Optional[torch.Tensor] = None, reverse: bool = False, ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: FILL_FUNC_BODY
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
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
25
95
94
189
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
6,114
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/modules.py
328,329
252,367
forward
ResBlock1
329,343
329,343
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,...
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,...
for c1, c2 in zip(self.convs1, self.convs2): xt = F.leaky_relu(x, self.lrelu_slope) if x_mask is not None: xt = xt * x_mask xt = c1(xt) xt = F.leaky_relu(xt, self.lrelu_slope) if x_mask is not None: xt = xt * x_mask ...
for c1, c2 in zip(self.convs1, self.convs2): xt = F.leaky_relu(x, self.lrelu_slope) if x_mask is not None: xt = xt * x_mask xt = c1(xt) xt = F.leaky_relu(xt, self.lrelu_slope) if x_mask is not None: xt = xt * x_mask ...
57
808
179
987
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
6,115
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/modules.py
397,398
367,423
forward
ResBlock2
398,408
398,408
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, ...
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, ...
for c in self.convs: xt = F.leaky_relu(x, self.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
for c in self.convs: xt = F.leaky_relu(x, self.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
38
407
106
513
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
6,116
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/modules.py
512,519
477,552
forward
ResidualCouplingLayer
519,539
519,539
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...
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...
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 l...
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 l...
84
549
291
840
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
6,117
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/modules.py
188,191
136,252
forward
WN
191,219
191,219
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 ...
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 ...
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_layer, res_skip_layer) in enumerate( zip(self.in_layers, self.res_skip_layers) ): x_in = in_layer(x) ...
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_layer, res_skip_layer) in enumerate( zip(self.in_layers, self.res_skip_layers) ): x_in = in_layer(x) ...
101
1,029
389
1,418
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
import copy import math from typing import Optional, Tuple import numpy as np import scipy import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, weight_norm from infer.lib.infer_pack import ...
6,119
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/jit/get_rmvpe.py
4,5
1,13
get_rmvpe
5,13
5,13
import torch def get_rmvpe(model_path="assets/rmvpe/rmvpe.pt", device=torch.device("cpu")): FILL_FUNC_BODY
import torch def get_rmvpe(model_path="assets/rmvpe/rmvpe.pt", device=torch.device("cpu")): FILL_FUNC_BODY
from infer.lib.rmvpe import E2E model = E2E(4, 1, (2, 2)) ckpt = torch.load(model_path, map_location=device) model.load_state_dict(ckpt) model.eval() model = model.to(device) return model
from infer.lib.rmvpe import E2E model = E2E(4, 1, (2, 2)) ckpt = torch.load(model_path, map_location=device) model.load_state_dict(ckpt) model.eval() model = model.to(device) return model
21
51
96
147
import torch def get_rmvpe(model_path="assets/rmvpe/rmvpe.pt", device=torch.device("cpu")): FILL_FUNC_BODY
import torch def get_rmvpe(model_path="assets/rmvpe/rmvpe.pt", device=torch.device("cpu")): FILL_FUNC_BODY
6,121
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/train/losses.py
15,16
1,59
discriminator_loss
16,31
16,31
import torch def feature_loss(fmap_r, fmap_g): loss = 0 for dr, dg in zip(fmap_r, fmap_g): for rl, gl in zip(dr, dg): rl = rl.float().detach() gl = gl.float() loss += torch.mean(torch.abs(rl - gl)) return loss * 2 def discriminator_loss(disc_real_outputs, dis...
import torch def feature_loss(fmap_r, fmap_g): loss = 0 for dr, dg in zip(fmap_r, fmap_g): for rl, gl in zip(dr, dg): rl = rl.float().detach() gl = gl.float() loss += torch.mean(torch.abs(rl - gl)) return loss * 2 def discriminator_loss(disc_real_outputs, dis...
loss = 0 r_losses = [] g_losses = [] for dr, dg in zip(disc_real_outputs, disc_generated_outputs): dr = dr.float() dg = dg.float() r_loss = torch.mean((1 - dr) ** 2) g_loss = torch.mean(dg**2) loss += r_loss + g_loss r_losses.append(r_loss.item()) ...
loss = 0 r_losses = [] g_losses = [] for dr, dg in zip(disc_real_outputs, disc_generated_outputs): dr = dr.float() dg = dg.float() r_loss = torch.mean((1 - dr) ** 2) g_loss = torch.mean(dg**2) loss += r_loss + g_loss r_losses.append(r_loss.item()) ...
42
455
171
626
import torch def feature_loss(fmap_r, fmap_g): loss = 0 for dr, dg in zip(fmap_r, fmap_g): for rl, gl in zip(dr, dg): rl = rl.float().detach() gl = gl.float() loss += torch.mean(torch.abs(rl - gl)) return loss * 2 def discriminator_loss(disc_real_outputs, dis...
import torch def feature_loss(fmap_r, fmap_g): loss = 0 for dr, dg in zip(fmap_r, fmap_g): for rl, gl in zip(dr, dg): rl = rl.float().detach() gl = gl.float() loss += torch.mean(torch.abs(rl - gl)) return loss * 2 def discriminator_loss(disc_real_outputs, dis...
6,122
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/train/mel_processing.py
92,93
1,128
spec_to_mel_torch
93,111
93,111
import torch import torch.utils.data from librosa.filters import mel as librosa_mel_fn import logging logger = logging.getLogger(__name__) MAX_WAV_VALUE = 32768.0 def dynamic_range_compression_torch(x, C=1, clip_val=1e-5): """ PARAMS ------ C: compression factor """ return torch.log(torch.cl...
import torch import torch.utils.data from librosa.filters import mel as librosa_mel_fn import logging logger = logging.getLogger(__name__) MAX_WAV_VALUE = 32768.0 def dynamic_range_compression_torch(x, C=1, clip_val=1e-5): """ PARAMS ------ C: compression factor """ return torch.log(torch.cl...
# MelBasis - Cache if needed global mel_basis dtype_device = str(spec.dtype) + "_" + str(spec.device) fmax_dtype_device = str(fmax) + "_" + dtype_device if fmax_dtype_device not in mel_basis: mel = librosa_mel_fn( sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fm...
# MelBasis - Cache if needed global mel_basis dtype_device = str(spec.dtype) + "_" + str(spec.device) fmax_dtype_device = str(fmax) + "_" + dtype_device if fmax_dtype_device not in mel_basis: mel = librosa_mel_fn( sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fm...
59
1,134
283
1,417
import torch import torch.utils.data from librosa.filters import mel as librosa_mel_fn import logging logger = logging.getLogger(__name__) MAX_WAV_VALUE = 32768.0 def dynamic_range_compression_torch(x, C=1, clip_val=1e-5): """ PARAMS ------ C: compression factor """ return torch.log(torch.cl...
import torch import torch.utils.data from librosa.filters import mel as librosa_mel_fn import logging logger = logging.getLogger(__name__) MAX_WAV_VALUE = 32768.0 def dynamic_range_compression_torch(x, C=1, clip_val=1e-5): """ PARAMS ------ C: compression factor """ return torch.log(torch.cl...
6,124
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/uvr5_pack/lib_v5/model_param_init.py
36,37
1,70
int_keys
37,45
37,45
import json import os import pathlib default_param = {} default_param["bins"] = 768 default_param["unstable_bins"] = 9 # training only default_param["reduction_bins"] = 762 # training only default_param["sr"] = 44100 default_param["pre_filter_start"] = 757 default_param["pre_filter_stop"] = 768 default_param["band"]...
import json import os import pathlib default_param = {} default_param["bins"] = 768 default_param["unstable_bins"] = 9 # training only default_param["reduction_bins"] = 762 # training only default_param["sr"] = 44100 default_param["pre_filter_start"] = 757 default_param["pre_filter_stop"] = 768 default_param["band"]...
r = {} for k, v in d: if k.isdigit(): k = int(k) r[k] = v return r
r = {} for k, v in d: if k.isdigit(): k = int(k) r[k] = v return r
18
599
53
652
import json import os import pathlib default_param = {} default_param["bins"] = 768 default_param["unstable_bins"] = 9 # training only default_param["reduction_bins"] = 762 # training only default_param["sr"] = 44100 default_param["pre_filter_start"] = 757 default_param["pre_filter_stop"] = 768 default_param["band"]...
import json import os import pathlib default_param = {} default_param["bins"] = 768 default_param["unstable_bins"] = 9 # training only default_param["reduction_bins"] = 762 # training only default_param["sr"] = 44100 default_param["pre_filter_start"] = 757 default_param["pre_filter_stop"] = 768 default_param["band"]...
6,125
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/uvr5_pack/utils.py
25,26
1,122
inference
29,102
26,102
import json import numpy as np import torch from tqdm import tqdm def load_data(file_name: str = "./infer/lib/uvr5_pack/name_params.json") -> dict: with open(file_name, "r") as f: data = json.load(f) return data def make_padding(width, cropsize, offset): left = offset roi_size = cropsize -...
import json import numpy as np import torch from tqdm import tqdm def load_data(file_name: str = "./infer/lib/uvr5_pack/name_params.json") -> dict: with open(file_name, "r") as f: data = json.load(f) return data def make_padding(width, cropsize, offset): left = offset roi_size = cropsize -...
def _execute( X_mag_pad, roi_size, n_window, device, model, aggressiveness, is_half=True ): model.eval() with torch.no_grad(): preds = [] iterations = [n_window] total_iterations = sum(iterations) for i in tqdm(range(n_window)): ...
""" data : dic configs """ def _execute( X_mag_pad, roi_size, n_window, device, model, aggressiveness, is_half=True ): model.eval() with torch.no_grad(): preds = [] iterations = [n_window] total_iterations = sum(iterations) f...
213
456
898
1,354
import json import numpy as np import torch from tqdm import tqdm def load_data(file_name: str = "./infer/lib/uvr5_pack/name_params.json") -> dict: with open(file_name, "r") as f: data = json.load(f) return data def make_padding(width, cropsize, offset): left = offset roi_size = cropsize -...
import json import numpy as np import torch from tqdm import tqdm def load_data(file_name: str = "./infer/lib/uvr5_pack/name_params.json") -> dict: with open(file_name, "r") as f: data = json.load(f) return data def make_padding(width, cropsize, offset): left = offset roi_size = cropsize -...
6,126
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/modules/gui/utils.py
5,9
1,71
amp_to_db
24,28
9,28
import torch from torch.types import Number @torch.no_grad() def amp_to_db( x: torch.Tensor, eps=torch.finfo(torch.float64).eps, top_db=40 ) -> torch.Tensor: FILL_FUNC_BODY@torch.no_grad() def temperature_sigmoid(x: torch.Tensor, x0: float, temp_coeff: float) -> torch.Tensor: """ Apply a sigmoid function ...
import torch from torch.types import Number @torch.no_grad() def amp_to_db( x: torch.Tensor, eps=torch.finfo(torch.float64).eps, top_db=40 ) -> torch.Tensor: """ Convert the input tensor from amplitude to decibel scale. Arguments: x {[torch.Tensor]} -- [Input tensor.] Keyword Arguments: ...
x_db = 20 * torch.log10(x.abs() + eps) return torch.max(x_db, (x_db.max(-1).values - top_db).unsqueeze(-1))
""" Convert the input tensor from amplitude to decibel scale. Arguments: x {[torch.Tensor]} -- [Input tensor.] Keyword Arguments: eps {[float]} -- [Small value to avoid numerical instability.] (default: {torch.finfo(torch.float64).eps}) top_db {[float]...
12
760
64
824
import torch from torch.types import Number @torch.no_grad() def amp_to_db( x: torch.Tensor, eps=torch.finfo(torch.float64).eps, top_db=40 ) -> torch.Tensor: FILL_FUNC_BODY@torch.no_grad() def temperature_sigmoid(x: torch.Tensor, x0: float, temp_coeff: float) -> torch.Tensor: """ Apply a sigmoid function ...
import torch from torch.types import Number @torch.no_grad() def amp_to_db( x: torch.Tensor, eps=torch.finfo(torch.float64).eps, top_db=40 ) -> torch.Tensor: """ Convert the input tensor from amplitude to decibel scale. Arguments: x {[torch.Tensor]} -- [Input tensor.] Keyword Arguments: ...
6,128
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/modules/onnx/export.py
6,7
1,53
export_onnx
7,53
7,53
import torch from infer.lib.infer_pack.models_onnx import SynthesizerTrnMsNSFsidM def export_onnx(ModelPath, ExportedPath): FILL_FUNC_BODY
import torch from infer.lib.infer_pack.models_onnx import SynthesizerTrnMsNSFsidM def export_onnx(ModelPath, ExportedPath): FILL_FUNC_BODY
cpt = torch.load(ModelPath, map_location="cpu") cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] vec_channels = 256 if cpt.get("version", "v1") == "v1" else 768 test_phone = torch.rand(1, 200, vec_channels) # hidden unit test_phone_lengths = torch.tensor([200]).long() # hidden unit 长度(貌...
cpt = torch.load(ModelPath, map_location="cpu") cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] vec_channels = 256 if cpt.get("version", "v1") == "v1" else 768 test_phone = torch.rand(1, 200, vec_channels) # hidden unit test_phone_lengths = torch.tensor([200]).long() # hidden unit 长度(貌...
119
62
721
783
import torch from infer.lib.infer_pack.models_onnx import SynthesizerTrnMsNSFsidM def export_onnx(ModelPath, ExportedPath): FILL_FUNC_BODY
import torch from infer.lib.infer_pack.models_onnx import SynthesizerTrnMsNSFsidM def export_onnx(ModelPath, ExportedPath): FILL_FUNC_BODY
6,129
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/modules/train/preprocess.py
29,30
1,143
println
30,35
30,35
import multiprocessing import os import sys from scipy import signal now_dir = os.getcwd() sys.path.append(now_dir) print(*sys.argv[1:]) inp_root = sys.argv[1] sr = int(sys.argv[2]) n_p = int(sys.argv[3]) exp_dir = sys.argv[4] noparallel = sys.argv[5] == "True" per = float(sys.argv[6]) import os import traceback imp...
import multiprocessing import os import sys from scipy import signal now_dir = os.getcwd() sys.path.append(now_dir) print(*sys.argv[1:]) inp_root = sys.argv[1] sr = int(sys.argv[2]) n_p = int(sys.argv[3]) exp_dir = sys.argv[4] noparallel = sys.argv[5] == "True" per = float(sys.argv[6]) import os import traceback imp...
print(strr) f.write("%s\n" % strr) f.flush()
print(strr) f.write("%s\n" % strr) f.flush()
5
1,557
34
1,591
import multiprocessing import os import sys from scipy import signal now_dir = os.getcwd() sys.path.append(now_dir) print(*sys.argv[1:]) inp_root = sys.argv[1] sr = int(sys.argv[2]) n_p = int(sys.argv[3]) exp_dir = sys.argv[4] noparallel = sys.argv[5] == "True" per = float(sys.argv[6]) import os import traceback imp...
import multiprocessing import os import sys from scipy import signal now_dir = os.getcwd() sys.path.append(now_dir) print(*sys.argv[1:]) inp_root = sys.argv[1] sr = int(sys.argv[2]) n_p = int(sys.argv[3]) exp_dir = sys.argv[4] noparallel = sys.argv[5] == "True" per = float(sys.argv[6]) import os import traceback imp...
6,130
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/modules/train/preprocess.py
111,112
35,134
pipeline_mp_inp_dir
PreProcess
112,134
112,134
class PreProcess: def __init__(self, sr, exp_dir, per=3.7): self.slicer = Slicer( sr=sr, threshold=-42, min_length=1500, min_interval=400, hop_size=15, max_sil_kept=500, ) self.sr = sr self.bh, self.ah = signal.b...
class PreProcess: def __init__(self, sr, exp_dir, per=3.7): self.slicer = Slicer( sr=sr, threshold=-42, min_length=1500, min_interval=400, hop_size=15, max_sil_kept=500, ) self.sr = sr self.bh, self.ah = signal.b...
try: infos = [ ("%s/%s" % (inp_root, name), idx) for idx, name in enumerate(sorted(list(os.listdir(inp_root)))) ] if noparallel: for i in range(n_p): self.pipeline_mp(infos[i::n_p]) else: ...
try: infos = [ ("%s/%s" % (inp_root, name), idx) for idx, name in enumerate(sorted(list(os.listdir(inp_root)))) ] if noparallel: for i in range(n_p): self.pipeline_mp(infos[i::n_p]) else: ...
48
1,003
233
1,236
import multiprocessing import os import sys from scipy import signal now_dir = os.getcwd() sys.path.append(now_dir) print(*sys.argv[1:]) inp_root = sys.argv[1] sr = int(sys.argv[2]) n_p = int(sys.argv[3]) exp_dir = sys.argv[4] noparallel = sys.argv[5] == "True" per = float(sys.argv[6]) import os import traceback imp...
import multiprocessing import os import sys from scipy import signal now_dir = os.getcwd() sys.path.append(now_dir) print(*sys.argv[1:]) inp_root = sys.argv[1] sr = int(sys.argv[2]) n_p = int(sys.argv[3]) exp_dir = sys.argv[4] noparallel = sys.argv[5] == "True" per = float(sys.argv[6]) import os import traceback imp...
6,131
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/modules/uvr5/modules.py
17,18
1,109
uvr
18,109
18,109
import os import traceback import logging logger = logging.getLogger(__name__) import ffmpeg import torch from configs.config import Config from infer.modules.uvr5.mdxnet import MDXNetDereverb from infer.modules.uvr5.vr import AudioPre, AudioPreDeEcho config = Config() def uvr(model_name, inp_root, save_root_voca...
import os import traceback import logging logger = logging.getLogger(__name__) import ffmpeg import torch from configs.config import Config from infer.modules.uvr5.mdxnet import MDXNetDereverb from infer.modules.uvr5.vr import AudioPre, AudioPreDeEcho config = Config() def uvr(model_name, inp_root, save_root_voca...
infos = [] try: inp_root = inp_root.strip(" ").strip('"').strip("\n").strip('"').strip(" ") save_root_vocal = ( save_root_vocal.strip(" ").strip('"').strip("\n").strip('"').strip(" ") ) save_root_ins = ( save_root_ins.strip(" ").strip('"').strip("\n").stri...
infos = [] try: inp_root = inp_root.strip(" ").strip('"').strip("\n").strip('"').strip(" ") save_root_vocal = ( save_root_vocal.strip(" ").strip('"').strip("\n").strip('"').strip(" ") ) save_root_ins = ( save_root_ins.strip(" ").strip('"').strip("\n").stri...
229
133
1,160
1,293
import os import traceback import logging logger = logging.getLogger(__name__) import ffmpeg import torch from configs.config import Config from infer.modules.uvr5.mdxnet import MDXNetDereverb from infer.modules.uvr5.vr import AudioPre, AudioPreDeEcho config = Config() def uvr(model_name, inp_root, save_root_voca...
import os import traceback import logging logger = logging.getLogger(__name__) import ffmpeg import torch from configs.config import Config from infer.modules.uvr5.mdxnet import MDXNetDereverb from infer.modules.uvr5.vr import AudioPre, AudioPreDeEcho config = Config() def uvr(model_name, inp_root, save_root_voca...
6,132
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/modules/vc/utils.py
22,23
1,34
load_hubert
23,34
23,34
import os from fairseq import checkpoint_utils def get_index_path_from_model(sid): return next( ( f for f in [ os.path.join(root, name) for root, _, files in os.walk(os.getenv("index_root"), topdown=False) for name in files ...
import os from fairseq import checkpoint_utils def get_index_path_from_model(sid): return next( ( f for f in [ os.path.join(root, name) for root, _, files in os.walk(os.getenv("index_root"), topdown=False) for name in files ...
models, _, _ = checkpoint_utils.load_model_ensemble_and_task( ["assets/hubert/hubert_base.pt"], suffix="", ) hubert_model = models[0] hubert_model = hubert_model.to(config.device) if config.is_half: hubert_model = hubert_model.half() else: hubert_model = hubert_mo...
models, _, _ = checkpoint_utils.load_model_ensemble_and_task( ["assets/hubert/hubert_base.pt"], suffix="", ) hubert_model = models[0] hubert_model = hubert_model.to(config.device) if config.is_half: hubert_model = hubert_model.half() else: hubert_model = hubert_mo...
25
158
141
299
import os from fairseq import checkpoint_utils def get_index_path_from_model(sid): return next( ( f for f in [ os.path.join(root, name) for root, _, files in os.walk(os.getenv("index_root"), topdown=False) for name in files ...
import os from fairseq import checkpoint_utils def get_index_path_from_model(sid): return next( ( f for f in [ os.path.join(root, name) for root, _, files in os.walk(os.getenv("index_root"), topdown=False) for name in files ...
6,134
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/tools/cmd/calc_rvc_model_similarity.py
56,57
1,97
main
57,93
57,93
# This code references https://huggingface.co/JosephusCheung/ASimilarityCalculatior/blob/main/qwerty.py # Fill in the path of the model to be queried and the root directory of the reference models, and this script will return the similarity between the model to be queried and all reference models. import os import logg...
# This code references https://huggingface.co/JosephusCheung/ASimilarityCalculatior/blob/main/qwerty.py # Fill in the path of the model to be queried and the root directory of the reference models, and this script will return the similarity between the model to be queried and all reference models. import os import logg...
torch.manual_seed(114514) model_a = torch.load(path, map_location="cpu")["weight"] logger.info("Query:\t\t%s\t%s" % (path, model_hash(path))) map_attn_a = {} map_rand_input = {} for n in range(6): hidden_dim, embed_dim, _ = model_a[ f"enc_p.encoder.attn_layers.{n}.conv_v.we...
torch.manual_seed(114514) model_a = torch.load(path, map_location="cpu")["weight"] logger.info("Query:\t\t%s\t%s" % (path, model_hash(path))) map_attn_a = {} map_rand_input = {} for n in range(6): hidden_dim, embed_dim, _ = model_a[ f"enc_p.encoder.attn_layers.{n}.conv_v.we...
83
761
468
1,229
# This code references https://huggingface.co/JosephusCheung/ASimilarityCalculatior/blob/main/qwerty.py # Fill in the path of the model to be queried and the root directory of the reference models, and this script will return the similarity between the model to be queried and all reference models. import os import logg...
# This code references https://huggingface.co/JosephusCheung/ASimilarityCalculatior/blob/main/qwerty.py # Fill in the path of the model to be queried and the root directory of the reference models, and this script will return the similarity between the model to be queried and all reference models. import os import logg...
6,135
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/tools/cmd/infer_batch_rvc.py
41,42
1,73
main
42,71
42,71
import argparse import os import sys print("Command-line arguments:", sys.argv) now_dir = os.getcwd() sys.path.append(now_dir) import sys import tqdm as tq from dotenv import load_dotenv from scipy.io import wavfile from configs.config import Config from infer.modules.vc.modules import VC def arg_parse() -> tuple...
import argparse import os import sys print("Command-line arguments:", sys.argv) now_dir = os.getcwd() sys.path.append(now_dir) import sys import tqdm as tq from dotenv import load_dotenv from scipy.io import wavfile from configs.config import Config from infer.modules.vc.modules import VC def arg_parse() -> tuple...
load_dotenv() args = arg_parse() config = Config() config.device = args.device if args.device else config.device config.is_half = args.is_half if args.is_half else config.is_half vc = VC(config) vc.get_vc(args.model_name) audios = os.listdir(args.input_path) for file in tq.tqdm(audio...
load_dotenv() args = arg_parse() config = Config() config.device = args.device if args.device else config.device config.is_half = args.is_half if args.is_half else config.is_half vc = VC(config) vc.get_vc(args.model_name) audios = os.listdir(args.input_path) for file in tq.tqdm(audio...
62
527
333
860
import argparse import os import sys print("Command-line arguments:", sys.argv) now_dir = os.getcwd() sys.path.append(now_dir) import sys import tqdm as tq from dotenv import load_dotenv from scipy.io import wavfile from configs.config import Config from infer.modules.vc.modules import VC def arg_parse() -> tuple...
import argparse import os import sys print("Command-line arguments:", sys.argv) now_dir = os.getcwd() sys.path.append(now_dir) import sys import tqdm as tq from dotenv import load_dotenv from scipy.io import wavfile from configs.config import Config from infer.modules.vc.modules import VC def arg_parse() -> tuple...
6,136
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/tools/cmd/infer_cli.py
19,20
1,68
arg_parse
20,41
20,41
import argparse import os import sys now_dir = os.getcwd() sys.path.append(now_dir) from dotenv import load_dotenv from scipy.io import wavfile from configs.config import Config from infer.modules.vc.modules import VC #### # USAGE # # In your Terminal or CMD or whatever def arg_parse() -> tuple: FILL_FUNC_BODYdef ...
import argparse import os import sys now_dir = os.getcwd() sys.path.append(now_dir) from dotenv import load_dotenv from scipy.io import wavfile from configs.config import Config from infer.modules.vc.modules import VC #### # USAGE # # In your Terminal or CMD or whatever def arg_parse() -> tuple: FILL_FUNC_BODYdef ...
parser = argparse.ArgumentParser() parser.add_argument("--f0up_key", type=int, default=0) parser.add_argument("--input_path", type=str, help="input path") parser.add_argument("--index_path", type=str, help="index path") parser.add_argument("--f0method", type=str, default="harvest", help="harvest or ...
parser = argparse.ArgumentParser() parser.add_argument("--f0up_key", type=int, default=0) parser.add_argument("--input_path", type=str, help="input path") parser.add_argument("--index_path", type=str, help="index path") parser.add_argument("--f0method", type=str, default="harvest", help="harvest or ...
71
358
406
764
import argparse import os import sys now_dir = os.getcwd() sys.path.append(now_dir) from dotenv import load_dotenv from scipy.io import wavfile from configs.config import Config from infer.modules.vc.modules import VC #### # USAGE # # In your Terminal or CMD or whatever def arg_parse() -> tuple: FILL_FUNC_BODYdef ...
import argparse import os import sys now_dir = os.getcwd() sys.path.append(now_dir) from dotenv import load_dotenv from scipy.io import wavfile from configs.config import Config from infer.modules.vc.modules import VC #### # USAGE # # In your Terminal or CMD or whatever def arg_parse() -> tuple: FILL_FUNC_BODYdef ...
6,137
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/tools/download_models.py
10,11
1,80
dl_model
11,19
11,19
import os from pathlib import Path import requests RVC_DOWNLOAD_LINK = "https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/main/" BASE_DIR = Path(__file__).resolve().parent.parent def dl_model(link, model_name, dir_name): FILL_FUNC_BODYif __name__ == "__main__": print("Downloading hubert_base.pt...") ...
import os from pathlib import Path import requests RVC_DOWNLOAD_LINK = "https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/main/" BASE_DIR = Path(__file__).resolve().parent.parent def dl_model(link, model_name, dir_name): FILL_FUNC_BODYif __name__ == "__main__": print("Downloading hubert_base.pt...") ...
with requests.get(f"{link}{model_name}") as r: r.raise_for_status() os.makedirs(os.path.dirname(dir_name / model_name), exist_ok=True) with open(dir_name / model_name, "wb") as f: for chunk in r.iter_content(chunk_size=8192): f.write(chunk)
with requests.get(f"{link}{model_name}") as r: r.raise_for_status() os.makedirs(os.path.dirname(dir_name / model_name), exist_ok=True) with open(dir_name / model_name, "wb") as f: for chunk in r.iter_content(chunk_size=8192): f.write(chunk)
21
994
119
1,113
import os from pathlib import Path import requests RVC_DOWNLOAD_LINK = "https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/main/" BASE_DIR = Path(__file__).resolve().parent.parent def dl_model(link, model_name, dir_name): FILL_FUNC_BODYif __name__ == "__main__": print("Downloading hubert_base.pt...") ...
import os from pathlib import Path import requests RVC_DOWNLOAD_LINK = "https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/main/" BASE_DIR = Path(__file__).resolve().parent.parent def dl_model(link, model_name, dir_name): FILL_FUNC_BODYif __name__ == "__main__": print("Downloading hubert_base.pt...") ...
6,303
/home/hieuvd/dung_repo/raw/stars_01/SYSTRAN_faster-whisper/faster-whisper
/home/hieuvd/dung_repo/raw/stars_01/SYSTRAN_faster-whisper/faster-whisper/benchmark/speed_benchmark.py
18,19
1,32
measure_speed
19,30
19,30
import argparse import timeit from typing import Callable from utils import inference parser = argparse.ArgumentParser(description="Speed benchmark") parser.add_argument( "--repeat", type=int, default=3, help="Times an experiment will be run.", ) args = parser.parse_args() def measure_speed(func: C...
import argparse import timeit from typing import Callable from utils import inference parser = argparse.ArgumentParser(description="Speed benchmark") parser.add_argument( "--repeat", type=int, default=3, help="Times an experiment will be run.", ) args = parser.parse_args() def measure_speed(func: C...
# as written in https://docs.python.org/3/library/timeit.html#timeit.Timer.repeat, # min should be taken rather than the average runtimes = timeit.repeat( func, repeat=args.repeat, number=10, ) print(runtimes) print("Min execution time: %.3fs" % (min(runtimes) / 10.0))
# as written in https://docs.python.org/3/library/timeit.html#timeit.Timer.repeat, # min should be taken rather than the average runtimes = timeit.repeat( func, repeat=args.repeat, number=10, ) print(runtimes) print("Min execution time: %.3fs" % (min(runtimes) / 10.0))
30
133
123
256
import argparse import timeit from typing import Callable from utils import inference parser = argparse.ArgumentParser(description="Speed benchmark") parser.add_argument( "--repeat", type=int, default=3, help="Times an experiment will be run.", ) args = parser.parse_args() def measure_speed(func: C...
import argparse import timeit from typing import Callable from utils import inference parser = argparse.ArgumentParser(description="Speed benchmark") parser.add_argument( "--repeat", type=int, default=3, help="Times an experiment will be run.", ) args = parser.parse_args() def measure_speed(func: C...
6,304
/home/hieuvd/dung_repo/raw/stars_01/SYSTRAN_faster-whisper/faster-whisper
/home/hieuvd/dung_repo/raw/stars_01/SYSTRAN_faster-whisper/faster-whisper/benchmark/utils.py
12,13
1,40
inference
13,18
13,18
import logging from threading import Thread from typing import Optional from faster_whisper import WhisperModel model_path = "large-v3" model = WhisperModel(model_path, device="cuda") def inference(): FILL_FUNC_BODYdef get_logger(name: Optional[str] = None) -> logging.Logger: formatter = logging.Formatter("%(l...
import logging from threading import Thread from typing import Optional from faster_whisper import WhisperModel model_path = "large-v3" model = WhisperModel(model_path, device="cuda") def inference(): FILL_FUNC_BODYdef get_logger(name: Optional[str] = None) -> logging.Logger: formatter = logging.Formatter("%(l...
segments, info = model.transcribe("benchmark.m4a", language="fr") for segment in segments: print("[%.2fs -> %.2fs] %s" % (segment.start, segment.end, segment.text))
segments, info = model.transcribe("benchmark.m4a", language="fr") for segment in segments: print("[%.2fs -> %.2fs] %s" % (segment.start, segment.end, segment.text))
17
265
71
336
import logging from threading import Thread from typing import Optional from faster_whisper import WhisperModel model_path = "large-v3" model = WhisperModel(model_path, device="cuda") def inference(): FILL_FUNC_BODYdef get_logger(name: Optional[str] = None) -> logging.Logger: formatter = logging.Formatter("%(l...
import logging from threading import Thread from typing import Optional from faster_whisper import WhisperModel model_path = "large-v3" model = WhisperModel(model_path, device="cuda") def inference(): FILL_FUNC_BODYdef get_logger(name: Optional[str] = None) -> logging.Logger: formatter = logging.Formatter("%(l...
6,305
/home/hieuvd/dung_repo/raw/stars_01/SYSTRAN_faster-whisper/faster-whisper
/home/hieuvd/dung_repo/raw/stars_01/SYSTRAN_faster-whisper/faster-whisper/benchmark/utils.py
35,36
28,40
run
MyThread
36,38
36,38
class MyThread(Thread): def __init__(self, func, params): super(MyThread, self).__init__() self.func = func self.params = params self.result = None def run(self): FILL_FUNC_BODY def get_result(self): return self.result
class MyThread(Thread): def __init__(self, func, params): super(MyThread, self).__init__() self.func = func self.params = params self.result = None def run(self): FILL_FUNC_BODY def get_result(self): return self.result
self.result = self.func(*self.params)
self.result = self.func(*self.params)
3
86
17
103
import logging from threading import Thread from typing import Optional from faster_whisper import WhisperModel model_path = "large-v3" model = WhisperModel(model_path, device="cuda") def inference(): segments, info = model.transcribe("benchmark.m4a", language="fr") for segment in segments: print("...
import logging from threading import Thread from typing import Optional from faster_whisper import WhisperModel model_path = "large-v3" model = WhisperModel(model_path, device="cuda") def inference(): segments, info = model.transcribe("benchmark.m4a", language="fr") for segment in segments: print("...
6,306
/home/hieuvd/dung_repo/raw/stars_01/SYSTRAN_faster-whisper/faster-whisper
/home/hieuvd/dung_repo/raw/stars_01/SYSTRAN_faster-whisper/faster-whisper/faster_whisper/audio.py
19,24
1,120
decode_audio
37,75
24,75
"""We use the PyAV library to decode the audio: https://github.com/PyAV-Org/PyAV The advantage of PyAV is that it bundles the FFmpeg libraries so there is no additional system dependencies. FFmpeg does not need to be installed on the system. However, the API is quite low-level so we need to manipulate audio frames di...
"""We use the PyAV library to decode the audio: https://github.com/PyAV-Org/PyAV The advantage of PyAV is that it bundles the FFmpeg libraries so there is no additional system dependencies. FFmpeg does not need to be installed on the system. However, the API is quite low-level so we need to manipulate audio frames di...
resampler = av.audio.resampler.AudioResampler( format="s16", layout="mono" if not split_stereo else "stereo", rate=sampling_rate, ) raw_buffer = io.BytesIO() dtype = None with av.open(input_file, mode="r", metadata_errors="ignore") as container: frames = container.d...
"""Decodes the audio. Args: input_file: Path to the input file or a file-like object. sampling_rate: Resample the audio to this sample rate. split_stereo: Return separate left and right channels. Returns: A float32 Numpy array. If `split_stereo` is enabled, the function retu...
101
692
396
1,088
"""We use the PyAV library to decode the audio: https://github.com/PyAV-Org/PyAV The advantage of PyAV is that it bundles the FFmpeg libraries so there is no additional system dependencies. FFmpeg does not need to be installed on the system. However, the API is quite low-level so we need to manipulate audio frames di...
"""We use the PyAV library to decode the audio: https://github.com/PyAV-Org/PyAV The advantage of PyAV is that it bundles the FFmpeg libraries so there is no additional system dependencies. FFmpeg does not need to be installed on the system. However, the API is quite low-level so we need to manipulate audio frames di...
6,307
/home/hieuvd/dung_repo/raw/stars_01/SYSTRAN_faster-whisper/faster-whisper
/home/hieuvd/dung_repo/raw/stars_01/SYSTRAN_faster-whisper/faster-whisper/faster_whisper/feature_extractor.py
74,75
5,171
fram_wave
FeatureExtractor
83,118
75,118
class FeatureExtractor: def __init__( self, feature_size=80, sampling_rate=16000, hop_length=160, chunk_length=30, n_fft=400, ): self.n_fft = n_fft self.hop_length = hop_length self.chunk_length = chunk_length self.n_samples = chunk...
class FeatureExtractor: def __init__( self, feature_size=80, sampling_rate=16000, hop_length=160, chunk_length=30, n_fft=400, ): self.n_fft = n_fft self.hop_length = hop_length self.chunk_length = chunk_length self.n_samples = chunk...
frames = [] for i in range(0, waveform.shape[0] + 1, self.hop_length): half_window = (self.n_fft - 1) // 2 + 1 if center: start = i - half_window if i > half_window else 0 end = ( i + half_window if i < wavef...
""" Transform a raw waveform into a list of smaller waveforms. The window length defines how much of the signal is contain in each frame (smalle waveform), while the hope length defines the step between the beginning of each new frame. Centering is done by reflecting the ...
113
1,616
397
2,013
import numpy as np # Adapted from https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/feature_extraction_whisper.py # noqa: E501 class FeatureExtractor: def __init__( self, feature_size=80, sampling_rate=16000, hop_length=160, chunk_length...
import numpy as np # Adapted from https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/feature_extraction_whisper.py # noqa: E501 class FeatureExtractor: def __init__( self, feature_size=80, sampling_rate=16000, hop_length=160, chunk_length...
6,308
/home/hieuvd/dung_repo/raw/stars_01/SYSTRAN_faster-whisper/faster-whisper
/home/hieuvd/dung_repo/raw/stars_01/SYSTRAN_faster-whisper/faster-whisper/faster_whisper/tokenizer.py
108,111
9,172
split_to_word_tokens
Tokenizer
111,119
111,119
class Tokenizer: """Simple wrapper around a tokenizers.Tokenizer.""" def __init__( self, tokenizer: tokenizers.Tokenizer, multilingual: bool, task: Optional[str] = None, language: Optional[str] = None, ): self.tokenizer = tokenizer if multilingual: ...
class Tokenizer: """Simple wrapper around a tokenizers.Tokenizer.""" def __init__( self, tokenizer: tokenizers.Tokenizer, multilingual: bool, task: Optional[str] = None, language: Optional[str] = None, ): self.tokenizer = tokenizer if multilingual: ...
if self.language_code in {"zh", "ja", "th", "lo", "my", "yue"}: # These languages don't typically use spaces, so it is difficult to split words # without morpheme analysis. Here, we instead split words at any # position where the tokens are decoded as valid unicode points ...
if self.language_code in {"zh", "ja", "th", "lo", "my", "yue"}: # These languages don't typically use spaces, so it is difficult to split words # without morpheme analysis. Here, we instead split words at any # position where the tokens are decoded as valid unicode points ...
49
1,544
127
1,671
import string from functools import cached_property from typing import List, Optional, Tuple import tokenizers class Tokenizer: """Simple wrapper around a tokenizers.Tokenizer.""" def __init__( self, tokenizer: tokenizers.Tokenizer, multilingual: bool, task: Optional[str] = ...
import string from functools import cached_property from typing import List, Optional, Tuple import tokenizers class Tokenizer: """Simple wrapper around a tokenizers.Tokenizer.""" def __init__( self, tokenizer: tokenizers.Tokenizer, multilingual: bool, task: Optional[str] = ...
6,312
/home/hieuvd/dung_repo/raw/stars_01/SYSTRAN_faster-whisper/faster-whisper
/home/hieuvd/dung_repo/raw/stars_01/SYSTRAN_faster-whisper/faster-whisper/faster_whisper/vad.py
264,265
244,292
get_initial_state
SileroVADModel
265,269
265,269
class SileroVADModel: def __init__(self, path): try: import onnxruntime except ImportError as e: raise RuntimeError( "Applying the VAD filter requires the onnxruntime package" ) from e opts = onnxruntime.SessionOptions() opts.inter...
class SileroVADModel: def __init__(self, path): try: import onnxruntime except ImportError as e: raise RuntimeError( "Applying the VAD filter requires the onnxruntime package" ) from e opts = onnxruntime.SessionOptions() opts.inter...
h = np.zeros((2, batch_size, 64), dtype=np.float32) c = np.zeros((2, batch_size, 64), dtype=np.float32) return h, c
h = np.zeros((2, batch_size, 64), dtype=np.float32) c = np.zeros((2, batch_size, 64), dtype=np.float32) return h, c
15
406
67
473
import bisect import functools import os import warnings from typing import List, NamedTuple, Optional import numpy as np from faster_whisper.utils import get_assets_path # The code below is adapted from https://github.com/snakers4/silero-vad. class VadOptions(NamedTuple): """VAD options. Attributes: ...
import bisect import functools import os import warnings from typing import List, NamedTuple, Optional import numpy as np from faster_whisper.utils import get_assets_path # The code below is adapted from https://github.com/snakers4/silero-vad. class VadOptions(NamedTuple): """VAD options. Attributes: ...
6,313
/home/hieuvd/dung_repo/raw/stars_01/SYSTRAN_faster-whisper/faster-whisper
/home/hieuvd/dung_repo/raw/stars_01/SYSTRAN_faster-whisper/faster-whisper/faster_whisper/vad.py
229,230
199,237
get_chunk_index
SpeechTimestampsMap
230,237
230,237
class SpeechTimestampsMap: """Helper class to restore original speech timestamps.""" def __init__(self, chunks: List[dict], sampling_rate: int, time_precision: int = 2): self.sampling_rate = sampling_rate self.time_precision = time_precision self.chunk_end_sample = [] self.total...
class SpeechTimestampsMap: """Helper class to restore original speech timestamps.""" def __init__(self, chunks: List[dict], sampling_rate: int, time_precision: int = 2): self.sampling_rate = sampling_rate self.time_precision = time_precision self.chunk_end_sample = [] self.total...
sample = int(time * self.sampling_rate) return min( bisect.bisect(self.chunk_end_sample, sample), len(self.chunk_end_sample) - 1, )
sample = int(time * self.sampling_rate) return min( bisect.bisect(self.chunk_end_sample, sample), len(self.chunk_end_sample) - 1, )
13
342
68
410
import bisect import functools import os import warnings from typing import List, NamedTuple, Optional import numpy as np from faster_whisper.utils import get_assets_path # The code below is adapted from https://github.com/snakers4/silero-vad. class VadOptions(NamedTuple): """VAD options. Attributes: ...
import bisect import functools import os import warnings from typing import List, NamedTuple, Optional import numpy as np from faster_whisper.utils import get_assets_path # The code below is adapted from https://github.com/snakers4/silero-vad. class VadOptions(NamedTuple): """VAD options. Attributes: ...
6,314
/home/hieuvd/dung_repo/raw/stars_01/SYSTRAN_faster-whisper/faster-whisper
/home/hieuvd/dung_repo/raw/stars_01/SYSTRAN_faster-whisper/faster-whisper/setup.py
22,23
1,69
get_requirements
23,27
23,27
import os from setuptools import find_packages, setup base_dir = os.path.dirname(os.path.abspath(__file__)) def get_long_description(): readme_path = os.path.join(base_dir, "README.md") with open(readme_path, encoding="utf-8") as readme_file: return readme_file.read() def get_project_version(): ...
import os from setuptools import find_packages, setup base_dir = os.path.dirname(os.path.abspath(__file__)) def get_long_description(): readme_path = os.path.join(base_dir, "README.md") with open(readme_path, encoding="utf-8") as readme_file: return readme_file.read() def get_project_version(): ...
with open(path, encoding="utf-8") as requirements: return [requirement.strip() for requirement in requirements]
with open(path, encoding="utf-8") as requirements: return [requirement.strip() for requirement in requirements]
11
673
37
710
import os from setuptools import find_packages, setup base_dir = os.path.dirname(os.path.abspath(__file__)) def get_long_description(): readme_path = os.path.join(base_dir, "README.md") with open(readme_path, encoding="utf-8") as readme_file: return readme_file.read() def get_project_version(): ...
import os from setuptools import find_packages, setup base_dir = os.path.dirname(os.path.abspath(__file__)) def get_long_description(): readme_path = os.path.join(base_dir, "README.md") with open(readme_path, encoding="utf-8") as readme_file: return readme_file.read() def get_project_version(): ...
6,634
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM-6B/ChatGLM-6B
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM-6B/ChatGLM-6B/cli_demo.py
29,30
1,59
main
30,57
30,57
import os import platform import signal from transformers import AutoTokenizer, AutoModel import readline tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).half().cuda() model = model.eval() os_name = pla...
import os import platform import signal from transformers import AutoTokenizer, AutoModel import readline tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).half().cuda() model = model.eval() os_name = pla...
history = [] global stop_stream print("欢迎使用 ChatGLM-6B 模型,输入内容即可进行对话,clear 清空对话历史,stop 终止程序") while True: query = input("\n用户:") if query.strip() == "stop": break if query.strip() == "clear": history = [] os.system(clear_command) pr...
history = [] global stop_stream print("欢迎使用 ChatGLM-6B 模型,输入内容即可进行对话,clear 清空对话历史,stop 终止程序") while True: query = input("\n用户:") if query.strip() == "stop": break if query.strip() == "clear": history = [] os.system(clear_command) pr...
68
290
302
592
import os import platform import signal from transformers import AutoTokenizer, AutoModel import readline tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).half().cuda() model = model.eval() os_name = pla...
import os import platform import signal from transformers import AutoTokenizer, AutoModel import readline tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).half().cuda() model = model.eval() os_name = pla...
6,635
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM-6B/ChatGLM-6B
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM-6B/ChatGLM-6B/cli_demo_vision.py
31,32
1,65
main
32,63
32,63
import os import platform import signal import sys from transformers import AutoTokenizer, AutoModel import readline tokenizer = AutoTokenizer.from_pretrained("THUDM/visualglm-6b", trust_remote_code=True) model = AutoModel.from_pretrained("THUDM/visualglm-6b", trust_remote_code=True).half().cuda() model = model.eval(...
import os import platform import signal import sys from transformers import AutoTokenizer, AutoModel import readline tokenizer = AutoTokenizer.from_pretrained("THUDM/visualglm-6b", trust_remote_code=True) model = AutoModel.from_pretrained("THUDM/visualglm-6b", trust_remote_code=True).half().cuda() model = model.eval(...
global stop_stream while True: history = [] prefix = "欢迎使用 VisualGLM-6B 模型,输入图片路径和内容即可进行对话,clear 清空对话历史,stop 终止程序" print(prefix) image_path = input("\n请输入图片路径:") if image_path == "stop": break prefix = prefix + "\n" + image_path query = "描述这张图片...
global stop_stream while True: history = [] prefix = "欢迎使用 VisualGLM-6B 模型,输入图片路径和内容即可进行对话,clear 清空对话历史,stop 终止程序" print(prefix) image_path = input("\n请输入图片路径:") if image_path == "stop": break prefix = prefix + "\n" + image_path query = "描述这张图片...
85
265
338
603
import os import platform import signal import sys from transformers import AutoTokenizer, AutoModel import readline tokenizer = AutoTokenizer.from_pretrained("THUDM/visualglm-6b", trust_remote_code=True) model = AutoModel.from_pretrained("THUDM/visualglm-6b", trust_remote_code=True).half().cuda() model = model.eval(...
import os import platform import signal import sys from transformers import AutoTokenizer, AutoModel import readline tokenizer = AutoTokenizer.from_pretrained("THUDM/visualglm-6b", trust_remote_code=True) model = AutoModel.from_pretrained("THUDM/visualglm-6b", trust_remote_code=True).half().cuda() model = model.eval(...
6,637
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM-6B/ChatGLM-6B
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM-6B/ChatGLM-6B/utils.py
8,9
1,55
auto_configure_device_map
9,38
9,38
import os from typing import Dict, Tuple, Union, Optional from torch.nn import Module from transformers import AutoModel def auto_configure_device_map(num_gpus: int) -> Dict[str, int]: FILL_FUNC_BODYdef load_model_on_gpus(checkpoint_path: Union[str, os.PathLike], num_gpus: int = 2, device_map:...
import os from typing import Dict, Tuple, Union, Optional from torch.nn import Module from transformers import AutoModel def auto_configure_device_map(num_gpus: int) -> Dict[str, int]: FILL_FUNC_BODYdef load_model_on_gpus(checkpoint_path: Union[str, os.PathLike], num_gpus: int = 2, device_map:...
# transformer.word_embeddings 占用1层 # transformer.final_layernorm 和 lm_head 占用1层 # transformer.layers 占用 28 层 # 总共30层分配到num_gpus张卡上 num_trans_layers = 28 per_gpu_layers = 30 / num_gpus # bugfix: 在linux中调用torch.embedding传入的weight,input不在同一device上,导致RuntimeError # windows下 model.device 会被设...
# transformer.word_embeddings 占用1层 # transformer.final_layernorm 和 lm_head 占用1层 # transformer.layers 占用 28 层 # 总共30层分配到num_gpus张卡上 num_trans_layers = 28 per_gpu_layers = 30 / num_gpus # bugfix: 在linux中调用torch.embedding传入的weight,input不在同一device上,导致RuntimeError # windows下 model.device 会被设...
82
277
418
695
import os from typing import Dict, Tuple, Union, Optional from torch.nn import Module from transformers import AutoModel def auto_configure_device_map(num_gpus: int) -> Dict[str, int]: FILL_FUNC_BODYdef load_model_on_gpus(checkpoint_path: Union[str, os.PathLike], num_gpus: int = 2, device_map:...
import os from typing import Dict, Tuple, Union, Optional from torch.nn import Module from transformers import AutoModel def auto_configure_device_map(num_gpus: int) -> Dict[str, int]: FILL_FUNC_BODYdef load_model_on_gpus(checkpoint_path: Union[str, os.PathLike], num_gpus: int = 2, device_map:...
6,638
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM2-6B/ChatGLM2-6B
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM2-6B/ChatGLM2-6B/cli_demo.py
19,20
1,61
build_prompt
20,27
20,27
import os import platform import signal from transformers import AutoTokenizer, AutoModel import readline tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True) model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True).cuda() # 多显卡支持,使用下面两行代替上面一行,将num_gpus改为你实际的显卡数量...
import os import platform import signal from transformers import AutoTokenizer, AutoModel import readline tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True) model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True).cuda() # 多显卡支持,使用下面两行代替上面一行,将num_gpus改为你实际的显卡数量...
prompt = "欢迎使用 ChatGLM2-6B 模型,输入内容即可进行对话,clear 清空对话历史,stop 终止程序" for query, response in history: prompt += f"\n\n用户:{query}" prompt += f"\n\nChatGLM2-6B:{response}" return prompt
prompt = "欢迎使用 ChatGLM2-6B 模型,输入内容即可进行对话,clear 清空对话历史,stop 终止程序" for query, response in history: prompt += f"\n\n用户:{query}" prompt += f"\n\nChatGLM2-6B:{response}" return prompt
20
574
99
673
import os import platform import signal from transformers import AutoTokenizer, AutoModel import readline tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True) model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True).cuda() # 多显卡支持,使用下面两行代替上面一行,将num_gpus改为你实际的显卡数量...
import os import platform import signal from transformers import AutoTokenizer, AutoModel import readline tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True) model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True).cuda() # 多显卡支持,使用下面两行代替上面一行,将num_gpus改为你实际的显卡数量...
6,639
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM2-6B/ChatGLM2-6B
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM2-6B/ChatGLM2-6B/ptuning/trainer.py
37,38
32,71
_save
PrefixTrainer
38,71
38,71
class PrefixTrainer(Trainer): def __init__(self, *args, save_changed=False, **kwargs): self.save_changed = save_changed super().__init__(*args, **kwargs) def _save(self, output_dir: Optional[str] = None, state_dict=None): FILL_FUNC_BODY
class PrefixTrainer(Trainer): def __init__(self, *args, save_changed=False, **kwargs): self.save_changed = save_changed super().__init__(*args, **kwargs) def _save(self, output_dir: Optional[str] = None, state_dict=None): FILL_FUNC_BODY
# If we are executing this function, we are the process zero, so we don't check for that. output_dir = output_dir if output_dir is not None else self.args.output_dir os.makedirs(output_dir, exist_ok=True) logger.info(f"Saving model checkpoint to {output_dir}") # Save a trained mo...
# If we are executing this function, we are the process zero, so we don't check for that. output_dir = output_dir if output_dir is not None else self.args.output_dir os.makedirs(output_dir, exist_ok=True) logger.info(f"Saving model checkpoint to {output_dir}") # Save a trained mo...
140
92
549
641
# coding=utf-8 # Copyright 2020-present the HuggingFace Inc. team. # # 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 ap...
# coding=utf-8 # Copyright 2020-present the HuggingFace Inc. team. # # 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 ap...
6,640
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM2-6B/ChatGLM2-6B
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM2-6B/ChatGLM2-6B/utils.py
8,9
1,60
auto_configure_device_map
9,45
9,45
import os from typing import Dict, Tuple, Union, Optional from torch.nn import Module from transformers import AutoModel def auto_configure_device_map(num_gpus: int) -> Dict[str, int]: FILL_FUNC_BODYdef load_model_on_gpus(checkpoint_path: Union[str, os.PathLike], num_gpus: int = 2, device_map:...
import os from typing import Dict, Tuple, Union, Optional from torch.nn import Module from transformers import AutoModel def auto_configure_device_map(num_gpus: int) -> Dict[str, int]: FILL_FUNC_BODYdef load_model_on_gpus(checkpoint_path: Union[str, os.PathLike], num_gpus: int = 2, device_map:...
# transformer.word_embeddings 占用1层 # transformer.final_layernorm 和 lm_head 占用1层 # transformer.layers 占用 28 层 # 总共30层分配到num_gpus张卡上 num_trans_layers = 28 per_gpu_layers = 30 / num_gpus # bugfix: 在linux中调用torch.embedding传入的weight,input不在同一device上,导致RuntimeError # windows下 model.device 会被设...
# transformer.word_embeddings 占用1层 # transformer.final_layernorm 和 lm_head 占用1层 # transformer.layers 占用 28 层 # 总共30层分配到num_gpus张卡上 num_trans_layers = 28 per_gpu_layers = 30 / num_gpus # bugfix: 在linux中调用torch.embedding传入的weight,input不在同一device上,导致RuntimeError # windows下 model.device 会被设...
92
275
520
795
import os from typing import Dict, Tuple, Union, Optional from torch.nn import Module from transformers import AutoModel def auto_configure_device_map(num_gpus: int) -> Dict[str, int]: FILL_FUNC_BODYdef load_model_on_gpus(checkpoint_path: Union[str, os.PathLike], num_gpus: int = 2, device_map:...
import os from typing import Dict, Tuple, Union, Optional from torch.nn import Module from transformers import AutoModel def auto_configure_device_map(num_gpus: int) -> Dict[str, int]: FILL_FUNC_BODYdef load_model_on_gpus(checkpoint_path: Union[str, os.PathLike], num_gpus: int = 2, device_map:...
6,641
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM2-6B/ChatGLM2-6B
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM2-6B/ChatGLM2-6B/web_demo2.py
12,14
1,71
get_model
14,23
14,23
from transformers import AutoModel, AutoTokenizer import streamlit as st st.set_page_config( page_title="ChatGLM2-6b 演示", page_icon=":robot:", layout='wide' ) @st.cache_resource def get_model(): FILL_FUNC_BODYtokenizer, model = get_model() st.title("ChatGLM2-6B") max_length = st.sidebar.slider( 'm...
from transformers import AutoModel, AutoTokenizer import streamlit as st st.set_page_config( page_title="ChatGLM2-6b 演示", page_icon=":robot:", layout='wide' ) @st.cache_resource def get_model(): FILL_FUNC_BODYtokenizer, model = get_model() st.title("ChatGLM2-6B") max_length = st.sidebar.slider( 'm...
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True) model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True).cuda() # 多显卡支持,使用下面两行代替上面一行,将num_gpus改为你实际的显卡数量 # from utils import load_model_on_gpus # model = load_model_on_gpus("THUDM/chatglm2-6b...
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True) model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True).cuda() # 多显卡支持,使用下面两行代替上面一行,将num_gpus改为你实际的显卡数量 # from utils import load_model_on_gpus # model = load_model_on_gpus("THUDM/chatglm2-6b...
26
674
175
849
from transformers import AutoModel, AutoTokenizer import streamlit as st st.set_page_config( page_title="ChatGLM2-6b 演示", page_icon=":robot:", layout='wide' ) @st.cache_resource def get_model(): FILL_FUNC_BODYtokenizer, model = get_model() st.title("ChatGLM2-6B") max_length = st.sidebar.slider( 'm...
from transformers import AutoModel, AutoTokenizer import streamlit as st st.set_page_config( page_title="ChatGLM2-6b 演示", page_icon=":robot:", layout='wide' ) @st.cache_resource def get_model(): FILL_FUNC_BODYtokenizer, model = get_model() st.title("ChatGLM2-6B") max_length = st.sidebar.slider( 'm...
6,642
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3/Intel_device_demo/ipex_llm_cpu_demo/openai_api_request.py
20,21
1,90
function_chat
21,56
21,56
""" This script is an example of using the OpenAI API to create various interactions with a ChatGLM3 model. It includes functions to: 1. Conduct a basic chat session, asking about weather conditions in multiple cities. 2. Initiate a simple chat in Chinese, asking the model to tell a short story. 3. Retrieve and print ...
""" This script is an example of using the OpenAI API to create various interactions with a ChatGLM3 model. It includes functions to: 1. Conduct a basic chat session, asking about weather conditions in multiple cities. 2. Initiate a simple chat in Chinese, asking the model to tell a short story. 3. Retrieve and print ...
messages = [{"role": "user", "content": "What's the weather like in San Francisco, Tokyo, and Paris?"}] tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather in a given location", ...
messages = [{"role": "user", "content": "What's the weather like in San Francisco, Tokyo, and Paris?"}] tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather in a given location", ...
84
504
319
823
""" This script is an example of using the OpenAI API to create various interactions with a ChatGLM3 model. It includes functions to: 1. Conduct a basic chat session, asking about weather conditions in multiple cities. 2. Initiate a simple chat in Chinese, asking the model to tell a short story. 3. Retrieve and print ...
""" This script is an example of using the OpenAI API to create various interactions with a ChatGLM3 model. It includes functions to: 1. Conduct a basic chat session, asking about weather conditions in multiple cities. 2. Initiate a simple chat in Chinese, asking the model to tell a short story. 3. Retrieve and print ...
6,643
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3/Intel_device_demo/ipex_llm_cpu_demo/utils.py
46,48
1,187
generate_stream_chatglm3
48,122
48,122
import gc import json import torch from transformers import PreTrainedModel, PreTrainedTokenizer from transformers.generation.logits_process import LogitsProcessor from typing import Union, Tuple class InvalidScoreLogitsProcessor(LogitsProcessor): def __call__( self, input_ids: torch.LongTensor, score...
import gc import json import torch from transformers import PreTrainedModel, PreTrainedTokenizer from transformers.generation.logits_process import LogitsProcessor from typing import Union, Tuple class InvalidScoreLogitsProcessor(LogitsProcessor): def __call__( self, input_ids: torch.LongTensor, score...
messages = params["messages"] tools = params["tools"] temperature = float(params.get("temperature", 1.0)) repetition_penalty = float(params.get("repetition_penalty", 1.0)) top_p = float(params.get("top_p", 1.0)) max_new_tokens = int(params.get("max_tokens", 256)) echo = params.get("echo", Tr...
messages = params["messages"] tools = params["tools"] temperature = float(params.get("temperature", 1.0)) repetition_penalty = float(params.get("repetition_penalty", 1.0)) top_p = float(params.get("top_p", 1.0)) max_new_tokens = int(params.get("max_tokens", 256)) echo = params.get("echo", Tr...
186
958
875
1,833
import gc import json import torch from transformers import PreTrainedModel, PreTrainedTokenizer from transformers.generation.logits_process import LogitsProcessor from typing import Union, Tuple class InvalidScoreLogitsProcessor(LogitsProcessor): def __call__( self, input_ids: torch.LongTensor, score...
import gc import json import torch from transformers import PreTrainedModel, PreTrainedTokenizer from transformers.generation.logits_process import LogitsProcessor from typing import Union, Tuple class InvalidScoreLogitsProcessor(LogitsProcessor): def __call__( self, input_ids: torch.LongTensor, score...
6,644
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3/basic_demo/cli_demo.py
28,29
1,58
main
29,56
29,56
import os import platform from transformers import AutoTokenizer, AutoModel MODEL_PATH = os.environ.get('MODEL_PATH', 'THUDM/chatglm3-6b') TOKENIZER_PATH = os.environ.get("TOKENIZER_PATH", MODEL_PATH) tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_PATH, trust_remote_code=True) model = AutoModel.from_pretrained(M...
import os import platform from transformers import AutoTokenizer, AutoModel MODEL_PATH = os.environ.get('MODEL_PATH', 'THUDM/chatglm3-6b') TOKENIZER_PATH = os.environ.get("TOKENIZER_PATH", MODEL_PATH) tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_PATH, trust_remote_code=True) model = AutoModel.from_pretrained(M...
past_key_values, history = None, [] global stop_stream print(welcome_prompt) while True: query = input("\n用户:") if query.strip() == "stop": break if query.strip() == "clear": past_key_values, history = None, [] os.system(clear_command) ...
past_key_values, history = None, [] global stop_stream print(welcome_prompt) while True: query = input("\n用户:") if query.strip() == "stop": break if query.strip() == "clear": past_key_values, history = None, [] os.system(clear_command) ...
61
362
284
646
import os import platform from transformers import AutoTokenizer, AutoModel MODEL_PATH = os.environ.get('MODEL_PATH', 'THUDM/chatglm3-6b') TOKENIZER_PATH = os.environ.get("TOKENIZER_PATH", MODEL_PATH) tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_PATH, trust_remote_code=True) model = AutoModel.from_pretrained(M...
import os import platform from transformers import AutoTokenizer, AutoModel MODEL_PATH = os.environ.get('MODEL_PATH', 'THUDM/chatglm3-6b') TOKENIZER_PATH = os.environ.get("TOKENIZER_PATH", MODEL_PATH) tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_PATH, trust_remote_code=True) model = AutoModel.from_pretrained(M...
6,645
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3/basic_demo/cli_demo_bad_word_ids.py
44,45
1,88
main
45,86
45,86
""" This script demonstrates how to use the `bad_words_ids` argument in the context of a conversational AI model to filter out unwanted words or phrases from the model's responses. It's designed to showcase a fundamental method of content moderation within AI-generated text, particularly useful in scenarios where maint...
""" This script demonstrates how to use the `bad_words_ids` argument in the context of a conversational AI model to filter out unwanted words or phrases from the model's responses. It's designed to showcase a fundamental method of content moderation within AI-generated text, particularly useful in scenarios where maint...
past_key_values, history = None, [] global stop_stream print(welcome_prompt) while True: query = input("\n用户:") if query.strip().lower() == "stop": break if query.strip().lower() == "clear": past_key_values, history = None, [] os.system(clear_c...
past_key_values, history = None, [] global stop_stream print(welcome_prompt) while True: query = input("\n用户:") if query.strip().lower() == "stop": break if query.strip().lower() == "clear": past_key_values, history = None, [] os.system(clear_c...
122
577
455
1,032
""" This script demonstrates how to use the `bad_words_ids` argument in the context of a conversational AI model to filter out unwanted words or phrases from the model's responses. It's designed to showcase a fundamental method of content moderation within AI-generated text, particularly useful in scenarios where maint...
""" This script demonstrates how to use the `bad_words_ids` argument in the context of a conversational AI model to filter out unwanted words or phrases from the model's responses. It's designed to showcase a fundamental method of content moderation within AI-generated text, particularly useful in scenarios where maint...
6,646
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3/basic_demo/web_demo_streamlit.py
28,30
1,87
get_model
30,37
30,37
""" This script is a simple web demo based on Streamlit, showcasing the use of the ChatGLM3-6B model. For a more comprehensive web demo, it is recommended to use 'composite_demo'. Usage: - Run the script using Streamlit: `streamlit run web_demo_streamlit.py` - Adjust the model parameters from the sidebar. - Enter ques...
""" This script is a simple web demo based on Streamlit, showcasing the use of the ChatGLM3-6B model. For a more comprehensive web demo, it is recommended to use 'composite_demo'. Usage: - Run the script using Streamlit: `streamlit run web_demo_streamlit.py` - Adjust the model parameters from the sidebar. - Enter ques...
tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_PATH, trust_remote_code=True) model = AutoModel.from_pretrained(MODEL_PATH, trust_remote_code=True, device_map="auto").eval() return tokenizer, model # 加载Chatglm3的model和tokenizer
tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_PATH, trust_remote_code=True) model = AutoModel.from_pretrained(MODEL_PATH, trust_remote_code=True, device_map="auto").eval() return tokenizer, model # 加载Chatglm3的model和tokenizer
14
930
95
1,025
""" This script is a simple web demo based on Streamlit, showcasing the use of the ChatGLM3-6B model. For a more comprehensive web demo, it is recommended to use 'composite_demo'. Usage: - Run the script using Streamlit: `streamlit run web_demo_streamlit.py` - Adjust the model parameters from the sidebar. - Enter ques...
""" This script is a simple web demo based on Streamlit, showcasing the use of the ChatGLM3-6B model. For a more comprehensive web demo, it is recommended to use 'composite_demo'. Usage: - Run the script using Streamlit: `streamlit run web_demo_streamlit.py` - Adjust the model parameters from the sidebar. - Enter ques...
6,647
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3/composite_demo/tool_registry.py
119,123
1,139
get_shell
126,136
123,136
""" This code is the tool registration part. By registering the tool, the model can call the tool. This code provides extended functionality to the model, enabling it to call and interact with a variety of utilities through defined interfaces. """ import copy import inspect from pprint import pformat import traceback ...
""" This code is the tool registration part. By registering the tool, the model can call the tool. This code provides extended functionality to the model, enabling it to call and interact with a variety of utilities through defined interfaces. """ import copy import inspect from pprint import pformat import traceback ...
if not isinstance(query, str): raise TypeError("Command must be a string") try: result = subprocess.run(query, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) return result.stdout except subprocess.CalledProcessError ...
""" Use shell to run command """ if not isinstance(query, str): raise TypeError("Command must be a string") try: result = subprocess.run(query, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) return result....
27
1,221
109
1,330
""" This code is the tool registration part. By registering the tool, the model can call the tool. This code provides extended functionality to the model, enabling it to call and interact with a variety of utilities through defined interfaces. """ import copy import inspect from pprint import pformat import traceback ...
""" This code is the tool registration part. By registering the tool, the model can call the tool. This code provides extended functionality to the model, enabling it to call and interact with a variety of utilities through defined interfaces. """ import copy import inspect from pprint import pformat import traceback ...
6,648
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3/langchain_demo/ChatGLM3.py
37,38
8,144
_tool_history
ChatGLM3
38,81
38,81
class ChatGLM3(LLM): max_token: int = 8192 do_sample: bool = True temperature: float = 0.8 top_p = 0.8 tokenizer: object = None model: object = None history: List = [] has_search: bool = False def __init__(self): super().__init__() @property def _llm_type(self) -> s...
class ChatGLM3(LLM): max_token: int = 8192 do_sample: bool = True temperature: float = 0.8 top_p = 0.8 tokenizer: object = None model: object = None history: List = [] has_search: bool = False def __init__(self): super().__init__() @property def _llm_type(self) -> s...
ans = [] tool_prompts = prompt.split( "You have access to the following tools:\n\n")[1].split("\n\nUse a json blob")[0].split("\n") tools_json = [] for tool_desc in tool_prompts: name = tool_desc.split(":")[0] description = tool_desc.split(", args:")...
ans = [] tool_prompts = prompt.split( "You have access to the following tools:\n\n")[1].split("\n\nUse a json blob")[0].split("\n") tools_json = [] for tool_desc in tool_prompts: name = tool_desc.split(":")[0] description = tool_desc.split(", args:")...
125
927
509
1,436
import ast import json from langchain.llms.base import LLM from transformers import AutoTokenizer, AutoModel, AutoConfig from typing import List, Optional class ChatGLM3(LLM): max_token: int = 8192 do_sample: bool = True temperature: float = 0.8 top_p = 0.8 tokenizer: object = None model: obje...
import ast import json from langchain.llms.base import LLM from transformers import AutoTokenizer, AutoModel, AutoConfig from typing import List, Optional class ChatGLM3(LLM): max_token: int = 8192 do_sample: bool = True temperature: float = 0.8 top_p = 0.8 tokenizer: object = None model: obje...
6,649
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3/langchain_demo/tools/Calculator.py
20,21
12,55
parameter_validation
Calculator
27,34
21,34
class Calculator(BaseTool, abc.ABC): name = "Calculator" description = "Useful for when you need to calculate math problems" args_schema: Type[BaseModel] = CalculatorInput def __init__(self): super().__init__() def parameter_validation(self, para: str): FILL_FUNC_BODY def _run(self, cal...
class Calculator(BaseTool, abc.ABC): name = "Calculator" description = "Useful for when you need to calculate math problems" args_schema: Type[BaseModel] = CalculatorInput def __init__(self): super().__init__() def parameter_validation(self, para: str): """ You can write yo...
symbols = ["math", "sqrt", "log", "sin", "cos", "tan", "pi"] for sym in symbols: para = para.replace(sym, "") patten = re.compile("[+*/\-%\d()=\s.]{3,}") if re.findall(patten, para): return True
""" You can write your own parameter validation rules here, you can refer to the code given here. :param para: :return: """ symbols = ["math", "sqrt", "log", "sin", "cos", "tan", "pi"] for sym in symbols: para = para.replace(sym, "") pa...
25
453
96
549
import abc import re from typing import Type from langchain.tools import BaseTool from pydantic import BaseModel, Field class CalculatorInput(BaseModel): calculation: str = Field(description="calculation to perform") class Calculator(BaseTool, abc.ABC): name = "Calculator" description = "Useful for when...
import abc import re from typing import Type from langchain.tools import BaseTool from pydantic import BaseModel, Field class CalculatorInput(BaseModel): calculation: str = Field(description="calculation to perform") class Calculator(BaseTool, abc.ABC): name = "Calculator" description = "Useful for when...
6,650
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3/langchain_demo/tools/DistanceConversion.py
21,22
13,47
_run
DistanceConverter
22,47
22,47
class DistanceConverter(BaseTool, abc.ABC): name = "DistanceConverter" description = "Converts distance between meters, kilometers, and feet" args_schema: Type[BaseModel] = DistanceConversionInput def __init__(self): super().__init__() def _run(self, distance: float, unit: str, to_unit: st...
class DistanceConverter(BaseTool, abc.ABC): name = "DistanceConverter" description = "Converts distance between meters, kilometers, and feet" args_schema: Type[BaseModel] = DistanceConversionInput def __init__(self): super().__init__() def _run(self, distance: float, unit: str, to_unit: st...
unit_conversions = { "m_to_km": 0.001, "km_to_m": 1000, "feet_to_m": 0.3048, "m_to_feet": 3.28084, "km_to_feet": 3280.84, "feet_to_km": 0.0003048 } if unit == to_unit: return f"{distance} {unit} is equal to {dis...
unit_conversions = { "m_to_km": 0.001, "km_to_m": 1000, "feet_to_m": 0.3048, "m_to_feet": 3.28084, "km_to_feet": 3280.84, "feet_to_km": 0.0003048 } if unit == to_unit: return f"{distance} {unit} is equal to {dis...
81
113
334
447
import abc from typing import Type from langchain.tools import BaseTool from pydantic import BaseModel, Field class DistanceConversionInput(BaseModel): distance: float = Field(description="The numerical value of the distance to convert") unit: str = Field(description="The current unit of the distance (m, km, ...
import abc from typing import Type from langchain.tools import BaseTool from pydantic import BaseModel, Field class DistanceConversionInput(BaseModel): distance: float = Field(description="The numerical value of the distance to convert") unit: str = Field(description="The current unit of the distance (m, km, ...
6,651
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3/langchain_demo/tools/Weather.py
20,21
12,34
_run
Weather
21,34
21,34
class Weather(BaseTool): name = "weather" description = "Use for searching weather at a specific location" args_schema: Type[BaseModel] = WeatherInput def __init__(self): super().__init__() def _run(self, location: str) -> dict[str, Any]: FILL_FUNC_BODY
class Weather(BaseTool): name = "weather" description = "Use for searching weather at a specific location" args_schema: Type[BaseModel] = WeatherInput def __init__(self): super().__init__() def _run(self, location: str) -> dict[str, Any]: FILL_FUNC_BODY
api_key = os.environ["SENIVERSE_KEY"] url = f"https://api.seniverse.com/v3/weather/now.json?key={api_key}&location={location}&language=zh-Hans&unit=c" response = requests.get(url) if response.status_code == 200: data = response.json() weather = { "...
api_key = os.environ["SENIVERSE_KEY"] url = f"https://api.seniverse.com/v3/weather/now.json?key={api_key}&location={location}&language=zh-Hans&unit=c" response = requests.get(url) if response.status_code == 200: data = response.json() weather = { "...
34
92
185
277
import os import requests from typing import Type, Any from langchain.tools import BaseTool from pydantic import BaseModel, Field class WeatherInput(BaseModel): location: str = Field(description="the location need to check the weather") class Weather(BaseTool): name = "weather" description = "Use for se...
import os import requests from typing import Type, Any from langchain.tools import BaseTool from pydantic import BaseModel, Field class WeatherInput(BaseModel): location: str = Field(description="the location need to check the weather") class Weather(BaseTool): name = "weather" description = "Use for se...
6,652
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3/openai_api_demo/openai_api_request.py
86,87
1,100
embedding
87,95
87,95
""" This script is an example of using the OpenAI API to create various interactions with a ChatGLM3 model. It includes functions to: 1. Conduct a basic chat session, asking about weather conditions in multiple cities. 2. Initiate a simple chat in Chinese, asking the model to tell a short story. 3. Retrieve and print ...
""" This script is an example of using the OpenAI API to create various interactions with a ChatGLM3 model. It includes functions to: 1. Conduct a basic chat session, asking about weather conditions in multiple cities. 2. Initiate a simple chat in Chinese, asking the model to tell a short story. 3. Retrieve and print ...
response = client.embeddings.create( model="bge-large-zh-1.5", input=["你好,给我讲一个故事,大概100字"], ) embeddings = response.data[0].embedding print("嵌入完成,维度:", len(embeddings))
response = client.embeddings.create( model="bge-large-zh-1.5", input=["你好,给我讲一个故事,大概100字"], ) embeddings = response.data[0].embedding print("嵌入完成,维度:", len(embeddings))
11
799
93
892
""" This script is an example of using the OpenAI API to create various interactions with a ChatGLM3 model. It includes functions to: 1. Conduct a basic chat session, asking about weather conditions in multiple cities. 2. Initiate a simple chat in Chinese, asking the model to tell a short story. 3. Retrieve and print ...
""" This script is an example of using the OpenAI API to create various interactions with a ChatGLM3 model. It includes functions to: 1. Conduct a basic chat session, asking about weather conditions in multiple cities. 2. Initiate a simple chat in Chinese, asking the model to tell a short story. 3. Retrieve and print ...
6,653
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3/openai_api_demo/utils.py
19,20
1,193
process_response
20,46
20,46
import gc import json import torch from transformers import PreTrainedModel, PreTrainedTokenizer from transformers.generation.logits_process import LogitsProcessor from typing import Union, Tuple class InvalidScoreLogitsProcessor(LogitsProcessor): def __call__( self, input_ids: torch.LongTensor, score...
import gc import json import torch from transformers import PreTrainedModel, PreTrainedTokenizer from transformers.generation.logits_process import LogitsProcessor from typing import Union, Tuple class InvalidScoreLogitsProcessor(LogitsProcessor): def __call__( self, input_ids: torch.LongTensor, score...
content = "" for response in output.split("<|assistant|>"): metadata, content = response.split("\n", maxsplit=1) if not metadata.strip(): content = content.strip() content = content.replace("[[训练时间]]", "2023年") else: if use_tool: conten...
content = "" for response in output.split("<|assistant|>"): metadata, content = response.split("\n", maxsplit=1) if not metadata.strip(): content = content.strip() content = content.replace("[[训练时间]]", "2023年") else: if use_tool: conten...
55
1,617
229
1,846
import gc import json import torch from transformers import PreTrainedModel, PreTrainedTokenizer from transformers.generation.logits_process import LogitsProcessor from typing import Union, Tuple class InvalidScoreLogitsProcessor(LogitsProcessor): def __call__( self, input_ids: torch.LongTensor, score...
import gc import json import torch from transformers import PreTrainedModel, PreTrainedTokenizer from transformers.generation.logits_process import LogitsProcessor from typing import Union, Tuple class InvalidScoreLogitsProcessor(LogitsProcessor): def __call__( self, input_ids: torch.LongTensor, score...
6,654
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3/openai_api_demo/zhipu_api_request.py
57,58
1,101
simple_chat
58,87
58,87
""" This script is an example of using the Zhipu API to create various interactions with a ChatGLM3 model. It includes functions to: 1. Conduct a basic chat session, asking about weather conditions in multiple cities. 2. Initiate a simple chat in Chinese, asking the model to tell a short story. 3. Retrieve and print e...
""" This script is an example of using the Zhipu API to create various interactions with a ChatGLM3 model. It includes functions to: 1. Conduct a basic chat session, asking about weather conditions in multiple cities. 2. Initiate a simple chat in Chinese, asking the model to tell a short story. 3. Retrieve and print e...
messages = [ { "role": "system", "content": "You are ChatGLM3, a large language model trained by Zhipu.AI. Follow " "the user's instructions carefully. Respond using markdown.", }, { "role": "user", "content": "你好,请你介绍一下c...
messages = [ { "role": "system", "content": "You are ChatGLM3, a large language model trained by Zhipu.AI. Follow " "the user's instructions carefully. Respond using markdown.", }, { "role": "user", "content": "你好,请你介绍一下c...
60
670
278
948
""" This script is an example of using the Zhipu API to create various interactions with a ChatGLM3 model. It includes functions to: 1. Conduct a basic chat session, asking about weather conditions in multiple cities. 2. Initiate a simple chat in Chinese, asking the model to tell a short story. 3. Retrieve and print e...
""" This script is an example of using the Zhipu API to create various interactions with a ChatGLM3 model. It includes functions to: 1. Conduct a basic chat session, asking about weather conditions in multiple cities. 2. Initiate a simple chat in Chinese, asking the model to tell a short story. 3. Retrieve and print e...
6,655
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3/tools_using_demo/cli_demo_tool.py
103,104
1,130
main
104,128
104,128
""" This demo script is designed for interacting with the ChatGLM3-6B in Function, to show Function Call capabilities. """ import os import platform import torch from transformers import AutoTokenizer, AutoModel MODEL_PATH = os.environ.get('MODEL_PATH', 'THUDM/chatglm3-6b') TOKENIZER_PATH = os.environ.get("TOKENIZER_...
""" This demo script is designed for interacting with the ChatGLM3-6B in Function, to show Function Call capabilities. """ import os import platform import torch from transformers import AutoTokenizer, AutoModel MODEL_PATH = os.environ.get('MODEL_PATH', 'THUDM/chatglm3-6b') TOKENIZER_PATH = os.environ.get("TOKENIZER_...
past_key_values, history = None, [system_item] role = "user" global stop_stream print("欢迎使用 ChatGLM3-6B 模型,输入内容即可进行对话,clear 清空对话历史,stop 终止程序") while True: query = input("\n用户:") if role == "user" else input("\n结果:") if query.strip() == "stop": break if query.strip...
past_key_values, history = None, [system_item] role = "user" global stop_stream print("欢迎使用 ChatGLM3-6B 模型,输入内容即可进行对话,clear 清空对话历史,stop 终止程序") while True: query = input("\n用户:") if role == "user" else input("\n结果:") if query.strip() == "stop": break if query.strip...
73
860
310
1,170
""" This demo script is designed for interacting with the ChatGLM3-6B in Function, to show Function Call capabilities. """ import os import platform import torch from transformers import AutoTokenizer, AutoModel MODEL_PATH = os.environ.get('MODEL_PATH', 'THUDM/chatglm3-6b') TOKENIZER_PATH = os.environ.get("TOKENIZER_...
""" This demo script is designed for interacting with the ChatGLM3-6B in Function, to show Function Call capabilities. """ import os import platform import torch from transformers import AutoTokenizer, AutoModel MODEL_PATH = os.environ.get('MODEL_PATH', 'THUDM/chatglm3-6b') TOKENIZER_PATH = os.environ.get("TOKENIZER_...
6,656
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3
/home/hieuvd/dung_repo/raw/stars_01/THUDM_ChatGLM3/ChatGLM3/tools_using_demo/tool_register.py
89,93
1,119
get_weather
96,116
93,116
""" 这段代码是工具注册的部分,通过注册工具,让模型实现工具调用 """ import inspect import traceback from copy import deepcopy from pprint import pformat from types import GenericAlias from typing import get_origin, Annotated _TOOL_HOOKS = {} _TOOL_DESCRIPTIONS = {} def register_tool(func: callable): tool_name = func.__name__ tool_descrip...
""" 这段代码是工具注册的部分,通过注册工具,让模型实现工具调用 """ import inspect import traceback from copy import deepcopy from pprint import pformat from types import GenericAlias from typing import get_origin, Annotated _TOOL_HOOKS = {} _TOOL_DESCRIPTIONS = {} def register_tool(func: callable): tool_name = func.__name__ tool_descrip...
if not isinstance(city_name, str): raise TypeError("City name must be a string") key_selection = { "current_condition": ["temp_C", "FeelsLikeC", "humidity", "weatherDesc", "observation_time"], } import requests try: resp = requests.get(f"https://wttr.in/{city_name}?format=j...
""" Get the current weather for `city_name` """ if not isinstance(city_name, str): raise TypeError("City name must be a string") key_selection = { "current_condition": ["temp_C", "FeelsLikeC", "humidity", "weatherDesc", "observation_time"], } import requests try: ...
60
940
223
1,163
""" 这段代码是工具注册的部分,通过注册工具,让模型实现工具调用 """ import inspect import traceback from copy import deepcopy from pprint import pformat from types import GenericAlias from typing import get_origin, Annotated _TOOL_HOOKS = {} _TOOL_DESCRIPTIONS = {} def register_tool(func: callable): tool_name = func.__name__ tool_descrip...
""" 这段代码是工具注册的部分,通过注册工具,让模型实现工具调用 """ import inspect import traceback from copy import deepcopy from pprint import pformat from types import GenericAlias from typing import get_origin, Annotated _TOOL_HOOKS = {} _TOOL_DESCRIPTIONS = {} def register_tool(func: callable): tool_name = func.__name__ tool_descrip...
6,734
/home/hieuvd/dung_repo/raw/stars_01/THUDM_CodeGeeX2/CodeGeeX2
/home/hieuvd/dung_repo/raw/stars_01/THUDM_CodeGeeX2/CodeGeeX2/demo/gpus.py
8,9
1,60
auto_configure_device_map
9,45
9,45
import os from typing import Dict, Tuple, Union, Optional from torch.nn import Module from transformers import AutoModel def auto_configure_device_map(num_gpus: int) -> Dict[str, int]: FILL_FUNC_BODYdef load_model_on_gpus(checkpoint_path: Union[str, os.PathLike], num_gpus: int = 2, device_map:...
import os from typing import Dict, Tuple, Union, Optional from torch.nn import Module from transformers import AutoModel def auto_configure_device_map(num_gpus: int) -> Dict[str, int]: FILL_FUNC_BODYdef load_model_on_gpus(checkpoint_path: Union[str, os.PathLike], num_gpus: int = 2, device_map:...
# transformer.word_embeddings 占用1层 # transformer.final_layernorm 和 lm_head 占用1层 # transformer.layers 占用 28 层 # 总共30层分配到num_gpus张卡上 num_trans_layers = 28 per_gpu_layers = 30 / num_gpus # bugfix: 在linux中调用torch.embedding传入的weight,input不在同一device上,导致RuntimeError # windows下 model.device 会被设...
# transformer.word_embeddings 占用1层 # transformer.final_layernorm 和 lm_head 占用1层 # transformer.layers 占用 28 层 # 总共30层分配到num_gpus张卡上 num_trans_layers = 28 per_gpu_layers = 30 / num_gpus # bugfix: 在linux中调用torch.embedding传入的weight,input不在同一device上,导致RuntimeError # windows下 model.device 会被设...
92
275
526
801
import os from typing import Dict, Tuple, Union, Optional from torch.nn import Module from transformers import AutoModel def auto_configure_device_map(num_gpus: int) -> Dict[str, int]: FILL_FUNC_BODYdef load_model_on_gpus(checkpoint_path: Union[str, os.PathLike], num_gpus: int = 2, device_map:...
import os from typing import Dict, Tuple, Union, Optional from torch.nn import Module from transformers import AutoModel def auto_configure_device_map(num_gpus: int) -> Dict[str, int]: FILL_FUNC_BODYdef load_model_on_gpus(checkpoint_path: Union[str, os.PathLike], num_gpus: int = 2, device_map:...
8,044
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/cli2.py
27,28
1,75
run_server
28,39
28,39
import os import sys import subprocess from time import sleep import shutil from sys import platform from multiprocessing import Process from superagi.lib.logger import logger def check_command(command, message): if not shutil.which(command): logger.info(message) sys.exit(1) def run_npm_commands...
import os import sys import subprocess from time import sleep import shutil from sys import platform from multiprocessing import Process from superagi.lib.logger import logger def check_command(command, message): if not shutil.which(command): logger.info(message) sys.exit(1) def run_npm_commands...
tgwui_process = Process(target=subprocess.run, args=(["python", "test.py","--name",a_name,"--description",a_description,"--goals"]+goals,), kwargs={"shell": shell}) api_process = Process(target=subprocess.run, args=(["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"],), kwargs={"shell": shell}) c...
tgwui_process = Process(target=subprocess.run, args=(["python", "test.py","--name",a_name,"--description",a_description,"--goals"]+goals,), kwargs={"shell": shell}) api_process = Process(target=subprocess.run, args=(["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"],), kwargs={"shell": shell}) c...
42
615
286
901
import os import sys import subprocess from time import sleep import shutil from sys import platform from multiprocessing import Process from superagi.lib.logger import logger def check_command(command, message): if not shutil.which(command): logger.info(message) sys.exit(1) def run_npm_commands...
import os import sys import subprocess from time import sleep import shutil from sys import platform from multiprocessing import Process from superagi.lib.logger import logger def check_command(command, message): if not shutil.which(command): logger.info(message) sys.exit(1) def run_npm_commands...
8,045
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/run_gui.py
13,14
1,52
run_npm_commands
14,22
14,22
import os import sys import subprocess from time import sleep import shutil from superagi.lib.logger import logger def check_command(command, message): if not shutil.which(command): logger.info(message) sys.exit(1) def run_npm_commands(): FILL_FUNC_BODYdef run_server(): api_process = subproces...
import os import sys import subprocess from time import sleep import shutil from superagi.lib.logger import logger def check_command(command, message): if not shutil.which(command): logger.info(message) sys.exit(1) def run_npm_commands(): FILL_FUNC_BODYdef run_server(): api_process = subproces...
os.chdir("gui") try: subprocess.run(["npm", "install"], check=True) except subprocess.CalledProcessError: logger.error(f"Error during '{' '.join(sys.exc_info()[1].cmd)}'. Exiting.") sys.exit(1) os.chdir("..")
os.chdir("gui") try: subprocess.run(["npm", "install"], check=True) except subprocess.CalledProcessError: logger.error(f"Error during '{' '.join(sys.exc_info()[1].cmd)}'. Exiting.") sys.exit(1) os.chdir("..")
14
423
97
520
import os import sys import subprocess from time import sleep import shutil from superagi.lib.logger import logger def check_command(command, message): if not shutil.which(command): logger.info(message) sys.exit(1) def run_npm_commands(): FILL_FUNC_BODYdef run_server(): api_process = subproces...
import os import sys import subprocess from time import sleep import shutil from superagi.lib.logger import logger def check_command(command, message): if not shutil.which(command): logger.info(message) sys.exit(1) def run_npm_commands(): FILL_FUNC_BODYdef run_server(): api_process = subproces...
8,046
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/agent/agent_workflow_step_wait_handler.py
32,33
10,46
handle_next_step
AgentWaitStepHandler
34,46
33,46
class AgentWaitStepHandler: """Handle Agent Wait Step in the agent workflow.""" def __init__(self, session, agent_id, agent_execution_id): self.session = session self.agent_id = agent_id self.agent_execution_id = agent_execution_id def execute_step(self): """Execute the age...
class AgentWaitStepHandler: """Handle Agent Wait Step in the agent workflow.""" def __init__(self, session, agent_id, agent_execution_id): self.session = session self.agent_id = agent_id self.agent_execution_id = agent_execution_id def execute_step(self): """Execute the age...
execution = AgentExecution.get_agent_execution_from_id(self.session, self.agent_execution_id) workflow_step = AgentWorkflowStep.find_by_id(self.session, execution.current_agent_step_id) step_response = "default" next_step = AgentWorkflowStep.fetch_next_step(self.session, workflow_step.i...
"""Handle next step of agent workflow in case of wait step.""" execution = AgentExecution.get_agent_execution_from_id(self.session, self.agent_execution_id) workflow_step = AgentWorkflowStep.find_by_id(self.session, execution.current_agent_step_id) step_response = "default" next...
35
305
230
535
from datetime import datetime from superagi.agent.types.agent_execution_status import AgentExecutionStatus from superagi.lib.logger import logger from superagi.models.agent_execution import AgentExecution from superagi.models.workflows.agent_workflow_step import AgentWorkflowStep from superagi.models.workflows.agent_w...
from datetime import datetime from superagi.agent.types.agent_execution_status import AgentExecutionStatus from superagi.lib.logger import logger from superagi.models.agent_execution import AgentExecution from superagi.models.workflows.agent_workflow_step import AgentWorkflowStep from superagi.models.workflows.agent_w...
8,047
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/agent/output_parser.py
29,30
27,50
parse
AgentSchemaOutputParser
30,50
30,50
class AgentSchemaOutputParser(BaseOutputParser): """Parses the output from the agent schema""" def parse(self, response: str) -> AgentGPTAction: FILL_FUNC_BODY
class AgentSchemaOutputParser(BaseOutputParser): """Parses the output from the agent schema""" def parse(self, response: str) -> AgentGPTAction: FILL_FUNC_BODY
if response.startswith("```") and response.endswith("```"): response = "```".join(response.split("```")[1:-1]) response = JsonCleaner.extract_json_section(response) # ast throws error if true/false params passed in json response = JsonCleaner.clean_boolean(response) ...
if response.startswith("```") and response.endswith("```"): response = "```".join(response.split("```")[1:-1]) response = JsonCleaner.extract_json_section(response) # ast throws error if true/false params passed in json response = JsonCleaner.clean_boolean(response) ...
63
52
251
303
import json from abc import ABC, abstractmethod from typing import Dict, NamedTuple, List import re import ast import json from superagi.helper.json_cleaner import JsonCleaner from superagi.lib.logger import logger class AgentGPTAction(NamedTuple): name: str args: Dict class AgentTasks(NamedTuple): task...
import json from abc import ABC, abstractmethod from typing import Dict, NamedTuple, List import re import ast import json from superagi.helper.json_cleaner import JsonCleaner from superagi.lib.logger import logger class AgentGPTAction(NamedTuple): name: str args: Dict class AgentTasks(NamedTuple): task...
8,048
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/agent/output_parser.py
52,53
50,71
parse
AgentSchemaToolOutputParser
53,71
53,71
class AgentSchemaToolOutputParser(BaseOutputParser): """Parses the output from the agent schema for the tool""" def parse(self, response: str) -> AgentGPTAction: FILL_FUNC_BODY
class AgentSchemaToolOutputParser(BaseOutputParser): """Parses the output from the agent schema for the tool""" def parse(self, response: str) -> AgentGPTAction: FILL_FUNC_BODY
if response.startswith("```") and response.endswith("```"): response = "```".join(response.split("```")[1:-1]) response = JsonCleaner.extract_json_section(response) # ast throws error if true/false params passed in json response = JsonCleaner.clean_boolean(response) ...
if response.startswith("```") and response.endswith("```"): response = "```".join(response.split("```")[1:-1]) response = JsonCleaner.extract_json_section(response) # ast throws error if true/false params passed in json response = JsonCleaner.clean_boolean(response) ...
63
56
241
297
import json from abc import ABC, abstractmethod from typing import Dict, NamedTuple, List import re import ast import json from superagi.helper.json_cleaner import JsonCleaner from superagi.lib.logger import logger class AgentGPTAction(NamedTuple): name: str args: Dict class AgentTasks(NamedTuple): task...
import json from abc import ABC, abstractmethod from typing import Dict, NamedTuple, List import re import ast import json from superagi.helper.json_cleaner import JsonCleaner from superagi.lib.logger import logger class AgentGPTAction(NamedTuple): name: str args: Dict class AgentTasks(NamedTuple): task...
8,049
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/agent/tool_builder.py
21,22
13,30
get_tool_config
DBToolkitConfiguration
22,30
22,30
class DBToolkitConfiguration(BaseToolkitConfiguration): session = None toolkit_id: int def __init__(self, session=None, toolkit_id=None): self.session = session self.toolkit_id = toolkit_id def get_tool_config(self, key: str): FILL_FUNC_BODY
class DBToolkitConfiguration(BaseToolkitConfiguration): session = None toolkit_id: int def __init__(self, session=None, toolkit_id=None): self.session = session self.toolkit_id = toolkit_id def get_tool_config(self, key: str): FILL_FUNC_BODY
tool_config = self.session.query(ToolConfig).filter_by(key=key, toolkit_id=self.toolkit_id).first() if tool_config and tool_config.value: if is_encrypted(tool_config.value): return decrypt_data(tool_config.value) else: return tool_config.value ...
tool_config = self.session.query(ToolConfig).filter_by(key=key, toolkit_id=self.toolkit_id).first() if tool_config and tool_config.value: if is_encrypted(tool_config.value): return decrypt_data(tool_config.value) else: return tool_config.value ...
17
91
114
205
import importlib import os from superagi.config.config import get_config from superagi.llms.llm_model_factory import get_model from superagi.models.tool import Tool from superagi.models.tool_config import ToolConfig from superagi.models.agent import Agent from superagi.resource_manager.file_manager import FileManager f...
import importlib import os from superagi.config.config import get_config from superagi.llms.llm_model_factory import get_model from superagi.models.tool import Tool from superagi.models.tool_config import ToolConfig from superagi.models.agent import Agent from superagi.resource_manager.file_manager import FileManager f...
8,050
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/agent/tool_builder.py
50,51
30,124
build_tool
ToolBuilder
60,84
51,84
class ToolBuilder: def __init__(self, session, agent_id: int, agent_execution_id: int = None): self.session = session self.agent_id = agent_id self.agent_execution_id = agent_execution_id def __validate_filename(self, filename): """ Validate the filename by removing the ...
class ToolBuilder: def __init__(self, session, agent_id: int, agent_execution_id: int = None): self.session = session self.agent_id = agent_id self.agent_execution_id = agent_execution_id def __validate_filename(self, filename): """ Validate the filename by removing the ...
file_name = self.__validate_filename(filename=tool.file_name) tools_dir="" tool_paths = ["superagi/tools", "superagi/tools/external_tools", "superagi/tools/marketplace_tools"] for tool_path in tool_paths: if os.path.exists(os.path.join(os.getcwd(), tool_path) + '/' + tool.fo...
""" Create an object of a agent usable tool dynamically. Args: tool (Tool) : Tool object from which agent tool would be made. Returns: object: The object of the agent usable tool. """ file_name = self.__validate_filename(filename=tool.file_name) ...
73
875
330
1,205
import importlib import os from superagi.config.config import get_config from superagi.llms.llm_model_factory import get_model from superagi.models.tool import Tool from superagi.models.tool_config import ToolConfig from superagi.models.agent import Agent from superagi.resource_manager.file_manager import FileManager f...
import importlib import os from superagi.config.config import get_config from superagi.llms.llm_model_factory import get_model from superagi.models.tool import Tool from superagi.models.tool_config import ToolConfig from superagi.models.agent import Agent from superagi.resource_manager.file_manager import FileManager f...
8,051
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/agent/types/agent_execution_status.py
11,13
4,19
get_agent_execution_status
AgentExecutionStatus
13,19
13,19
class AgentExecutionStatus(Enum): RUNNING = 'RUNNING' WAITING_FOR_PERMISSION = 'WAITING_FOR_PERMISSION' ITERATION_LIMIT_EXCEEDED = 'ITERATION_LIMIT_EXCEEDED' WAIT_STEP = 'WAIT_STEP' COMPLETED = 'COMPLETED' @classmethod def get_agent_execution_status(cls, store): FILL_FUNC_BODY
class AgentExecutionStatus(Enum): RUNNING = 'RUNNING' WAITING_FOR_PERMISSION = 'WAITING_FOR_PERMISSION' ITERATION_LIMIT_EXCEEDED = 'ITERATION_LIMIT_EXCEEDED' WAIT_STEP = 'WAIT_STEP' COMPLETED = 'COMPLETED' @classmethod def get_agent_execution_status(cls, store): FILL_FUNC_BODY
if store is None: raise ValueError("Storage type cannot be None.") store = store.upper() if store in cls.__members__: return cls[store] raise ValueError(f"{store} is not a valid storage name.")
if store is None: raise ValueError("Storage type cannot be None.") store = store.upper() if store in cls.__members__: return cls[store] raise ValueError(f"{store} is not a valid storage name.")
27
128
70
198
from enum import Enum class AgentExecutionStatus(Enum): RUNNING = 'RUNNING' WAITING_FOR_PERMISSION = 'WAITING_FOR_PERMISSION' ITERATION_LIMIT_EXCEEDED = 'ITERATION_LIMIT_EXCEEDED' WAIT_STEP = 'WAIT_STEP' COMPLETED = 'COMPLETED' @classmethod def get_agent_execution_status(cls, store): FILL...
from enum import Enum class AgentExecutionStatus(Enum): RUNNING = 'RUNNING' WAITING_FOR_PERMISSION = 'WAITING_FOR_PERMISSION' ITERATION_LIMIT_EXCEEDED = 'ITERATION_LIMIT_EXCEEDED' WAIT_STEP = 'WAIT_STEP' COMPLETED = 'COMPLETED' @classmethod def get_agent_execution_status(cls, store): FILL...
8,052
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/agent/types/agent_workflow_step_action_types.py
10,12
4,18
get_agent_workflow_action_type
AgentWorkflowStepAction
12,18
12,18
class AgentWorkflowStepAction(Enum): ITERATION_WORKFLOW = 'ITERATION_WORKFLOW' TOOL = 'TOOL' WAIT_STEP = 'WAIT_STEP' @classmethod def get_agent_workflow_action_type(cls, store): FILL_FUNC_BODY
class AgentWorkflowStepAction(Enum): ITERATION_WORKFLOW = 'ITERATION_WORKFLOW' TOOL = 'TOOL' WAIT_STEP = 'WAIT_STEP' @classmethod def get_agent_workflow_action_type(cls, store): FILL_FUNC_BODY
if store is None: raise ValueError("Storage type cannot be None.") store = store.upper() if store in cls.__members__: return cls[store] raise ValueError(f"{store} is not a valid storage name.")
if store is None: raise ValueError("Storage type cannot be None.") store = store.upper() if store in cls.__members__: return cls[store] raise ValueError(f"{store} is not a valid storage name.")
27
90
70
160
from enum import Enum class AgentWorkflowStepAction(Enum): ITERATION_WORKFLOW = 'ITERATION_WORKFLOW' TOOL = 'TOOL' WAIT_STEP = 'WAIT_STEP' @classmethod def get_agent_workflow_action_type(cls, store): FILL_FUNC_BODY
from enum import Enum class AgentWorkflowStepAction(Enum): ITERATION_WORKFLOW = 'ITERATION_WORKFLOW' TOOL = 'TOOL' WAIT_STEP = 'WAIT_STEP' @classmethod def get_agent_workflow_action_type(cls, store): FILL_FUNC_BODY
8,053
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/agent/types/wait_step_status.py
9,11
4,17
get_agent_workflow_step_wait_status
AgentWorkflowStepWaitStatus
11,17
11,17
class AgentWorkflowStepWaitStatus(Enum): PENDING = 'PENDING' WAITING = 'WAITING' COMPLETED = 'COMPLETED' @classmethod def get_agent_workflow_step_wait_status(cls, store): FILL_FUNC_BODY
class AgentWorkflowStepWaitStatus(Enum): PENDING = 'PENDING' WAITING = 'WAITING' COMPLETED = 'COMPLETED' @classmethod def get_agent_workflow_step_wait_status(cls, store): FILL_FUNC_BODY
if store is None: raise ValueError("Storage type cannot be None.") store = store.upper() if store in cls.__members__: return cls[store] raise ValueError(f"{store} is not a valid storage name.")
if store is None: raise ValueError("Storage type cannot be None.") store = store.upper() if store in cls.__members__: return cls[store] raise ValueError(f"{store} is not a valid storage name.")
27
81
70
151
from enum import Enum class AgentWorkflowStepWaitStatus(Enum): PENDING = 'PENDING' WAITING = 'WAITING' COMPLETED = 'COMPLETED' @classmethod def get_agent_workflow_step_wait_status(cls, store): FILL_FUNC_BODY
from enum import Enum class AgentWorkflowStepWaitStatus(Enum): PENDING = 'PENDING' WAITING = 'WAITING' COMPLETED = 'COMPLETED' @classmethod def get_agent_workflow_step_wait_status(cls, store): FILL_FUNC_BODY
8,055
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/agent/workflow_seed.py
229,231
218,270
build_task_based_agents
IterationWorkflowSeed
231,254
231,254
class IterationWorkflowSeed: @classmethod def build_single_step_agent(cls, session): iteration_workflow = IterationWorkflow.find_or_create_by_name(session, "Goal Based Agent-I", "Goal Based Agent") output = AgentPromptTemplate.get_super_agi_single_prompt() IterationWorkflowStep.find_or_c...
class IterationWorkflowSeed: @classmethod def build_single_step_agent(cls, session): iteration_workflow = IterationWorkflow.find_or_create_by_name(session, "Goal Based Agent-I", "Goal Based Agent") output = AgentPromptTemplate.get_super_agi_single_prompt() IterationWorkflowStep.find_or_c...
iteration_workflow = IterationWorkflow.find_or_create_by_name(session, "Dynamic Task Queue-I", "Dynamic Task Queue", has_task_queue=True) output = AgentPromptTemplate.analyse_task() workflow_step1 = IterationWorkflowStep.find...
iteration_workflow = IterationWorkflow.find_or_create_by_name(session, "Dynamic Task Queue-I", "Dynamic Task Queue", has_task_queue=True) output = AgentPromptTemplate.analyse_task() workflow_step1 = IterationWorkflowStep.find...
53
492
353
845
from superagi.agent.agent_prompt_builder import AgentPromptBuilder from superagi.agent.agent_prompt_template import AgentPromptTemplate from superagi.models.workflows.agent_workflow import AgentWorkflow from superagi.models.workflows.agent_workflow_step import AgentWorkflowStep from superagi.models.workflows.iteration_...
from superagi.agent.agent_prompt_builder import AgentPromptBuilder from superagi.agent.agent_prompt_template import AgentPromptTemplate from superagi.models.workflows.agent_workflow import AgentWorkflow from superagi.models.workflows.agent_workflow_step import AgentWorkflowStep from superagi.models.workflows.iteration_...
8,056
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/controllers/types/models_types.py
7,9
3,15
get_models_types
ModelsTypes
9,15
9,15
class ModelsTypes(Enum): MARKETPLACE = "Marketplace" CUSTOM = "Custom" @classmethod def get_models_types(cls, model_type): FILL_FUNC_BODY
class ModelsTypes(Enum): MARKETPLACE = "Marketplace" CUSTOM = "Custom" @classmethod def get_models_types(cls, model_type): FILL_FUNC_BODY
if model_type is None: raise ValueError("Queue status type cannot be None.") model_type = model_type.upper() if model_type in cls.__members__: return cls[model_type] raise ValueError(f"{model_type} is not a valid storage name.")
if model_type is None: raise ValueError("Queue status type cannot be None.") model_type = model_type.upper() if model_type in cls.__members__: return cls[model_type] raise ValueError(f"{model_type} is not a valid storage name.")
28
61
82
143
from enum import Enum class ModelsTypes(Enum): MARKETPLACE = "Marketplace" CUSTOM = "Custom" @classmethod def get_models_types(cls, model_type): FILL_FUNC_BODY
from enum import Enum class ModelsTypes(Enum): MARKETPLACE = "Marketplace" CUSTOM = "Custom" @classmethod def get_models_types(cls, model_type): FILL_FUNC_BODY
8,057
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/helper/feed_parser.py
8,9
1,59
parse_feed
19,59
9,59
import json from datetime import datetime from superagi.helper.time_helper import get_time_difference from superagi.lib.logger import logger def parse_feed(feed): FILL_FUNC_BODY
import json from datetime import datetime from superagi.helper.time_helper import get_time_difference from superagi.lib.logger import logger def parse_feed(feed): """ Helper function to parse the feed. Args: feed (AgentExecutionFeed): The feed to be parsed. Returns: dict: Parsed fee...
# Get the current time feed.time_difference = get_time_difference(feed.updated_at, str(datetime.now())) # Check if the feed belongs to an assistant role if feed.role == "assistant": try: # Parse the feed as JSON parsed = json.loads(feed.feed, strict=False) ...
""" Helper function to parse the feed. Args: feed (AgentExecutionFeed): The feed to be parsed. Returns: dict: Parsed feed information with role, feed content, and updated timestamp. If parsing fails, the original feed is returned. """ # Get the current time f...
155
129
571
700
import json from datetime import datetime from superagi.helper.time_helper import get_time_difference from superagi.lib.logger import logger def parse_feed(feed): FILL_FUNC_BODY
import json from datetime import datetime from superagi.helper.time_helper import get_time_difference from superagi.lib.logger import logger def parse_feed(feed): """ Helper function to parse the feed. Args: feed (AgentExecutionFeed): The feed to be parsed. Returns: dict: Parsed fee...
8,058
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/helper/imap_email.py
23,24
4,40
adjust_imap_folder
ImapEmail
34,40
24,40
class ImapEmail: def imap_open(self, imap_folder, email_sender, email_password, imap_server) -> imaplib.IMAP4_SSL: """ Function to open an IMAP connection to the email server. Args: imap_folder (str): The folder to open. email_sender (str): The email address of the ...
class ImapEmail: def imap_open(self, imap_folder, email_sender, email_password, imap_server) -> imaplib.IMAP4_SSL: """ Function to open an IMAP connection to the email server. Args: imap_folder (str): The folder to open. email_sender (str): The email address of the ...
if "@gmail" in email_sender.lower(): if "sent" in imap_folder.lower(): return '"[Gmail]/Sent Mail"' if "draft" in imap_folder.lower(): return '"[Gmail]/Drafts"' return imap_folder
""" Function to adjust the IMAP folder based on the email address of the sender. Args: imap_folder (str): The folder to open. email_sender (str): The email address of the sender. Returns: str: The adjusted IMAP folder. """ if "@gmail"...
19
301
82
383
import imaplib class ImapEmail: def imap_open(self, imap_folder, email_sender, email_password, imap_server) -> imaplib.IMAP4_SSL: """ Function to open an IMAP connection to the email server. Args: imap_folder (str): The folder to open. email_sender (str): The emai...
import imaplib class ImapEmail: def imap_open(self, imap_folder, email_sender, email_password, imap_server) -> imaplib.IMAP4_SSL: """ Function to open an IMAP connection to the email server. Args: imap_folder (str): The folder to open. email_sender (str): The emai...
8,059
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/helper/models_helper.py
4,6
3,20
validate_end_point
ModelsHelper
6,20
6,20
class ModelsHelper: @staticmethod def validate_end_point(model_api_key, end_point, model_provider): FILL_FUNC_BODY
class ModelsHelper: @staticmethod def validate_end_point(model_api_key, end_point, model_provider): FILL_FUNC_BODY
response = {"success": True} if (model_provider == 'Hugging Face'): try: result = HuggingFace(api_key=model_api_key, end_point=end_point).verify_end_point() except Exception as e: response['success'] = False response['error'] = str...
response = {"success": True} if (model_provider == 'Hugging Face'): try: result = HuggingFace(api_key=model_api_key, end_point=end_point).verify_end_point() except Exception as e: response['success'] = False response['error'] = str...
30
44
121
165
from superagi.llms.hugging_face import HuggingFace class ModelsHelper: @staticmethod def validate_end_point(model_api_key, end_point, model_provider): FILL_FUNC_BODY
from superagi.llms.hugging_face import HuggingFace class ModelsHelper: @staticmethod def validate_end_point(model_api_key, end_point, model_provider): FILL_FUNC_BODY
8,060
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/helper/prompt_reader.py
5,7
4,28
read_tools_prompt
PromptReader
7,17
7,17
class PromptReader: @staticmethod def read_tools_prompt(current_file: str, prompt_file: str) -> str: FILL_FUNC_BODY @staticmethod def read_agent_prompt(current_file: str, prompt_file: str) -> str: file_path = str(Path(current_file).resolve().parent) + "/prompts/" + prompt_file try: ...
class PromptReader: @staticmethod def read_tools_prompt(current_file: str, prompt_file: str) -> str: FILL_FUNC_BODY @staticmethod def read_agent_prompt(current_file: str, prompt_file: str) -> str: file_path = str(Path(current_file).resolve().parent) + "/prompts/" + prompt_file try: ...
file_path = str(Path(current_file).resolve().parent) + "/prompts/" + prompt_file try: f = open(file_path, "r") file_content = f.read() f.close() except FileNotFoundError as e: print(e.__str__()) raise e return file_content
file_path = str(Path(current_file).resolve().parent) + "/prompts/" + prompt_file try: f = open(file_path, "r") file_content = f.read() f.close() except FileNotFoundError as e: print(e.__str__()) raise e return file_content
25
167
100
267
from pathlib import Path class PromptReader: @staticmethod def read_tools_prompt(current_file: str, prompt_file: str) -> str: FILL_FUNC_BODY @staticmethod def read_agent_prompt(current_file: str, prompt_file: str) -> str: file_path = str(Path(current_file).resolve().parent) + "/prompts/" + prom...
from pathlib import Path class PromptReader: @staticmethod def read_tools_prompt(current_file: str, prompt_file: str) -> str: FILL_FUNC_BODY @staticmethod def read_agent_prompt(current_file: str, prompt_file: str) -> str: file_path = str(Path(current_file).resolve().parent) + "/prompts/" + prom...
8,061
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/helper/resource_helper.py
101,103
12,183
get_root_output_dir
ResourceHelper
105,114
103,114
class ResourceHelper: @classmethod def make_written_file_resource(cls, file_name: str, agent: Agent, agent_execution: AgentExecution, session): """ Function to create a Resource object for a written file. Args: file_name (str): The name of the file. agent (Agent)...
class ResourceHelper: @classmethod def make_written_file_resource(cls, file_name: str, agent: Agent, agent_execution: AgentExecution, session): """ Function to create a Resource object for a written file. Args: file_name (str): The name of the file. agent (Agent)...
root_dir = get_config('RESOURCES_OUTPUT_ROOT_DIR') if root_dir is not None: root_dir = root_dir if root_dir.startswith("/") else os.getcwd() + "/" + root_dir root_dir = root_dir if root_dir.endswith("/") else root_dir + "/" else: root_dir = os.getcwd() + "/" ...
"""Get root dir of the resource. """ root_dir = get_config('RESOURCES_OUTPUT_ROOT_DIR') if root_dir is not None: root_dir = root_dir if root_dir.startswith("/") else os.getcwd() + "/" + root_dir root_dir = root_dir if root_dir.endswith("/") else root_dir + "/" ...
36
1,907
128
2,035
import os from superagi.config.config import get_config from superagi.helper.s3_helper import S3Helper from superagi.lib.logger import logger from superagi.models.agent import Agent from superagi.models.agent_execution import AgentExecution from superagi.models.resource import Resource from superagi.types.storage_type...
import os from superagi.config.config import get_config from superagi.helper.s3_helper import S3Helper from superagi.lib.logger import logger from superagi.models.agent import Agent from superagi.models.agent_execution import AgentExecution from superagi.models.resource import Resource from superagi.types.storage_type...
8,062
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/helper/time_helper.py
4,5
1,44
get_time_difference
5,36
5,36
from datetime import datetime def get_time_difference(timestamp1, timestamp2): FILL_FUNC_BODYdef parse_interval_to_seconds(interval: str) -> int: units = {"Minutes": 60, "Hours": 3600, "Days": 86400, "Weeks": 604800, "Months": 2592000} interval = ' '.join(interval.split()) value, unit = interval.split(" "...
from datetime import datetime def get_time_difference(timestamp1, timestamp2): FILL_FUNC_BODYdef parse_interval_to_seconds(interval: str) -> int: units = {"Minutes": 60, "Hours": 3600, "Days": 86400, "Weeks": 604800, "Months": 2592000} interval = ' '.join(interval.split()) value, unit = interval.split(" "...
time_format = "%Y-%m-%d %H:%M:%S.%f" # Parse the given timestamp parsed_timestamp1 = datetime.strptime(str(timestamp1), time_format) parsed_timestamp2 = datetime.strptime(timestamp2, time_format) # Calculate the time difference time_difference = parsed_timestamp2 - parsed_timestamp1 # Con...
time_format = "%Y-%m-%d %H:%M:%S.%f" # Parse the given timestamp parsed_timestamp1 = datetime.strptime(str(timestamp1), time_format) parsed_timestamp2 = datetime.strptime(timestamp2, time_format) # Calculate the time difference time_difference = parsed_timestamp2 - parsed_timestamp1 # Con...
170
146
487
633
from datetime import datetime def get_time_difference(timestamp1, timestamp2): FILL_FUNC_BODYdef parse_interval_to_seconds(interval: str) -> int: units = {"Minutes": 60, "Hours": 3600, "Days": 86400, "Weeks": 604800, "Months": 2592000} interval = ' '.join(interval.split()) value, unit = interval.split(" "...
from datetime import datetime def get_time_difference(timestamp1, timestamp2): FILL_FUNC_BODYdef parse_interval_to_seconds(interval: str) -> int: units = {"Minutes": 60, "Hours": 3600, "Days": 86400, "Weeks": 604800, "Months": 2592000} interval = ' '.join(interval.split()) value, unit = interval.split(" "...
8,063
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/lib/logger.py
50,51
33,79
_make_custom_log_record
Logger
51,53
51,53
class Logger(metaclass=SingletonMeta): def __init__(self, logger_name='Super AGI', log_level=logging.DEBUG): if not hasattr(self, 'logger'): self.logger = logging.getLogger(logger_name) self.logger.setLevel(log_level) self.logger.makeRecord = self._make_custom_log_record ...
class Logger(metaclass=SingletonMeta): def __init__(self, logger_name='Super AGI', log_level=logging.DEBUG): if not hasattr(self, 'logger'): self.logger = logging.getLogger(logger_name) self.logger.setLevel(log_level) self.logger.makeRecord = self._make_custom_log_record ...
return CustomLogRecord(name, level, fn, lno, msg, args, exc_info, func=func, extra=extra, sinfo=sinfo)
return CustomLogRecord(name, level, fn, lno, msg, args, exc_info, func=func, extra=extra, sinfo=sinfo)
11
478
41
519
import logging import inspect class CustomLogRecord(logging.LogRecord): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) frame = inspect.currentframe().f_back while frame: if frame.f_globals['__name__'] != __name__ and frame.f_globals['__name__'] != 'logg...
import logging import inspect class CustomLogRecord(logging.LogRecord): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) frame = inspect.currentframe().f_back while frame: if frame.f_globals['__name__'] != __name__ and frame.f_globals['__name__'] != 'logg...
8,064
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/llms/local_llm.py
35,36
7,93
chat_completion
LocalLLM
46,61
36,61
class LocalLLM(BaseLlm): def __init__(self, temperature=0.6, max_tokens=get_config("MAX_MODEL_TOKEN_LIMIT"), top_p=1, frequency_penalty=0, presence_penalty=0, number_of_results=1, model=None, api_key='EMPTY', context_length=4096): """ Args: model (str): ...
class LocalLLM(BaseLlm): def __init__(self, temperature=0.6, max_tokens=get_config("MAX_MODEL_TOKEN_LIMIT"), top_p=1, frequency_penalty=0, presence_penalty=0, number_of_results=1, model=None, api_key='EMPTY', context_length=4096): """ Args: model (str): ...
try: if self.llm_model is None or self.llm_grammar is None: logger.error("Model not found.") return {"error": "Model loading error", "message": "Model not found. Please check your model path and try again."} else: response = self.llm_model....
""" Call the chat completion. Args: messages (list): The messages. max_tokens (int): The maximum number of tokens. Returns: dict: The response. """ try: if self.llm_model is None or self.llm_grammar is None: ...
62
621
265
886
from superagi.config.config import get_config from superagi.lib.logger import logger from superagi.llms.base_llm import BaseLlm from superagi.helper.llm_loader import LLMLoader class LocalLLM(BaseLlm): def __init__(self, temperature=0.6, max_tokens=get_config("MAX_MODEL_TOKEN_LIMIT"), top_p=1, fr...
from superagi.config.config import get_config from superagi.lib.logger import logger from superagi.llms.base_llm import BaseLlm from superagi.helper.llm_loader import LLMLoader class LocalLLM(BaseLlm): def __init__(self, temperature=0.6, max_tokens=get_config("MAX_MODEL_TOKEN_LIMIT"), top_p=1, fr...
8,065
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/llms/utils/huggingface_utils/tasks.py
31,32
11,43
_validate_params
TaskParameters
32,43
32,43
class TaskParameters: def __init__(self) -> None: self.params = self._generate_params() self._validate_params() def get_params(self, task, **kwargs) -> Dict[str, Union[int, float, bool, str]]: # Return the task parameters and override with any kwargs # This allows us to override...
class TaskParameters: def __init__(self) -> None: self.params = self._generate_params() self._validate_params() def get_params(self, task, **kwargs) -> Dict[str, Union[int, float, bool, str]]: # Return the task parameters and override with any kwargs # This allows us to override...
assert len(self.params) == len(Tasks), "Not all tasks have parameters defined" for task in Tasks: assert task in self.params, f"Task {task} does not have parameters defined" # params = self.params[task] # assert isinstance(params, dict), f"Task {task} parameters are ...
assert len(self.params) == len(Tasks), "Not all tasks have parameters defined" for task in Tasks: assert task in self.params, f"Task {task} does not have parameters defined" # params = self.params[task] # assert isinstance(params, dict), f"Task {task} parameters are ...
73
211
171
382
from enum import Enum from dataclasses import dataclass from typing import List, Dict, Union, Optional # Define an Enum for the different tasks class Tasks(Enum): TEXT_GENERATION = "text-generation" class TaskParameters: def __init__(self) -> None: self.params = self._generate_params() self....
from enum import Enum from dataclasses import dataclass from typing import List, Dict, Union, Optional # Define an Enum for the different tasks class Tasks(Enum): TEXT_GENERATION = "text-generation" class TaskParameters: def __init__(self) -> None: self.params = self._generate_params() self....
8,066
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/resource_manager/resource_summary.py
33,34
13,91
add_to_vector_store_and_create_summary
ResourceSummarizer
43,50
34,50
class ResourceSummarizer: """Class to summarize a resource.""" def __init__(self, session, agent_id: int, model: str): self.session = session self.agent_id = agent_id self.organisation_id = self.__get_organisation_id() self.model = model def __get_organisation_id(self): ...
class ResourceSummarizer: """Class to summarize a resource.""" def __init__(self, session, agent_id: int, model: str): self.session = session self.agent_id = agent_id self.organisation_id = self.__get_organisation_id() self.model = model def __get_organisation_id(self): ...
model_api_key = self.__get_model_api_key() try: ResourceManager(str(self.agent_id)).save_document_to_vector_store(documents, str(resource_id), model_api_key, self.__get_model_source()) except Exception as e: ...
""" Add a file to the vector store and generate a summary for it. Args: agent_id (str): ID of the agent. resource_id (int): ID of the resource. openai_api_key (str): OpenAI API key. documents (list): List of documents. """ model_ap...
21
919
116
1,035
from datetime import datetime import logging from superagi.lib.logger import logger from superagi.models.agent import Agent from superagi.models.agent_config import AgentConfiguration from superagi.models.configuration import Configuration from superagi.models.resource import Resource from superagi.resource_manager.lla...
from datetime import datetime import logging from superagi.lib.logger import logger from superagi.models.agent import Agent from superagi.models.agent_config import AgentConfiguration from superagi.models.configuration import Configuration from superagi.models.resource import Resource from superagi.resource_manager.lla...
8,067
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/tools/apollo/apollo_toolkit.py
16,17
9,18
get_env_keys
ApolloToolkit
17,18
17,18
class ApolloToolkit(BaseToolkit, ABC): name: str = "ApolloToolkit" description: str = "Apollo Tool kit contains all tools related to apollo.io tasks" def get_tools(self) -> List[BaseTool]: return [ApolloSearchTool()] def get_env_keys(self) -> List[str]: FILL_FUNC_BODY
class ApolloToolkit(BaseToolkit, ABC): name: str = "ApolloToolkit" description: str = "Apollo Tool kit contains all tools related to apollo.io tasks" def get_tools(self) -> List[BaseTool]: return [ApolloSearchTool()] def get_env_keys(self) -> List[str]: FILL_FUNC_BODY
return [ToolConfiguration(key="APOLLO_SEARCH_KEY", key_type=ToolConfigKeyType.STRING, is_required=True)]
return [ToolConfiguration(key="APOLLO_SEARCH_KEY", key_type=ToolConfigKeyType.STRING, is_required=True)]
4
102
38
140
from abc import ABC from typing import List from superagi.tools.apollo.apollo_search import ApolloSearchTool from superagi.tools.base_tool import BaseToolkit, BaseTool, ToolConfiguration from superagi.types.key_type import ToolConfigKeyType class ApolloToolkit(BaseToolkit, ABC): name: str = "ApolloToolkit" d...
from abc import ABC from typing import List from superagi.tools.apollo.apollo_search import ApolloSearchTool from superagi.tools.base_tool import BaseToolkit, BaseTool, ToolConfiguration from superagi.types.key_type import ToolConfigKeyType class ApolloToolkit(BaseToolkit, ABC): name: str = "ApolloToolkit" d...
8,068
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI
/home/hieuvd/dung_repo/raw/stars_01/TransformerOptimus_SuperAGI/SuperAGI/superagi/tools/code/coding_toolkit.py
15,16
11,20
get_tools
CodingToolkit
16,18
16,18
class CodingToolkit(BaseToolkit, ABC): name: str = "CodingToolkit" description: str = "Coding Tool kit contains all tools related to coding tasks" def get_tools(self) -> List[BaseTool]: FILL_FUNC_BODY def get_env_keys(self) -> List[ToolConfiguration]: return []
class CodingToolkit(BaseToolkit, ABC): name: str = "CodingToolkit" description: str = "Coding Tool kit contains all tools related to coding tasks" def get_tools(self) -> List[BaseTool]: FILL_FUNC_BODY def get_env_keys(self) -> List[ToolConfiguration]: return []
return [CodingTool(), WriteSpecTool(), WriteTestTool(), ImproveCodeTool()]
return [CodingTool(), WriteSpecTool(), WriteTestTool(), ImproveCodeTool()]
5
93
25
118
from abc import ABC from typing import List from superagi.tools.base_tool import BaseToolkit, BaseTool, ToolConfiguration from superagi.tools.code.improve_code import ImproveCodeTool from superagi.tools.code.write_code import CodingTool from superagi.tools.code.write_spec import WriteSpecTool from superagi.tools.code....
from abc import ABC from typing import List from superagi.tools.base_tool import BaseToolkit, BaseTool, ToolConfiguration from superagi.tools.code.improve_code import ImproveCodeTool from superagi.tools.code.write_code import CodingTool from superagi.tools.code.write_spec import WriteSpecTool from superagi.tools.code....